Core\Db\Connection::queryEachAs
$connection->queryEachAs<T>(
string $sql,
array<mixed> $params,
{timeout?: Core\Time\Duration},
): Core\Db\Stream<T>Runs one statement that reads rows, and gives them to you one at a time as objects of the class you name.
Core\Db\Connection::queryEachAs works like Core\Db\Connection::queryEach, and it builds an object from each row. You write the class in angle brackets, as in queryEachAs<Person>. Each round of a foreach reads one row and builds one Person. Only the current object is in memory, so a table of ten million rows uses about as much memory as a table of ten.
The class says how a row is read, as for Core\Db\Connection::queryAs: with the #[Db\Derive] attribute or with a fromRow method.
The connection is busy until the last row is read. A second statement on it while rows remain throws a LogicError. A loop you leave with break keeps the connection busy until the request ends, so put a limit in the statement instead.
The examples read a table as objects, pass a Core\Db\Stream of objects to the rest of a program, and report on a table that is larger than memory.
Parameters
$sqlstringThe statement, bound the same way as inquery. Use a?or a:namefor each value, and never write a value into the text. Ataintedstring does not compile here.$paramsarray<mixed>The values to bind, with the same rule asquery. 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, with the same rule asqueryEach. The limit applies while the rows are being read, so it covers every row and not only the first call. Without it, the loop waits as long as the server takes.
Return value
Returns Core\Db\Stream<T>. The statement's rows for a foreach loop, each one created as a T, in the server's order. No row has been read yet when this returns. The connection is busy, as with queryEach. Only one T exists at a time. That is the only difference from queryAs.
Errors
LogicErrorThe call is wrong, not the database. The placeholders and the array use different styles or different counts, a:namehas 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. ATwithout#[Db\Derive]also throws it here, although the compiler already reports that.ParseErrorA row did not matchT. A column is missing, or has a different type than the property. A SQL NULL is in a property that is not?T, or a property's type has no column mapping. Every bad column of that row is reported at once inissues, and eachpathis the column's name. The loop stops there, because the rest of the result is not read.Core\Db\DbErrorThe server rejected the statement, at the start or while the rows were read. 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 or one of its rows was being sent, ortimeoutpassed before the loop ended. The connection cannot be used for the rest of the request.
Changelog
| Version | Change |
|---|---|
0.0.6 | queryEach 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.
# 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"]Walk a large table as objects
<?nvs// Shows how to read a table that is too large to hold in memory, one object at// a time.use Core\Db\Derive;
// `#[Derive]` writes the code that fills this class from a row. Each property// takes the column of the same name.#[Derive]class Note{ public uint $id; // A text column arrives as `tainted`, because the value comes from the // database. public tainted string $text;
public function constructor(uint $id, tainted string $text) { $this->id = $id; $this->text = $text; }}
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 reads one row and builds one `Note` from it. The object before it// is gone by then.foreach ($db->queryEachAs<Note>('select id, text from notes order by id', []) as Note $note) { echo $note->id, ': ', $note->text, "\n";}
$db->close();1: buy milk2: call Ana3: book trainHand a typed walk to the rest of the program
<?nvs// Shows one method that opens the walk, and a caller that reads objects from// it without writing any SQL.use Core\Db\Derive;
#[Derive]class Order{ public uint $id; public tainted string $customer; public int $cents;
public function constructor(uint $id, tainted string $customer, int $cents) { $this->id = $id; $this->customer = $customer; $this->cents = $cents; }}
class Orders{ // `Core\Db\Stream<Order>` is a walk over `Order` objects. The caller reads // it like any other loop and never sees a column name. public static function large(Core\Db\Connection $db, int $cents): Core\Db\Stream<Order> { return $db->queryEachAs<Order>('select id, customer, cents from orders where cents >= ? order by id', [$cents]); }}
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', 450, 'Cy', 4500]);
// This prints the two orders of 1000 cents or more.foreach (Orders::large($db, 1000) as Order $order) { echo $order->customer, ': ', $order->cents, "\n";}
$db->close();Ana: 1200Cy: 4500Report on a table larger than memory
<?nvs// Shows the work a program really does with a typed walk: a report over a// table that does not fit in memory, written one object at a time.use Core\Db\Derive;
#[Derive]class Reading{ public int $celsius; public tainted string $station;
public function constructor(int $celsius, tainted string $station) { $this->celsius = $celsius; $this->station = $station; }}
var $db = Core\Db::connect('notes');$db->execute('create table readings (id integer primary key, station text not null, celsius int not null)', []);$db->execute('insert into readings (station, celsius) values (?, ?), (?, ?), (?, ?), (?, ?)', ['north', 12, 'south', 31, 'north', 28, 'south', 35]);
// One object is in memory at a time, so these counts cost the same for four// readings and for four million.int $warm = 0;int $highest = 0;foreach ($db->queryEachAs<Reading>('select station, celsius from readings order by id', []) as Reading $reading) { if ($reading->celsius >= 30) { $warm = $warm + 1; } if ($reading->celsius > $highest) { $highest = $reading->celsius; }}
// This prints 2 and 35.echo 'readings over 30: ', $warm, "\n";echo 'highest: ', $highest, "\n";
$db->close();readings over 30: 2highest: 35