• Start

v2 (alpha)

/

Concepts

Transactions

Run multiple statements atomically with version 2 of the PHP SDK, using a SurrealQL transaction block or explicit transaction handles.

A transaction groups statements so they either all succeed or all fail. This keeps related changes consistent, for example when transferring a value between two records.

The simplest approach wraps statements in BEGIN TRANSACTION and COMMIT TRANSACTION and runs them as a single query with run(). SurrealDB rolls back the whole block if any statement fails. This works over both WebSocket and HTTP.

$db->run('
    BEGIN TRANSACTION;
    UPDATE account:one SET balance -= 100;
    UPDATE account:two SET balance += 100;
    COMMIT TRANSACTION;
');

Use CANCEL TRANSACTION inside the block, or a THROW expression, to abort and roll back from within SurrealQL.

For finer control over a WebSocket connection, the ConnectionController exposes explicit transaction handles through connection(). Call begin() to start one, then commit() or cancel() with the returned handle.

$txn = $db->connection()->begin();

try {
    // ... run statements bound to $txn ...
    $db->connection()->commit($txn);
} catch (\Throwable $error) {
    $db->connection()->cancel($txn);
    throw $error;
}
Note

Explicit handles require the transactions feature, which depends on the WebSocket engine and a compatible server version. For most applications, a transaction block run with run() is simpler and works everywhere.

Was this page helpful?