Skip to content

Core\Db::connect

Core\Db::connect(
    string $name,
    {shared?: bool, timeout?: Core\Time\Duration},
): Core\Db\Connection

Opens the database an operator set up, under the name they gave it.

A [db.<name>] block in nvs.toml holds the address, the user and the password. Core\Db::connect opens the block with that name. Your program writes the name and nothing else, so a password never reaches your source code. A deployment can also point the same program at a different server.

Every call with the same name gives back the same connection while the request runs. So each function that needs the database can call Core\Db::connect itself. You do not need to pass the connection as a parameter. The shared option turns that off, and then every call opens a new connection.

A server keeps a limited number of connections for each name. When they are all busy the call waits, and the timeout option says how long it waits before it throws an error.

Good to know: the operator decides which blocks a program may open. [app.capabilities.db] connect in nvs.toml lists the names. A name that is not in that list throws an error.

Parameters

  • $namestringThe block to open. It must match exactly: "main" is [db.main]. Two blocks for the same server give two separate connections.

Options

  • sharedbooloptionalWhether this call may return the connection that an earlier call opened. false opens a separate connection. You need one for a write that must stay after a rollback, for a session lock, or for a second statement during a queryEach loop.
  • timeoutCore\Time\DurationoptionalHow long opening the connection may take, including the DNS lookup and TLS. Without it, only the server and the network limit the time.

Return value

Returns Core\Db\Connection. A Core\Db\Connection. The same call twice in one request returns the same object, unless shared is false. The connection is closed when the request ends.

Errors

  • RuntimeErrordb.connect does not grant $name, or there is no [db.<name>] block of that name. It is also thrown when the block does not describe a valid connection. Examples are a missing driver, a setting of another driver, or a time_zone that is not an offset.
  • IOErrorThe host name does not resolve, or the connection, the TLS handshake or the login failed. It is also thrown when this CPU core already uses [db.<name>.pool] max connections with that name and none is free within acquire. When the server sends its own error message, the error includes it.

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"]

Open the database an operator named

<?nvs
// Shows how to open a database by its name. `Core\Db::connect` opens the
// `[db.notes]` block of `nvs.toml`. The address and the password stay in that
// block, so this program never writes them.
var $db = Core\Db::connect('notes');
$db->execute('create table notes (id integer primary key, text text not null)', []);
$db->execute('insert into notes (id, text) values (?, ?)', [1, 'buy milk']);
// This prints `1 buy milk`.
foreach ($db->query('select id, text from notes order by id', []) as Core\Db\Row $row) {
echo $row->int('id') ?? 0, ' ', $row->string('text') ?? '', "\n";
}
$db->close();
Output
1 buy milk

Wait only as long as a page can

<?nvs
// Shows how long a program waits for a free connection. A deployment keeps a
// limited number of connections for each name. When they are all in use,
// `Core\Db::connect` waits, and `timeout` says how long.
// 200 milliseconds is a bound that fits a web page. The visitor gets the page or
// an error. Nobody waits a minute for either.
Core\Time\Duration $wait = Core\Time\Duration::milliseconds(200);
var $db = Core\Db::connect('notes', { timeout: $wait });
$db->execute('create table visits (path text not null)', []);
$db->execute('insert into visits (path) values (?)', ['/prices']);
// This prints `1 visit so far`.
foreach ($db->query('select count(*) as n from visits', []) as Core\Db\Row $row) {
echo $row->int('n') ?? 0, " visit so far\n";
}
// A call that waits longer than this throws an `IOError`. With no `timeout` the
// call waits as long as `[db.notes.pool] acquire` in `nvs.toml` allows.
$db->close();
Output
1 visit so far

Every function asks for the database

<?nvs
// Shows a program that asks for the database where it needs it. Every call with
// the same name gives back the same connection, so a function does not have to
// take the connection as a parameter.
class Notes
{
public static function add(string $text): void
{
var $db = Core\Db::connect('notes');
$db->execute('insert into notes (text) values (?)', [$text]);
}
public static function count(): int
{
var $db = Core\Db::connect('notes');
int $total = 0;
foreach ($db->query('select count(*) as n from notes', []) as Core\Db\Row $row) {
$total = $row->int('n') ?? 0;
}
return $total;
}
}
var $db = Core\Db::connect('notes');
$db->execute('create table notes (id integer primary key, text text not null)', []);
Notes::add('buy milk');
Notes::add('call the plumber');
// The two methods above wrote to this connection. This prints `2 notes`.
echo Notes::count(), " notes\n";
$db->close();
Output
2 notes