Skip to content

Transactions

Glynn Quelch edited this page Feb 9, 2022 · 2 revisions

It is possible to create a transactional query, with automatic COMMIT and ROLLBACK. Making the possibility of creating a complex query, with less risk.

/**
 * Runs a transaction
 *
 * @param Closure(Transaction):void $callback
 *
 * @return QueryBuilderHandler
 */
public function transaction(Closure $callback): QueryBuilderHandler

The passed closure is injected an extended version of the query builder. This allows for the manual committing and rollback of the transaction.

function (Transaction $transaction): void{

    // Do your operations.
    $response = $transaction->table('foo')->insert([...]);

    // Once done, commit the transaction
    $transaction->commit();

    // If anything has gone wrong, rollback the transaction.
    $transaction->rollBack();
}

The use of commit and rollback methods is required. If an exception is raised, or wpdb prints to the screen. The transaction is automatically rolled back.

It is advised to set the connection as both as clone of wpdb and showing errors.

example

QB::transaction(function(Transaction $transaction) use ($something): void {

    // Create the initial row
    $saleId = $transaction->table('sale')->insert($something->saleData);

    // Check inserted, catching exceptions to rollback
    if(null === $saleId) {
        throw Exception("Failed to insert sale record, rolling back transaction");
    }

    // Create row in reference.
    $refData = $something->getReferenceModel()
        ->setSaleRef($saleId)
        ->toArray();
    $refId = $transaction->table('sale_ref')->insert($refData);

    // Check inserted, manually rollback
    if(null === $refId) {
        $transaction->rollBack();
    }

});