Skip to content

Core\Db\RolledBack

The error that is thrown when a program gives up on a transaction it started.

Core\Db\Connection::runTransaction runs a function. If the function returns, the work is saved. If it throws, the work is undone.

Code inside the function calls rollBack when the work should not be saved. Examples are a basket whose total is wrong, or a stock count that would go below zero. rollBack records the reason and throws this error with it. The runTransaction call throws the error again, even when code inside the function caught it.

So the code that called runTransaction always learns two things: nothing was written, and why. The reason is a sentence your program wrote. You read it as the reason property or as the error's message, so a log line and an if see the same words.

Good to know: this error is your program's own decision. When the database rejects a statement, the error is Core\Db\DbError. Neither class extends the other, so a catch for one never catches the other.

Examples

The examples below run with this configuration file.

nvs.toml
# The `schema` database is kept in memory. It is deleted when the program ends.
[db.schema]
driver = "sqlite"
path = ":memory:"
# The second example opens no database. The other two may open the `schema` database.
[[app]]
entry = "01-giving-up-on-a-batch.nvs"
[app.capabilities.db]
connect = ["schema"]
[[app]]
entry = "03-a-checkout-that-says-why.nvs"
[app.capabilities.db]
connect = ["schema"]

Giving up on a batch

<?nvs
// A transaction runs a callable. If it returns, the work is kept. If it throws,
// the work is undone. This one reads part-way through that the batch has a
// reading no thermometer could have produced, and gives up on all of it.
use Core\Db;
use Core\Db\RolledBack;
use Core\Db\Transaction;
var $db = Db::connect('schema');
$db->execute('create table readings (id integer primary key, celsius int not null)', []);
array<int> $batch = [19, 21, -400, 23];
try {
$db->runTransaction(fn(Transaction $tx): void => {
foreach ($batch as int $celsius) {
if ($celsius < -273) {
$tx->rollBack('a reading below absolute zero is in the batch');
}
$tx->execute('insert into readings (celsius) values (?)', [$celsius]);
}
});
echo "the batch was kept\n";
} catch (RolledBack $abandoned) {
echo 'gave up: ', $abandoned->reason, "\n";
}
// The two good readings before the bad one are gone as well. That is the point
// of asking for the whole batch at once.
echo 'rows kept: ', $db->query('select id from readings', [])->count(), "\n";
Output
gave up: a reading below absolute zero is in the batch
rows kept: 0

What the rollback tells you

<?nvs
// This program shows what a `RolledBack` error contains, and which `catch` block
// catches it. It does not open a database.
use Core\Db\RolledBack;
// `reason` is the text the program gave when it rolled back.
// `message` is the same text.
try {
throw new RolledBack('the basket no longer adds up');
} catch (RolledBack $abandoned) {
echo 'reason: ', $abandoned->reason, "\n";
echo 'message: ', $abandoned->message, "\n";
}
// A rollback is not a bug in the code, so `RolledBack` is a `RuntimeError`.
// This prints `a RuntimeError clause`.
try {
throw new RolledBack('the stock would have gone negative');
} catch (LogicError $notAMistake) {
echo "a LogicError clause\n";
} catch (RuntimeError $theWorldSaidNo) {
echo "a RuntimeError clause\n";
}
// A `DbError` is not a `RolledBack`, so the first `catch` block does not catch it.
// This prints `not a RolledBack clause`.
try {
throw new Core\Db\DbError('the server refused the statement');
} catch (RolledBack $notARollback) {
echo "a RolledBack clause\n";
} catch (RuntimeError $aRefusal) {
echo "not a RolledBack clause\n";
}
Output
reason: the basket no longer adds up
message: the basket no longer adds up
a RuntimeError clause
not a RolledBack clause

A checkout that says why

<?nvs
// Placing an order in a shop. The transaction reads the stock and checks it.
// If a check fails, `$tx->rollBack` stops the transaction and throws `RolledBack`.
// The text given to `rollBack` is the message the shop shows the customer.
use Core\Db;
use Core\Db\Connection;
use Core\Db\RolledBack;
use Core\Db\Transaction;
final class Checkout
{
public static function place(Connection $db, string $sku, int $wanted): string
{
try {
$db->runTransaction(fn(Transaction $tx): void => {
var $row = $tx->query('select stock from items where sku = ?', [$sku])->first();
if ($row == null) {
$tx->rollBack('we do not stock that item');
}
var $stock = $row?->int('stock');
if ($stock == null || $stock < $wanted) {
$tx->rollBack('we do not have that many left');
}
$tx->execute('update items set stock = stock - ? where sku = ?', [$wanted, $sku]);
$tx->execute('insert into orders (sku, quantity) values (?, ?)', [$sku, $wanted]);
});
return 'ordered';
} catch (RolledBack $abandoned) {
// The transaction wrote nothing. `reason` is the text of the check
// that failed.
return $abandoned->reason;
}
}
}
var $db = Db::connect('schema');
$db->execute('create table items (sku text not null primary key, stock int not null)', []);
$db->execute('create table orders (id integer primary key, sku text not null, quantity int not null)', []);
$db->execute("insert into items (sku, stock) values ('mug', 4)", []);
echo Checkout::place($db, 'mug', 3), "\n";
echo Checkout::place($db, 'mug', 3), "\n";
echo Checkout::place($db, 'kettle', 1), "\n";
echo 'orders placed: ', $db->query('select id from orders', [])->count(), "\n";
Output
ordered
we do not have that many left
we do not stock that item
orders placed: 1