Skip to content

Core\Db\Connection::queryAs

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

Runs one statement that reads rows, and returns every row as an object of the class you name.

Core\Db\Connection::queryAs runs the statement exactly as Core\Db\Connection::query does. Only the rows are different. You write the class in angle brackets, as in queryAs<Person>, and each row is built into a Person. 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. A value in a database may come from a visitor. tainted keeps it out of a query or a page until you check it. A plain string property does not compile.

If a column's value does not fit its property, queryAs throws an error that names the column.

The examples read rows into a class, build a class from a row with fromRow, and pass typed rows from one method to the rest of a program.

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 the rows as objects of your own class

<?nvs
// Shows how to read the rows of a `select` as objects of your own class.
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']);
// `queryAs<Note>` builds one `Note` for each row. This prints the three notes,
// one per line, with the id in front.
foreach ($db->queryAs<Note>('select id, text from notes order by id', []) as Note $note) {
echo $note->id, ': ', $note->text, "\n";
}
$db->close();
Output
1: buy milk
2: call Ana
3: book train

Let the class build itself from a row

<?nvs
// Shows a class that fills itself from a row. Write a `fromRow` method, and
// `queryAs` calls it for every row.
class Price
{
public tainted string $label;
public int $cents;
public function constructor(tainted string $label, int $cents)
{
$this->label = $label;
$this->cents = $cents;
}
// `fromRow` gets one row and returns the object. This one joins two
// columns into the label, which a property named after a column cannot do.
public static function fromRow(Core\Db\Row $row): static
{
tainted string $name = $row->string('name') ?? 'unknown';
tainted string $size = $row->string('size') ?? '';
int $cents = $row->int('cents') ?? 0;
return new static($name . ' (' . $size . ')', $cents);
}
}
var $db = Core\Db::connect('notes');
$db->execute('create table products (id integer primary key, name text not null, size text not null, cents int not null)', []);
$db->execute('insert into products (name, size, cents) values (?, ?, ?), (?, ?, ?)', ['Coffee', 'large', 450, 'Tea', 'small', 220]);
// Each row is a `Price` with the label the method built. This prints
// `Coffee (large): 450` and `Tea (small): 220`.
foreach ($db->queryAs<Price>('select name, size, cents from products order by name', []) as Price $price) {
echo $price->label, ': ', $price->cents, "\n";
}
$db->close();
Output
Coffee (large): 450
Tea (small): 220

Pass typed rows to the rest of the program

<?nvs
// Shows what a program does with typed rows: one method reads the orders of a
// customer, and everything after it works with `Order` objects.
use Core\Db\Derive;
#[Derive]
class Order
{
public uint $id;
public tainted string $customer;
public uint $cents;
public function constructor(uint $id, tainted string $customer, uint $cents)
{
$this->id = $id;
$this->customer = $customer;
$this->cents = $cents;
}
}
class Orders
{
// The return type says what the caller gets. `Core\Db\Rows<Order>` is a
// result of `Order` objects, so the statement stays in this one method.
public static function of(Core\Db\Connection $db, string $customer): Core\Db\Rows<Order>
{
return $db->queryAs<Order>('select id, customer, cents from orders where customer = ? order by id', [$customer]);
}
}
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]);
// This prints one line per order of Ana, then the total of the two.
uint $total = 0;
foreach (Orders::of($db, 'Ana') as Order $order) {
echo $order->id, ': ', $order->cents, "\n";
$total = $total + $order->cents;
}
echo 'total: ', $total, "\n";
$db->close();
Output
1: 1200
3: 800
total: 2000