Skip to content

Core\Db\Transaction::execute

$transaction->execute(
    string $sql,
    array<mixed> $params,
    {timeout?: Core\Time\Duration},
): Core\Db\Write

Runs one statement inside a transaction, and says what it did.

Core\Db\Transaction::execute is the method for an insert, an update, a delete or a create table inside the work you passed to Core\Db\Connection::runTransaction. It returns a Core\Db\Write. That object says how many rows changed, and it gives the id the database made for a new row. The method is the same one the connection has, so a statement you already wrote does not change when you move it inside a transaction.

What changes is when the write is kept. Every write of one transaction is saved together, at the moment your function returns. If your function throws an error, or calls Core\Db\Transaction::rollBack, none of them is saved.

A value never goes into the text of the statement. Write a ? for each value, or a :name for each, and pass the values as the second argument.

The examples write one row and read what it did, give up on a write, and save an order together with the lines that belong to it.

Parameters

  • $sqlstringThe statement, with a ? or a :name for each value. Never write a value into the text. A tainted string does not compile here, and no escape function can make one allowed.
  • $paramsarray<mixed>The values to bind. Use list keys for ? and string keys for :name, and never both in one array. This is the same rule as in query.

Options

  • timeoutCore\Time\DurationoptionalHow long this statement may take. The limit covers the whole statement: the prepare, the execution and every row of the result. When the time passes, the statement stops with an IOError. The connection cannot be used again, because it stopped in the middle of a message. Without it, the statement waits as long as the server takes.

Return value

Returns Core\Db\Write. A Core\Db\Write with the number of affected rows as the server reported it, and the id that a RETURNING clause returned. Any rows the statement returned are read and discarded, so the connection is free again. Use query to keep rows.

Errors

  • LogicErrorThe call is wrong, not the database. The placeholders and the array use different styles or different counts, or a :name has no element. It is also thrown for an element that cannot be bound, such as an array or an object that is not an inList. A statement already streaming on this connection throws it too.
  • Core\Db\DbErrorThe server rejected the statement, for example for a syntax error, a constraint or a permission. The error has the server's SQLSTATE and message.
  • IOErrorThe connection failed while the statement was running, or timeout passed before it finished. The connection cannot be used for the rest of the request.

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"]

Write a row inside a transaction

<?nvs
// Shows a write inside a transaction. The method returns a `Core\Db\Write`,
// which says how many rows changed and what id the new row was given.
var $db = Core\Db::connect('notes');
$db->execute('create table notes (id integer primary key, text text not null)', []);
$db->runTransaction(fn(Core\Db\Transaction $tx): void => {
var $written = $tx->execute('insert into notes (text) values (?)', ['buy milk']);
// This prints `1 row written, id 1`.
echo $written->affected(), ' row written, id ', $written->lastId() ?? 0, "\n";
});
// The transaction is over, so the row is saved. This prints `1 note`.
echo $db->query('select id from notes', [])->count(), " note\n";
$db->close();
Output
1 row written, id 1
1 note

Give up on a write

<?nvs
// Shows a write that is not kept. A row written inside a transaction is saved
// only when the work finishes. Here the work gives up, so the row is removed.
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 => {
var $written = $tx->execute('insert into orders (item) values (?)', ['a red bicycle']);
// The write reports one row. This prints `1 row written`.
echo $written->affected(), " row written\n";
// 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) {
// This prints `gave up: the item is sold out`.
echo 'gave up: ', $abandoned->reason, "\n";
}
// The row the write reported is gone. This prints `0 orders`.
echo $db->query('select id from orders', [])->count(), " orders\n";
$db->close();
Output
1 row written
gave up: the item is sold out
0 orders

Save an order with its lines

<?nvs
// Shows an order saved together with the lines that belong to it. The second
// write needs the id of the first row. A line without its order would be
// wrong, so every write runs inside one transaction.
var $db = Core\Db::connect('notes');
$db->execute('create table orders (id integer primary key, customer text not null)', []);
$db->execute('create table lines (id integer primary key, orderId integer not null, item text not null)', []);
array<string> $items = ['a red bicycle', 'a bell', 'a lamp'];
$db->runTransaction(fn(Core\Db\Transaction $tx): void => {
var $order = $tx->execute('insert into orders (customer) values (?)', ['Ada']);
// `lastId` gives the id the database made for the new order.
var $orderId = $order->lastId() ?? 0;
foreach ($items as string $item) {
$tx->execute('insert into lines (orderId, item) values (?, ?)', [$orderId, $item]);
}
});
// Order and lines were saved together. This prints `order 1 has 3 lines`.
foreach ($db->query('select id from orders', []) as Core\Db\Row $order) {
echo 'order ', $order->int('id') ?? 0, ' has ',
$db->query('select id from lines where orderId = ?', [$order->int('id') ?? 0])->count(),
" lines\n";
}
$db->close();
Output
order 1 has 3 lines