Skip to content

Core\Db::open

Core\Db::open({…} $settings, {shared?: bool}): Core\Db\ConnectionCore\Db::open(
    {…} $settings,
    {shared?: bool},
): Core\Db\Connection

Opens a database connection from settings the program itself writes.

Most programs name a connection instead. An operator puts the address and the password in a [db.<name>] block in nvs.toml, and Core\Db::connect opens it by name. Use Core\Db::open when a block cannot work. One case is a customer whose database is chosen while the program runs. Another is a tool where a person types the host.

The settings are one of two shapes, and driver decides which. MySQL, MariaDB, PostgreSQL and SQL Server take a host, a user and a password. SQLite takes a file path instead.

Two calls with the same settings give you the same connection. With shared: false, every call opens a new one.

If a TLS connection fails, the error names the cause and the fix (TLS connections).

Good to know: the operator still decides what you may reach. A database on another server needs the db.open capability for its host. A SQLite file follows the rules for files. The path :memory: gives a database that exists only in memory, and it needs no capability. On a server, a SQLite file in the application folder opens read-only, unless fs.write includes it.

Parameters

  • $settings{ driver: Core\Db\Driver::MySql|Core\Db\Driver::MariaDb|Core\Db\Driver::Postgres|Core\Db\Driver::SqlServer, host: string, port?: uint, database: tainted string, user: tainted string, password: secret tainted string, tlsCa?: string, tlsPin?: string|array<string>, tlsVerifyHost?: bool, tlsVerify?: bool, tlsMinVersion?: string, timeZone?: Core\Time\Zone, timeout?: Core\Time\Duration, statementCache?: uint }|{ driver: Core\Db\Driver::Sqlite, path: string, timeZone?: Core\Time\Zone, timeout?: Core\Time\Duration }All settings of the connection. The object has one of two shapes, and driver selects the shape. Four of the five databases need a host, and SQLite needs a file path.
    • driverDriverWhich database this is. It selects which of the two shapes the rest of the object must have.
    • hoststringThe server to connect to. Its certificate is checked against this name. It cannot be tainted, and no check can remove that, because no check on a string proves that a host is safe for a password.
    • portuintThe port to connect to. Without it, the driver's default is used: 5432 for PostgreSQL, and 3306 for MySQL and MariaDB.
    • databasetainted stringThe database or schema to use. It may be tainted, because it is sent as a separate value and never read as SQL.
    • usertainted stringThe role to log in as. It may be tainted for the same reason.
    • passwordsecret tainted stringThe role's password. It is secret, so it cannot reach a log line, a message or a trace.
    • tlsCastringPEM certificates to trust for this connection, in place of [tls.client] roots. It needs the tls.anchors capability for the host.
    • tlsPinstring|array<string>One or more sha256// hashes of the server's public key. A server with a matching key is accepted, and its certificate chain is not checked. It needs the tls.pin capability for the host.
    • tlsVerifyHostboolfalse checks the certificate chain, but not the host name in the certificate. It needs the tls.any_name capability for the host. The default is true.
    • tlsVerifyboolfalse checks neither the certificate chain nor the host name. The connection is still encrypted. Another machine on the network can still pretend to be the server and read every query and row. With SQL Server, it can also read the password. Use a real certificate and tlsCa where you can. It needs the tls.insecure capability for the host. The default is true.
    • tlsMinVersionstringThe lowest TLS version to accept: "1.2" or "1.3". It can only raise [tls.client] min_version, so it needs no capability.
    • timeZoneCore\Time\ZoneThe time zone for reading a column that has no time zone. The server is also told to use it. The default is UTC.
    • timeoutCore\Time\DurationHow long opening the connection may take, including the DNS lookup and TLS.
    • statementCacheuintHow many prepared statements this connection may keep on the server. 0 turns the cache off.
    • pathstringThe SQLite file, used in place of a host. It cannot be tainted, and it also needs the fs.read and fs.write capabilities.

Options

  • sharedbooloptionalWhether this call may return the connection that an earlier call opened with the same settings. false opens a separate connection.

Return value

