Core\Db\Transaction::rollBack
Gives up on a transaction. Nothing the transaction wrote is saved, and the reason you give reaches whoever catches the failure.
Core\Db\Transaction::rollBack takes one argument, the reason, and throws Core\Db\RolledBack. The reason becomes that error's reason property and its message, so write it for the person who reads the error. Nothing after the call runs, and none of the statements the transaction ran are kept.
Because the method throws, no other code has to check whether the transaction was given up. A function that your work calls can give up on the whole transaction by itself. The functions between it and Core\Db\Connection::runTransaction do not need to return anything for this.
Catch Core\Db\RolledBack around the call to Core\Db\Connection::runTransaction to handle it. Catching it inside the work does not save anything: the transaction is already given up by then.
The examples give up when a check fails, and give up from inside a function. The last one moves money between two accounts only when the first one can pay.
Parameters
$reasonstringWhy the work is stopped. It becomes thereasonproperty and the message of the thrownRolledBack, so write it for the person who reads the error.
Return value
Returns void. Nothing. This method always throws.
Errors
Core\Db\RolledBackAlways. TherunTransaction()call throws it even if code between here and there catches it, because that call checks the recorded reason, not the thrown error.LogicErrorThe transaction is used after itsrunTransaction()call returned, so there is nothing left to roll back.
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"]Give up when a check fails
<?nvs// Shows how to give up on a transaction. `rollBack` throws, so nothing after it// runs and none of the writes are 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)', []);
try { $db->runTransaction(fn(Transaction $tx): void => { $tx->execute('insert into notes (text) values (?)', ['buy milk']);
string $text = ''; if (Core\Str::length($text) == 0) { // The text you pass becomes the error's `reason`. Write it for the // person who reads the failure. $tx->rollBack('a note with no text was given'); }
echo "this line never runs\n"; });} catch (RolledBack $gaveUp) { // This prints `gave up: a note with no text was given`. echo 'gave up: ', $gaveUp->reason, "\n";}
// The insert above was part of the transaction, so it is gone. This prints// `0 notes`.echo $db->query('select id from notes', [])->count(), " notes\n";
$db->close();gave up: a note with no text was given0 notesGive up from inside a function
<?nvs// Shows that the work can be given up from anywhere it reaches. `rollBack`// throws, so a function deep inside the work stops the whole transaction. The// code around it needs no return value and no flag to check.use Core\Db\RolledBack;use Core\Db\Transaction;
class Cart{ // This function stops the transaction itself. It returns `void`, so nothing // that calls it has to pass an answer back up. public static function addItem(Transaction $tx, string $item, int $count): void { if ($count <= 0) { $tx->rollBack('the order asked for ' . $count . ' of ' . $item); } $tx->execute('insert into items (item, count) values (?, ?)', [$item, $count]); }}
var $db = Core\Db::connect('notes');$db->execute('create table items (id integer primary key, item text not null, count int not null)', []);
try { $db->runTransaction(fn(Transaction $tx): void => { Cart::addItem($tx, 'Coffee', 2); Cart::addItem($tx, 'Tea', 0); echo "this line never runs\n"; });} catch (RolledBack $gaveUp) { // This prints `gave up: the order asked for 0 of Tea`. echo 'gave up: ', $gaveUp->reason, "\n";}
// The coffee was written before the second call, and it is gone with the rest.// This prints `0 items`.echo $db->query('select id from items', [])->count(), " items\n";
$db->close();gave up: the order asked for 0 of Tea0 itemsMove money between two accounts
<?nvs// Shows the work a program really does here: money moves from one account to// another, and the whole move is given up if the first account cannot pay.use Core\Db\RolledBack;use Core\Db\Transaction;
var $db = Core\Db::connect('notes');$db->execute('create table accounts (id integer primary key, owner text not null, cents int not null)', []);$db->execute('insert into accounts (owner, cents) values (?, ?), (?, ?)', ['Ana', 5000, 'Bo', 1200]);
class Bank{ public static function move(Core\Db\Connection $db, int $from, int $to, int $cents): void { $db->runTransaction(fn(Transaction $tx): void => { $tx->execute('update accounts set cents = cents - ? where id = ?', [$cents, $from]); $tx->execute('update accounts set cents = cents + ? where id = ?', [$cents, $to]);
// Both updates have run. The check comes after them, so it reads the // balance the move would leave behind. var $left = $tx->query('select cents from accounts where id = ?', [$from])->first(); if (($left?->int('cents') ?? 0) < 0) { // Neither update is saved, because both are part of this // transaction. $tx->rollBack('account ' . $from . ' is short by ' . (0 - ($left?->int('cents') ?? 0)) . ' cents'); } }); }}
// This move fits, so it is saved.Bank::move($db, 1, 2, 2000);
// This one does not.try { Bank::move($db, 2, 1, 999999);} catch (RolledBack $gaveUp) { // This prints `gave up: account 2 is short by 996799 cents`. echo 'gave up: ', $gaveUp->reason, "\n";}
// Only the first move is in the table. This prints `Ana: 3000` and `Bo: 3200`.foreach ($db->query('select owner, cents from accounts order by id', []) as Core\Db\Row $row) { echo $row->string('owner') ?? '', ': ', $row->int('cents') ?? 0, "\n";}
$db->close();gave up: account 2 is short by 996799 centsAna: 3000Bo: 3200