Core\Db\Transaction::query
$transaction->query(
string $sql,
array<mixed> $params,
{timeout?: Core\Time\Duration},
): Core\Db\Rows<Core\Db\Row>Runs one statement that reads rows inside a transaction, and returns all of them.
Core\Db\Transaction::query is the method for a select inside the work you passed to Core\Db\Connection::runTransaction. It returns a Core\Db\Rows object. A foreach over that object reads one row at a time, count() gives the number of rows, and first() gives the first row or null. 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 what the read sees. Every row the transaction has written is already there, before the transaction ends. Nobody else sees those rows until it does.
Every row is read into memory before the method returns, so you can write inside the loop that reads them. 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 read what the transaction just wrote, write while reading the rows, and let a read decide whether the work is kept.
Parameters
$sqlstringThe statement, with a?or a:namefor each value. Never write a value into the text. Ataintedstring 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. ACore\Db::inListelement expands into several placeholders at its position. Nothing else expands.
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 anIOError. 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\Rows<Core\Db\Row>. A Core\Db\Rows<Core\Db\Row> with every row the statement returned, in the server's order. A statement that returns no rows, such as an update or a create table, gives an empty result. It is not an error.
Errors
LogicErrorThe call is wrong, not the database. The placeholders and the array use different styles or different counts, or a:namehas no element. It is also thrown for an element that cannot be bound, such as an array or an object that is not aninList. 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'sSQLSTATEand message. It is also thrown for a column type this driver cannot read yet.IOErrorThe connection failed while the statement was running, ortimeoutpassed before it finished. The connection cannot be used for the rest of the request.
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"]Read what the transaction just wrote
<?nvs// Shows a `select` inside a transaction. The rows the transaction has written// are already there when you read them, before the transaction ends.
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 => { $tx->execute('insert into notes (text) values (?), (?)', ['buy milk', 'call Ana']);
// `query` returns every row of the statement. The two rows above are part // of this transaction, so this prints both of them. foreach ($tx->query('select id, text from notes order by id', []) as Core\Db\Row $row) { echo $row->int('id') ?? 0, ': ', $row->string('text') ?? '', "\n"; }});
// The transaction is over, so the rows are saved. This prints `2 notes`.echo $db->query('select id from notes', [])->count(), " notes\n";
$db->close();1: buy milk2: call Ana2 notesWrite while you read the rows
<?nvs// Shows a loop that reads rows and writes one statement per row. `query` reads// every row into memory before it returns, so the transaction is free for the// next statement while you are still reading them.
var $db = Core\Db::connect('notes');$db->execute('create table tasks (id integer primary key, title text not null, done int not null)', []);$db->execute('insert into tasks (title, done) values (?, 0), (?, 0), (?, 0)', ['pack', 'label', 'ship']);
$db->runTransaction(fn(Core\Db\Transaction $tx): void => { var $open = $tx->query('select id, title from tasks where done = 0 order by id', []);
// Each round reads one row and writes with it. Both statements run on the // same transaction, so all three updates are saved together. foreach ($open as Core\Db\Row $row) { $tx->execute('update tasks set done = 1 where id = ?', [$row->int('id') ?? 0]); echo 'done: ', $row->string('title') ?? '', "\n"; }});
// This prints `3 of 3 done`.echo $db->query('select id from tasks where done = 1', [])->count(), ' of ', $db->query('select id from tasks', [])->count(), " done\n";
$db->close();done: packdone: labeldone: ship3 of 3 doneLet a read decide whether to keep the work
<?nvs// Shows an order that is only kept when the stock is there: the transaction// writes first, reads what it wrote, and gives up when the read says no.
var $db = Core\Db::connect('notes');$db->execute('create table stock (item text primary key, left int not null)', []);$db->execute('insert into stock (item, left) values (?, ?)', ['lamp', 2]);
var $order = fn(string $item, int $count): string => { try { $db->runTransaction(fn(Core\Db\Transaction $tx): void => { $tx->execute('update stock set left = left - ? where item = ?', [$count, $item]);
// The update is part of this transaction, so this read sees the new // number. A negative number means the order was too large. int $left = $tx->query('select left from stock where item = ?', [$item])->first()?->int('left') ?? 0; if ($left < 0) { $tx->rollBack('not enough in stock'); } }); } catch (Core\Db\RolledBack $gone) { return 'no: ' . $gone->reason; } return 'yes';};
// This prints `yes`, then `no: not enough in stock`.echo $order('lamp', 2), "\n";echo $order('lamp', 1), "\n";
// The second order changed nothing, so this prints `left: 0`.echo 'left: ', $db->query('select left from stock where item = ?', ['lamp'])->first()?->int('left') ?? 0, "\n";
$db->close();yesno: not enough in stockleft: 0