Returns Core\Db\Connection. A Core\Db\Connection. It is closed when the request ends. Two calls with the same settings return the same object. With shared: false, each call returns a new one.

Errors

  • RuntimeErrordb.open does not grant the host, or the host's address is in a private range that net.internal does not allow. It is also thrown when this build cannot open a connection with these settings.
  • LogicErrorA TLS setting makes the certificate check less strict, and its grant does not list the host. tlsCa needs tls.anchors, tlsPin needs tls.pin, tlsVerifyHost: false needs tls.any_name and tlsVerify: false needs tls.insecure. It is also thrown when tlsMinVersion is not "1.2" or "1.3", or is lower than [tls.client] min_version. Nothing is connected.
  • IOErrorThe host name does not resolve, or the connection, the TLS handshake or the login failed. It is also thrown when the connection pool for these settings is full and no connection became free in time.

Changelog

VersionChange
0.0.6A failed TLS connection names its cause, who can fix it and how, as TLS connection errors explains. For an expired certificate, the message gives the date it expired and the time on this host's clock. For a wrong pin, it gives the sha256// hash of the server's public key.
0.0.6Core\Db::open has the TLS settings of Core\Http\Client: tlsCa, tlsPin, tlsVerifyHost, tlsVerify and tlsMinVersion. A setting that makes the certificate check less strict needs the host in a list under [capabilities.tls], or the call throws a LogicError. A [db.<name>] block has the keys tls_ca_file, tls_pin, tls_verify_host, tls_verify and tls_min_version for the same settings.

Examples

Open a database the program names

<?nvs
// Shows how to open a database that the program itself names. `Core\Db::open`
// takes the settings a `[db.<name>]` block in `nvs.toml` would otherwise hold.
// `driver` says which backend this is. SQLite needs a file path, and the other
// four drivers need a host. `:memory:` lasts as long as the program runs.
var $db = Core\Db::open({ driver: Core\Db\Driver::Sqlite, path: ':memory:' });
$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

The same settings give the same connection

<?nvs
// Shows what the `shared` option does. Two calls with the same settings give you
// the same connection. `shared: false` gives you a new one every time.
var $first = Core\Db::open({ driver: Core\Db\Driver::Sqlite, path: ':memory:' });
$first->execute('create table notes (text text not null)', []);
$first->execute('insert into notes (text) values (?)', ['buy milk']);
// The settings are the same, so this is the connection that is already open. The
// table is there, and this prints `rows on the same connection: 1`.
var $again = Core\Db::open({ driver: Core\Db\Driver::Sqlite, path: ':memory:' });
foreach ($again->query('select count(*) as n from notes', []) as Core\Db\Row $row) {
echo 'rows on the same connection: ', $row->int('n') ?? 0, "\n";
}
// `shared: false` opens a second connection. A `:memory:` database belongs to one
// connection, so the second one starts empty and the table is not in it.
var $separate = Core\Db::open({ driver: Core\Db\Driver::Sqlite, path: ':memory:' }, { shared: false });
try {
$separate->query('select count(*) as n from notes', []);
echo "the second connection sees the table\n";
} catch (Core\Db\DbError $error) {
echo "the second connection has its own empty database\n";
}
$separate->close();
$first->close();
Output
rows on the same connection: 1
the second connection has its own empty database

A database for one report

<?nvs
// Shows a database a program opens only for itself. A report can put its numbers
// into a `:memory:` database and let SQL group them.
var $db = Core\Db::open({ driver: Core\Db\Driver::Sqlite, path: ':memory:' });
$db->execute('create table sales (city text not null, amount integer not null)', []);
// One prepared statement, three rows.
$db->executeMany('insert into sales (city, amount) values (?, ?)', [
['Berlin', 120],
['Hamburg', 90],
['Berlin', 30],
]);
// This prints `Berlin 150` and `Hamburg 90`.
foreach ($db->query('select city, sum(amount) as total from sales group by city order by city', []) as Core\Db\Row $row) {
echo $row->string('city') ?? '', ' ', $row->int('total') ?? 0, "\n";
}
$db->close();
Output
Berlin 150
Hamburg 90