Skip to content

Core\Db\Transaction::queryAs

$transaction->queryAs<T>(
    string $sql,
    array<mixed> $params,
    {timeout?: Core\Time\Duration},
): Core\Db\Rows<T>

Runs one statement inside a transaction, and returns every row as an object of the class you name.

Core\Db\Transaction::queryAs runs the statement exactly as Core\Db\Transaction::query does. Only the rows are different. You write the class in angle brackets, as in queryAs<Note>, and each row is built into a Note. The result is a Core\Db\Rows object, so foreach, all(), count() and first() work as they do for query.

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, so it can read several columns into one property.

A text column fills only a tainted string property, and a binary column only a tainted bytes property, as for Core\Db\Connection::queryAs.

The objects can contain rows the transaction wrote. If the transaction is rolled back, those rows no longer exist in the database. The objects you already built still exist.

The examples read what the transaction wrote as objects, build each object from several columns, and claim a batch of jobs.

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: one array, with list keys for ? and string keys for :name.

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 an IOError. 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<T>. A Core\Db\Rows<T> with one T per row, in the server's order. Each object is created when you read its row with all, first or a foreach. If you only count the rows, no object is created.

Errors

  • LogicErrorThe type argument is an array<...>. A result is already a list of arrays, one per row. It is also thrown when T has no #[Db\Derive], so there is no column mapping to create it from. Both errors come from the call itself, but they are found when the program runs.
  • ParseErrorA row did not match T. 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 the row is reported at once in issues, and each path is the column's name.

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 what the transaction wrote as objects

<?nvs
// Shows a `select` inside a transaction whose rows arrive as objects of your
// own class. 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']);
// `queryAs<Note>` builds one `Note` for each row. This prints both notes,
// with the id in front, before the transaction has ended.
foreach ($tx->queryAs<Note>('select id, text from notes order by id', []) as Note $note) {
echo $note->id, ': ', $note->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();
Output
1: buy milk
2: call Ana
2 notes

Build each object from several columns

<?nvs
// Shows a class that fills itself from a row. Write a `fromRow` method, and
// `queryAs` calls it for every row of the transaction's own read.
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]);
// Each row is a `Line` with the text and the sum the method built. This
// prints `2 x Coffee: 900` and `3 x Tea: 660`, then the total of the two.
int $total = 0;
foreach ($tx->queryAs<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();
Output
2 x Coffee: 900
3 x Tea: 660
total: 1560

Claim a batch of jobs

<?nvs
// Shows work a program really does: one transaction picks the jobs that are
// still open, marks each of them taken, and hands them on as objects. Reading
// and marking are saved together, so no second worker can take the same job.
use Core\Db\Derive;
#[Derive]
class Job
{
public uint $id;
public tainted string $task;
public function constructor(uint $id, tainted string $task)
{
$this->id = $id;
$this->task = $task;
}
}
var $db = Core\Db::connect('notes');
$db->execute('create table jobs (id integer primary key, task text not null, taken int not null)', []);
$db->execute('insert into jobs (task, taken) values (?, 0), (?, 0), (?, 0)', ['resize image', 'send mail', 'build report']);
// The work returns the jobs it claimed, so the rest of the program runs them
// after the transaction is saved.
var $claimed = $db->runTransaction(fn(Core\Db\Transaction $tx): array<Job> => {
array<Job> $batch = [];
foreach ($tx->queryAs<Job>('select id, task from jobs where taken = 0 order by id limit 2', []) as Job $job) {
$tx->execute('update jobs set taken = 1 where id = ?', [$job->id]);
$batch[] = $job;
}
return $batch;
});
// This prints the two jobs that were claimed.
foreach ($claimed as Job $job) {
echo 'running ', $job->id, ': ', $job->task, "\n";
}
// This prints `1 job left`.
echo $db->query('select id from jobs where taken = 0', [])->count(), " job left\n";
$db->close();
Output
running 1: resize image
running 2: send mail
1 job left