Skip to content

Core\Db\Transaction::queryEach

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

Runs one statement that reads rows inside a transaction, and gives you the rows one at a time.

Use Core\Db\Transaction::queryEach for a result that is too large for memory, inside the function you gave to Core\Db\Connection::runTransaction. It returns a Core\Db\Stream, and a foreach over it reads one row from the database in each round of the loop. Only the current row is in memory. The result includes the rows that the transaction has already written.

The transaction is busy until the last row is read. While rows remain, a second statement through the transaction throws a LogicError, and the transaction cannot end. So read all the rows first, and write after the loop.

Good to know: a loop that you leave early with break keeps the connection busy until the request ends. To read only the first rows, put a limit in the statement. For a result that fits in memory, use Core\Db\Transaction::query. With query you can write inside the loop.

The examples below read the rows that the transaction wrote one at a time, collect rows before they write them, and add up a large table into a summary row.

Parameters

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

Options

  • timeoutCore\Time\DurationoptionalHow long reading all the rows may take. The limit applies while the rows are being read, so it covers every row and not only the first call. When the time passes, the statement stops with an IOError, and the connection cannot be used again. Without it, the loop waits as long as the server takes.

Return value

Returns Core\Db\Stream<Core\Db\Row>. The statement's rows for a foreach loop, each one a Core\Db\Row, in the server's order. No row has been read yet when this returns. The connection is busy until the loop reaches the last row, and no other statement can run on it. A loop that writes for each row needs a second connection ({ shared: false }), or query instead.

Errors

  • LogicErrorThe call is wrong, not the database. The placeholders and the array use different styles or different counts, a :name has no element, or an element cannot be bound. It is also thrown when the connection is closed, or when a statement is already streaming on it.
  • Core\Db\DbErrorThe server rejected the statement, at the start or while the rows were read. The error has the server's SQLSTATE and message. It is also thrown for a column type this driver cannot read yet.
  • IOErrorThe connection failed while the statement or one of its rows was being sent, or timeout passed before the loop ended. 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"]

Read the transactions own rows one at a time

<?nvs
// Shows a read inside a transaction that gives you one row at a time. The rows
// the transaction has written are already there, 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']);
// Each step of the loop reads one row from the database. The two rows above
// are part of this transaction, so this prints both of them.
foreach ($tx->queryEach('select id, text from notes order by id', []) as Core\Db\Row $row) {
echo $row->int('id') ?? 0, ': ', $row->string('text') ?? '', "\n";
}
// The last row ended the walk, so the transaction can run another statement.
echo 'rows: ', $tx->query('select id from notes', [])->count(), "\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();
Output
1: buy milk
2: call Ana
rows: 2
2 notes

Collect the rows then write them

<?nvs
// Shows how to write with the rows of a walk. The walk holds the connection
// until its last row, so the loop collects the values and the writes come after.
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 => {
// A second statement while rows remain is a `LogicError`, so this loop only
// reads. It keeps one number per row and nothing else.
array<int> $todo = [];
foreach ($tx->queryEach('select id, title from tasks where done = 0 order by id', []) as Core\Db\Row $row) {
$todo[] = $row->int('id') ?? 0;
echo 'found: ', $row->string('title') ?? '', "\n";
}
// The walk read its last row, so the connection is free again. All three
// updates run on the same transaction and are saved together.
foreach ($todo as int $id) {
$tx->execute('update tasks set done = 1 where id = ?', [$id]);
}
});
// 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();
Output
found: pack
found: label
found: ship
3 of 3 done

Total a large table and store the result

<?nvs
// Shows the work a program really does here: a nightly total over a table that
// is larger than memory, saved with the reading in one transaction.
var $db = Core\Db::connect('notes');
$db->execute('create table orders (id integer primary key, customer text not null, cents int not null)', []);
$db->execute('create table totals (day text primary key, cents int not null, orders int not null)', []);
$db->execute('insert into orders (customer, cents) values (?, ?), (?, ?), (?, ?), (?, ?)', ['Ana', 1200, 'Bo', 4500, 'Ana', 800, 'Cy', 300]);
$db->runTransaction(fn(Core\Db\Transaction $tx): void => {
// Only one row is in memory at a time, so this costs the same for four
// orders and for four million.
int $cents = 0;
int $orders = 0;
foreach ($tx->queryEach('select cents from orders order by id', []) as Core\Db\Row $row) {
$cents = $cents + ($row->int('cents') ?? 0);
$orders = $orders + 1;
}
// The walk is over, so the connection is free for this write. The reading
// and the writing are one transaction, so the total always matches the rows.
$tx->execute('insert into totals (day, cents, orders) values (?, ?, ?)', ['2026-09-21', $cents, $orders]);
});
// This prints `2026-09-21: 6800 cents, 4 orders`.
var $saved = $db->query('select day, cents, orders from totals', [])->first();
echo $saved?->string('day') ?? '', ': ', $saved?->int('cents') ?? 0, ' cents, ', $saved?->int('orders') ?? 0, " orders\n";
$db->close();
Output
2026-09-21: 6800 cents, 4 orders