Skip to content

Core\Db\Connection::queryEach

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

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

Use Core\Db\Connection::queryEach for a result that is too large for memory. 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, so ten million rows need about as much memory as ten.

The connection is busy until the last row is read. A second statement on the same connection before that throws a LogicError. Read all the rows first and then run the next statement, or open a second connection.

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\Connection::query. It reads every row before it returns.

The examples below read a large table one row at a time, take only the first rows, and calculate totals over a large table.

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 a large table one row at a time

<?nvs
// Shows how to read a result that is too large to hold in memory. `queryEach`
// gives you one row at a time.
var $db = Core\Db::connect('notes');
$db->execute('create table notes (id integer primary key, text text not null)', []);
$db->execute('insert into notes (text) values (?), (?), (?)', ['buy milk', 'call Ana', 'book train']);
// Each step of the loop reads one row from the database. The rows before it
// are gone and the rows after it have not been read yet.
foreach ($db->queryEach('select id, text from notes order by id', []) as Core\Db\Row $row) {
echo $row->int('id') ?? 0, ': ', $row->string('text') ?? '', "\n";
}
// The loop read the last row, so the connection is free for this statement.
echo 'rows: ', $db->query('select count(*) as n from notes', [])->first()?->int('n') ?? 0, "\n";
$db->close();
Output
1: buy milk
2: call Ana
3: book train
rows: 3

Take only the first rows with limit

<?nvs
// Shows how to read only the first rows of a large table. The statement says
// how many rows there are, so the walk ends on its own.
var $db = Core\Db::connect('notes');
$db->execute('create table events (id integer primary key, kind text not null)', []);
$db->execute('insert into events (kind) values (?), (?), (?), (?)', ['open', 'error', 'open', 'error']);
// `limit` bounds the result in the database. Stopping the loop with `break`
// instead would keep the connection busy until the request ends.
foreach ($db->queryEach('select id, kind from events where kind = ? order by id limit 2', ['error']) as Core\Db\Row $row) {
echo 'error at ', $row->int('id') ?? 0, "\n";
}
// The walk read its last row, so the connection is free for this statement.
echo 'events: ', $db->query('select count(*) as n from events', [])->first()?->int('n') ?? 0, "\n";
$db->close();
Output
error at 2
error at 4
events: 4

Total a table without holding it

<?nvs
// Shows the work a program really does with a walk: a report over a table that
// is larger than memory, written one row at a time.
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('insert into orders (customer, cents) values (?, ?), (?, ?), (?, ?), (?, ?)', ['Ana', 1200, 'Bo', 4500, 'Ana', 800, 'Cy', 300]);
// Only one row is in memory at a time, so the totals below cost the same for
// four orders and for four million.
int $total = 0;
int $large = 0;
foreach ($db->queryEach('select customer, cents from orders order by id', []) as Core\Db\Row $row) {
int $cents = $row->int('cents') ?? 0;
$total = $total + $cents;
if ($cents >= 1000) {
$large = $large + 1;
}
echo $row->string('customer') ?? '', ': ', $cents, "\n";
}
// This prints 6800 and 2.
echo 'total: ', $total, "\n";
echo 'orders over 1000: ', $large, "\n";
$db->close();
Output
Ana: 1200
Bo: 4500
Ana: 800
Cy: 300
total: 6800
orders over 1000: 2