Skip to content

PHP library and ORM to handle DB connection, apply C.R.U.D. operations

License

Notifications You must be signed in to change notification settings

larapulse/database

Repository files navigation

Database

Latest Version on Packagist Software License Build Status Coverage Status Quality Score

PHP library and ORM to handle DB connection, apply C.R.U.D. operations.

Install

Via Composer

$ composer require thephpleague/database

Usage

$config = [
    'host'      => 'localhost',
    'port'      => 3306,
    'database'  => 'master_db',
    'username'  => 'root',
    'password'  => '',
];

$connection = new League\Database\ConnectionManager('core', $config);

BulkSql usage

Bulk SQL classes could be useful in scripts, when you need to insert big amount of records.

Example 1:

`BulkInsert` usage
use League\Database\BulkSql\BulkInsert;

$db = $connection->getMasterConnection();

$bulkInsert = new BulkInsert($db, 'users');
$bulkInsert
    ->setItemsPerQuery(50)
    ->useIgnore()
    ->disableIndexes();

try {
    $db->beginTransaction();
    
    foreach ($users as $user) {
        $bulkInsert->add($user);
    }
    
    $bulkInsert->finish();
    $affectedCount = $bulkInsert->getAffectedCount();
    
    $db->commit();
} catch (\PDOException $e) {
    $db->rollBack();
}

Example 2:

`BulkReplace` and `BulkDelete` usage (could be useful with feeds)
use League\Database\BulkSql\BulkReplace;
use League\Database\BulkSql\BulkDelete;

$db = $connection->getMasterConnection();

$bulkReplace = new BulkReplace($db, 'offers');
$bulkReplace->setItemsPerQuery(500);
$bulkDelete = new BulkDelete($db, 'offers');
$bulkDelete->setItemsPerQuery(1000);

try {
    $db->beginTransaction();
    
    foreach ($offers as $offer) {
        $flag = $offer['deltaStatus'] ?? null;
        
        switch ($delta) {
            case 'REMOVE':
                $bulkDelete->add(['id' => $data['id']]);
                break;
            case 'ADD':
                $bulkReplace->add($data);
                break;
            default:
                $logger->notice("Unsupported delta flag \"{$flag}\"";
        }
    }

    $bulkReplace->finish();
    $bulkDelete->finish();
    
    $db->commit();
    
    $insertsCount = $bulkReplace->getInsertedCount();
    $updatesCount = $bulkReplace->getReplacedCount();
    $deletesCount = $bulkDelete->getAffectedCount();
} catch (\PDOException $e) {
    $db->rollBack();
}

Change log

Please see CHANGELOG for more information on what has changed recently.

Testing

$ composer test

Contributing

Please see CONTRIBUTING and CODE_OF_CONDUCT for details.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.