Skip to content

Core\Db\Transaction::runTransaction

$transaction->runTransaction(
    callable(Core\Db\Transaction): T $fn,
    {isolation?: Core\Db\Isolation, readOnly?: bool, retries?: uint},
): T

Runs a function as one step inside a transaction that is already open.

Core\Db\Transaction::runTransaction works like the method with the same name on a connection. It takes a function, runs it, and returns what the function returned. The inner transaction is a savepoint. When you call rollBack on it, only its own changes are undone. The outer transaction continues and can still save its own work. When nothing is undone, all changes are saved together when the outer transaction ends.

In plain words: the inner transaction is one step of a bigger job. When one step fails, you can undo that step and keep the job.

This is useful for a function that needs a transaction for its own writes. The function can open one without checking whether its caller already has one open.

Good to know: the isolation level and readOnly are set for the whole transaction. An inner call that sets one of them throws a LogicError. Set them on the outermost call.

The examples below undo one step and keep the others, let a function open its own transaction, and keep an order when its coupon cannot be used.

Parameters

  • $fncallable(Core\Db\Transaction): TThe work to run. It gets a Core\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 is false. A nested call cannot set it, for the same reason as isolation.
  • retriesuintoptionalHow many times $fn runs again when the commit reports a deadlock or a serialization failure. This applies to the outermost transaction only. The default is 0, 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 $fn is 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$fn called rollBack. This call throws it even if code inside $fn caught it, because the rollback is recorded on the transaction itself.
  • LogicErrorA statement inside $fn was not allowed because of the way it was written. It is also thrown when the transaction is used after its runTransaction() call returned, or when a nested call sets its own isolation or readOnly.
  • Core\Db\DbErrorThe server rejected the BEGIN, or rejected the COMMIT after $fn returned, 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

VersionChange
0.0.6queryEach 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.

nvs.toml
# 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"]

Undo one step and keep the rest

<?nvs
// Shows a transaction opened inside another transaction. Giving up on the inner
// one undoes only what that one wrote, and the work around it is still saved.
use Core\Db\RolledBack;
use Core\Db\Transaction;
var $db = Core\Db::connect('notes');
$db->execute('create table notes (id integer primary key, text text not null)', []);
$db->runTransaction(fn(Transaction $work): void => {
$work->execute('insert into notes (text) values (?)', ['buy milk']);
try {
// A second transaction inside the first one. It is one step of the work,
// with its own end.
$work->runTransaction(fn(Transaction $step): void => {
$step->execute('insert into notes (text) values (?)', ['call Ana']);
$step->rollBack('this note is not wanted');
});
} catch (RolledBack $gaveUp) {
// This prints `gave up: this note is not wanted`.
echo 'gave up: ', $gaveUp->reason, "\n";
}
$work->execute('insert into notes (text) values (?)', ['book train']);
});
// The step's note is gone and the two around it are kept. This prints
// `buy milk` and `book train`.
foreach ($db->query('select text from notes order by id', []) as Core\Db\Row $row) {
echo $row->string('text') ?? '', "\n";
}
$db->close();
Output
gave up: this note is not wanted
buy milk
book train

Let a function open its own transaction

<?nvs
// Shows a function that opens a transaction of its own while the caller already
// has one open. Both writes are one unit of work, and neither side needs to
// know what the other did.
use Core\Db\Transaction;
var $db = Core\Db::connect('notes');
$db->execute('create table notes (id integer primary key, text text not null)', []);
$db->execute('create table events (id integer primary key, what text not null)', []);
class Audit
{
// The parameter is a `Core\Db\Transaction`, so this function runs inside the
// caller's transaction. Its own `runTransaction` call is one step of it.
public static function record(Transaction $tx, string $what): void
{
$tx->runTransaction(fn(Transaction $step): void => {
$step->execute('insert into events (what) values (?)', [$what]);
});
}
}
$db->runTransaction(fn(Transaction $work): void => {
$work->execute('insert into notes (text) values (?)', ['buy milk']);
Audit::record($work, 'a note was written');
});
// Both rows are saved together. This prints `1 note` and `1 event`.
echo $db->query('select id from notes', [])->count(), " note\n";
echo $db->query('select id from events', [])->count(), " event\n";
$db->close();
Output
1 note
1 event

Keep the order when the coupon fails

<?nvs
// Shows the work a program really does here: an order is saved, and a coupon is
// applied in a step of its own. A coupon that is used up costs the order
// nothing.
use Core\Db\RolledBack;
use Core\Db\Transaction;
var $db = Core\Db::connect('notes');
$db->execute('create table orders (id integer primary key, email text not null, cents int not null)', []);
$db->execute('create table coupons (code text not null, remaining int not null)', []);
$db->execute('insert into coupons (code, remaining) values (?, ?), (?, ?)', ['SPRING', 3, 'GONE', 0]);
class Checkout
{
public static function place(Core\Db\Connection $db, string $email, int $cents, string $code): void
{
$db->runTransaction(fn(Transaction $order): void => {
$order->execute('insert into orders (email, cents) values (?, ?)', [$email, $cents]);
try {
// The discount is a step inside the order. Both writes it makes
// are undone together if the coupon turns out to be used up.
$order->runTransaction(fn(Transaction $step): void => {
$step->execute('update coupons set remaining = remaining - 1 where code = ?', [$code]);
$step->execute('update orders set cents = cents - 500 where email = ?', [$email]);
var $coupon = $step->query('select remaining from coupons where code = ?', [$code])->first();
if (($coupon?->int('remaining') ?? -1) < 0) {
$step->rollBack('the coupon ' . $code . ' is used up');
}
});
} catch (RolledBack $noDiscount) {
// This prints `no discount: the coupon GONE is used up`. The
// order around this step is still saved.
echo 'no discount: ', $noDiscount->reason, "\n";
}
});
}
}
Checkout::place($db, 'ana@example.com', 4000, 'SPRING');
Checkout::place($db, 'bo@example.com', 4000, 'GONE');
// Both orders are there, and only the first one was given the discount. This
// prints `ana@example.com: 3500` and `bo@example.com: 4000`.
foreach ($db->query('select email, cents from orders order by id', []) as Core\Db\Row $row) {
echo $row->string('email') ?? '', ': ', $row->int('cents') ?? 0, "\n";
}
$db->close();
Output
no discount: the coupon GONE is used up
ana@example.com: 3500
bo@example.com: 4000