The transaction() method in the LibSQL PHP Extension initiates a new database transaction, allowing multiple SQL statements to be executed as an atomic unit of work. This method provides control over transaction behavior, such as deferred or immediate transaction initiation.

Method Signature

public function transaction(string $behavior = "DEFERRED"): LibSQLTransaction

Parameters

  • $behavior (string): Optional. Specifies the behavior of the transaction. Possible values are "DEFERRED", "READ", or "WRITE". Default is "DEFERRED".

Return Value

  • LibSQLTransaction: Returns a transaction object that can be used to manage the transaction.

Example

// Create a new LibSQL instance
$db = new LibSQL("database.db");

// Start a new transaction with default behavior
$transaction = $db->transaction();

$transaction->execute("UPDATE users SET name = 'Glauber Costa' WHERE id = 6");

$another_transaction = true;

if ($another_transaction) {
    $transaction->commit();
    echo "Transaction commited!" . PHP_EOL;
} else {
    $transaction->rollback();
    echo "Transaction rollback!" . PHP_EOL;
}

Notes

  • Transactions ensure data integrity by allowing a series of SQL statements to be treated as a single unit of work, either all succeeding or all failing.
  • The $behavior parameter determines the concurrency control behavior of the transaction:
    • "DEFERRED" delays the acquisition of database locks until they are needed
    • "WRITE" acquires locks as soon as the transaction begins
    • "READ" prevents other transactions from accessing the database until the transaction completes.
  • Always commit or rollback transactions after their execution to release locks and maintain database consistency.
  • Handle exceptions and errors appropriately within transaction blocks to ensure proper error recovery and transaction management.

See also