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, anddriverselects 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 betainted, 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 betainted, because it is sent as a separate value and never read as SQL.usertainted stringThe role to log in as. It may betaintedfor the same reason.passwordsecret tainted stringThe role's password. It issecret, 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 thetls.anchorscapability for the host.tlsPinstring|array<string>One or moresha256//hashes of the server's public key. A server with a matching key is accepted, and its certificate chain is not checked. It needs thetls.pincapability for the host.tlsVerifyHostboolfalsechecks the certificate chain, but not the host name in the certificate. It needs thetls.any_namecapability for the host. The default istrue.tlsVerifyboolfalsechecks 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 andtlsCawhere you can. It needs thetls.insecurecapability for the host. The default istrue.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.0turns the cache off.pathstringThe SQLite file, used in place of a host. It cannot betainted, and it also needs thefs.readandfs.writecapabilities.
Options
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.opendoes not grant the host, or the host's address is in a private range thatnet.internaldoes 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.tlsCaneedstls.anchors,tlsPinneedstls.pin,tlsVerifyHost: falseneedstls.any_nameandtlsVerify: falseneedstls.insecure. It is also thrown whentlsMinVersionis 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
| Version | Change |
|---|---|
0.0.6 | A 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.6 | Core\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();1 buy milkThe 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();rows on the same connection: 1the second connection has its own empty databaseA 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();Berlin 150Hamburg 90