Core\Db\Transaction::queryEachAs
$transaction->queryEachAs<T>(
string $sql,
array<mixed> $params,
{timeout?: Core\Time\Duration},
): Core\Db\Stream<T>Runs one statement inside a transaction and gives you each row as an object of your class, one row at a time.
Core\Db\Transaction::queryEachAs works like Core\Db\Transaction::queryEach, and it builds an object from each row. You write the class in angle brackets, as in queryEachAs<Note>. Each round of a foreach reads one row and builds one Note. Only the current object is in memory.
The class says how a row is read, as for Core\Db\Transaction::queryAs. A class with the #[Db\Derive] attribute gets one property for each column with the same name. A class with a fromRow method builds the object itself. A text column fills only a tainted string property, and a binary column only a tainted bytes property.
Good to know: the transaction is busy until the last row is read. While rows remain, a second statement in the transaction throws a LogicError. Read all the rows, keep what you need, and write after the loop. To read only the first rows, put a limit in the statement.
The examples read the rows that the transaction wrote as objects, build each object from several columns, and write a reminder for every overdue invoice.
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"]Read the transactions own rows as objects
<?nvs// Shows a read inside a transaction that gives you one object at a time. The// rows the transaction has written are already there.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->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 and builds one `Note` from it. The // object before it is gone by then, so only one is in memory at a time. foreach ($tx->queryEachAs<Note>('select id, text from notes order by id', []) as Note $note) { echo $note->id, ': ', $note->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();1: buy milk2: call Anarows: 22 notesBuild each object from several columns
<?nvs// Shows a class that fills itself from a row. Write a `fromRow` method, and// `queryEachAs` calls it once for each row it reads.
class Line{ public tainted string $what; public int $cents;
public function constructor(tainted string $what, int $cents) { $this->what = $what; $this->cents = $cents; }
// `fromRow` gets one row and returns the object. This one joins two // columns into the text, which a property named after a column cannot do. public static function fromRow(Core\Db\Row $row): static { tainted string $item = $row->string('item') ?? 'unknown'; int $count = $row->int('count') ?? 0; int $cents = $row->int('cents') ?? 0; return new static($count . ' x ' . $item, $count * $cents); }}
var $db = Core\Db::connect('notes');$db->execute('create table lines (id integer primary key, item text not null, count int not null, cents int not null)', []);
$db->runTransaction(fn(Core\Db\Transaction $tx): void => { $tx->execute('insert into lines (item, count, cents) values (?, ?, ?), (?, ?, ?)', ['Coffee', 2, 450, 'Tea', 3, 220]);
// One `Line` is built per row, with the text and the sum the method made. // This prints `2 x Coffee: 900` and `3 x Tea: 660`, then the total. int $total = 0; foreach ($tx->queryEachAs<Line>('select item, count, cents from lines order by id', []) as Line $line) { echo $line->what, ': ', $line->cents, "\n"; $total = $total + $line->cents; } echo 'total: ', $total, "\n";});
$db->close();2 x Coffee: 9003 x Tea: 660total: 1560Remind every overdue invoice
<?nvs// Shows the work a program really does here: a nightly pass over an invoice// table that is larger than memory, which writes a reminder for the overdue// ones. Reading and writing are one transaction.use Core\Db\Derive;
#[Derive]class Invoice{ public uint $id; public tainted string $customer; public int $daysLate;
public function constructor(uint $id, tainted string $customer, int $daysLate) { $this->id = $id; $this->customer = $customer; $this->daysLate = $daysLate; }}
var $db = Core\Db::connect('notes');$db->execute('create table invoices (id integer primary key, customer text not null, daysLate int not null, paid int not null)', []);$db->execute('create table reminders (id integer primary key, invoice int not null, customer text not null)', []);$db->execute('insert into invoices (customer, daysLate, paid) values (?, ?, 0), (?, ?, 0), (?, ?, 0), (?, ?, 1)', ['Ana', 12, 'Bo', 0, 'Cy', 40, 'Dee', 90]);
$db->runTransaction(fn(Core\Db\Transaction $tx): void => { // A second statement while rows remain is a `LogicError`, so this loop only // reads. It keeps the objects it needs and nothing else. array<Invoice> $late = []; foreach ($tx->queryEachAs<Invoice>('select id, customer, daysLate from invoices where paid = 0 order by id', []) as Invoice $invoice) { if ($invoice->daysLate > 7) { $late[] = $invoice; } }
// The walk read its last row, so the connection is free again. Both writes // run on the same transaction and are saved together. foreach ($late as Invoice $invoice) { $tx->execute('insert into reminders (invoice, customer) values (?, ?)', [$invoice->id, $invoice->customer]); echo 'reminding ', $invoice->customer, ' after ', $invoice->daysLate, " days\n"; }});
// This prints `2 reminders`.echo $db->query('select id from reminders', [])->count(), " reminders\n";
$db->close();reminding Ana after 12 daysreminding Cy after 40 days2 reminders