Core\Db\Connection::runTransaction
$connection->runTransaction(
callable(Core\Db\Transaction): T $fn,
{isolation?: Core\Db\Isolation, readOnly?: bool, retries?: uint},
): TRuns your work inside a database transaction.
Core\Db\Connection::runTransaction takes a function and runs it. Your function is given a Core\Db\Transaction, which has the same query, execute and executeMany methods a connection has. When the function returns, the work is committed, and runTransaction returns what the function returned. When the function throws an error, the work is rolled back, and runTransaction throws the same error.
There is no method that begins, commits or rolls back a transaction on its own, so a transaction cannot be left open by an early return.
Inside the function, Core\Db\Transaction::rollBack gives up. It takes a reason and throws Core\Db\RolledBack with that reason.
A second runTransaction inside the first is a savepoint. Giving up on the inner one undoes only its own work, so a program can skip one bad row and keep the rest.
You can also name an isolation level, ask for a read-only transaction, and set how many times a deadlock may re-run the function.
The examples move money between two accounts, give up on an order that cannot be filled, and import a list where one row is bad.
Parameters
$fncallable(Core\Db\Transaction): TThe work to run. It gets aCore\Db\Transaction, which has the same query methods as the connection. The function may declare that parameter or no parameter.
Options
isolationCore\Db\IsolationoptionalHow much this transaction can see of other transactions running at the same time. Without it, the transaction uses the level set on the server. A nested call cannot set it. The level is for the whole transaction, not for a savepoint inside it.readOnlybooloptionalWrites are not allowed during the transaction, so the server can plan for reads only. The default isfalse. A nested call cannot set it, for the same reason asisolation.retriesuintoptionalHow many times$fnruns again when the commit reports a deadlock or a serialization failure. This applies to the outermost transaction only. The default is0, because a function with side effects should run again only when you ask for it. Nothing else is retried, and there is no wait between attempts. A conflict from a statement inside$fnis thrown and not retried.
Return value
Returns T. What $fn returned, after the commit. A nested call on the same connection is a savepoint. So you can call a function that wraps its own writes in a transaction from inside another transaction.
Errors
Core\Db\RolledBack$fncalledrollBack. This call throws it even if code inside$fncaught it, because the rollback is recorded on the transaction itself.LogicErrorA statement inside$fnwas not allowed because of the way it was written. It is also thrown when the transaction is used after itsrunTransaction()call returned, or when a nested call sets its ownisolationorreadOnly.Core\Db\DbErrorThe server rejected theBEGIN, or rejected theCOMMITafter$fnreturned, for example for a serialization failure or a deferred constraint. In both cases nothing is committed.IOErrorThe connection failed while the transaction was open. The connection cannot be used for the rest of the request.
Changelog
| Version | Change |
|---|---|
0.0.6 | queryEach and queryEachAs run a query and read its rows one at a time. runTransaction runs a function in a transaction, and Core\Db\Column->isNullable() checks a column. The old names were stream, streamAs, transaction and nullable. |
Examples
The examples below run with this configuration file.
# The `notes` database is kept in memory. It is deleted when the program ends.[db.notes]driver = "sqlite"path = ":memory:"
# The program may open the `notes` database.[capabilities.db]connect = ["notes"]Do both writes or neither
<?nvs// Shows how to move money between two accounts. Both rows change together,// because both writes run inside one transaction.
var $db = Core\Db::connect('notes');$db->execute('create table accounts (id integer primary key, owner text not null, balance integer not null)', []);$db->execute('insert into accounts (owner, balance) values (?, ?), (?, ?)', ['Ada', 100, 'Ben', 20]);
// Your function runs inside a transaction. When it returns, both writes are// saved together. When it throws an error, neither of them is saved.uint $moved = $db->runTransaction(fn(Core\Db\Transaction $tx): uint => { $tx->execute('update accounts set balance = balance - ? where owner = ?', [30, 'Ada']); $tx->execute('update accounts set balance = balance + ? where owner = ?', [30, 'Ben']); return 30;});
// `runTransaction` returns what your function returned. This prints `moved 30`,// then `Ada 70` and `Ben 50`.echo 'moved ', $moved, "\n";foreach ($db->query('select owner, balance from accounts order by id', [])->all() as Core\Db\Row $row) { echo $row->string('owner') ?? '', ' ', $row->int('balance') ?? 0, "\n";}
$db->close();moved 30Ada 70Ben 50Give up on the work
<?nvs// Shows how to give up on a transaction. `Core\Db\Transaction::rollBack` takes// a reason and throws `Core\Db\RolledBack`. Nothing your function wrote is kept.
var $db = Core\Db::connect('notes');$db->execute('create table orders (id integer primary key, item text not null)', []);
try { $db->runTransaction(fn(Core\Db\Transaction $tx): void => { $tx->execute('insert into orders (item) values (?)', ['a red bicycle']); // The item turned out to be sold out, so this order must not be kept. $tx->rollBack('the item is sold out'); });} catch (Core\Db\RolledBack $abandoned) { // The reason you gave is the error's `reason`. This prints // `gave up: the item is sold out`. echo 'gave up: ', $abandoned->reason, "\n";}
// The row your function wrote is gone. This prints `0 orders`.echo $db->query('select id from orders', [])->count(), " orders\n";
$db->close();gave up: the item is sold out0 ordersKeep the import when one row is bad
<?nvs// Shows an import that skips a bad row and keeps the good ones. A transaction// inside a transaction is a savepoint, so giving up on one row does not give// up on the whole import.
var $db = Core\Db::connect('notes');$db->execute('create table people (id integer primary key, name text not null)', []);
array<string> $names = ['Ada', '', 'Ben'];
$db->runTransaction(fn(Core\Db\Transaction $import): void => { foreach ($names as string $name) { try { // One row, in its own transaction inside the import. $import->runTransaction(fn(Core\Db\Transaction $row): void => { $row->execute('insert into people (name) values (?)', [$name]); if ($name == '') { $row->rollBack('the name is empty'); } }); } catch (Core\Db\RolledBack $skipped) { // Only this row is undone. This prints `skipped: the name is empty`. echo 'skipped: ', $skipped->reason, "\n"; } }});
// The two good rows were kept. This prints `Ada` and `Ben`.foreach ($db->query('select name from people order by id', [])->all() as Core\Db\Row $row) { echo $row->string('name') ?? '', "\n";}
$db->close();skipped: the name is emptyAdaBen