Core\Db\Connection::driver
$connection->driver(): Core\Db\DriverSays which database system a connection speaks to.
Core\Db\Connection::driver returns a Core\Db\Driver case: Sqlite, Postgres, MySql, MariaDb or SqlServer. A case is a value, so your program compares it with == and never reads a name out of a string.
The value comes from the connection itself, not from the settings file. A connection that Core\Db::connect opened from a [db.<name>] block and one that Core\Db::open opened from a settings value both return it the same way.
Programs call this when a statement does not work on every database, and when a program supports some databases and not others. A closed connection throws a LogicError here.
Return value
Returns Core\Db\Driver. The connection's own Core\Db\Driver case.
Errors
LogicErrorThe connection has been closed.
Examples
The examples below run with this configuration file.
# 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"]See which database you are connected to
<?nvs// Shows how to ask a connection which database system it speaks to. The answer// is a `Core\Db\Driver` case, so the program compares it with `==`.
var $db = Core\Db::connect('notes');
// This prints `SQLite`.if ($db->driver() == Core\Db\Driver::Sqlite) { echo "SQLite\n";} else { echo "another database\n";}
$db->close();SQLiteWrite the statement the database understands
<?nvs// Shows a program that runs one statement on SQL Server and another one// everywhere else. Both ask for the first row, and each database has its own// way to write that.
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 `buy milk`, because the connection is a SQLite one.if ($db->driver() == Core\Db\Driver::SqlServer) { foreach ($db->query('select top 1 text from notes order by id', []) as Core\Db\Row $row) { echo $row->string('text') ?? '', "\n"; }} else { foreach ($db->query('select text from notes order by id limit 1', []) as Core\Db\Row $row) { echo $row->string('text') ?? '', "\n"; }}
$db->close();buy milkStop on a database the program does not support
<?nvs// Shows a maintenance program that only knows SQLite. It asks the connection// which database it is before it does anything, and says so on any other one.
class Maintenance{ public static function run(Core\Db\Connection $db): string { if ($db->driver() != Core\Db\Driver::Sqlite) { return 'This program needs SQLite.'; } $db->execute('vacuum', []); return 'The database was cleaned up.'; }}
var $db = Core\Db::connect('notes');
// This prints `The database was cleaned up.`echo Maintenance::run($db), "\n";
$db->close();The database was cleaned up.