Database: Getting Started
Introduction
@plinthjs/database is the layer that talks to your database. It gives you a Connection, a fluent query builder, a schema builder and migrations, seeders, and a small introspection API for reading a schema back.
Everything runs through a Driver, a tiny interface that executes compiled SQL and returns rows. The package ships one driver: SQLite, backed by Node's built-in node:sqlite, so it needs no native dependencies and no server. For MySQL, MariaDB or Postgres you supply a Driver that wraps the client library of your choice, and Plinth supplies the matching SQL grammar.
pnpm add @plinthjs/databaseConnecting to a database
sqliteConnection() returns a Connection backed by an in-memory SQLite database. Pass a filename to use a file instead.
import { sqliteConnection } from '@plinthjs/database'
const db = sqliteConnection() // in-memory
const fileDb = sqliteConnection({ filename: 'storage/database.sqlite' })
await db.statement('create table users (id integer primary key, name text, age integer)')
await db.table('users').insert({ name: 'Ada', age: 36 })
await db.table('users').count() // => 1
await db.close()db.table('users') starts a query against a table. The rest of the query API is covered in Query Builder.
TIP
An in-memory connection is the easiest way to experiment and to write tests: every call to sqliteConnection() creates a fresh, empty database that disappears when the connection is closed.
In a generated application
A scaffolded app binds one Connection as a container singleton under the DB token (see src/providers/app-service-provider.ts). It reads the default connection from src/config/database.ts, which is driven by environment variables:
DB_CONNECTION=sqlite
DB_DATABASE=storage/database.sqliteAnywhere in your code you can get the connection with the db() helper from src/support/container.ts:
import { db } from '../Support/container.js'
const users = await db().table('users').get()The generated config also describes mysql, mariadb and pgsql connections. The app ships a mysql2-backed driver in src/database/mysql-driver.ts, used when DB_CONNECTION=mysql (or mariadb). For Postgres you write the driver yourself, as described below.
Supported databases and drivers
A Connection picks its SQL dialect from the dialect string reported by its driver.
| Dialect | Query grammar | Schema grammar | Driver shipped |
|---|---|---|---|
sqlite | base grammar | SqliteSchemaGrammar | SqliteDriver |
mysql | MySqlGrammar | MySqlSchemaGrammar | none (bring your own) |
mariadb | MySqlGrammar | MariaDbSchemaGrammar | none (bring your own) |
pgsql | PostgresGrammar | PostgresSchemaGrammar | none (bring your own) |
sqlsrv (or mssql) | base grammar | SqlServerSchemaGrammar | none (bring your own) |
SQL Server has schema-builder and introspection support, but no dedicated query grammar: its queries compile with the base grammar (double-quoted identifiers and ? placeholders).
Writing a driver
A Driver has four members: a dialect name, select for statements that return rows, statement for writes and DDL, and close. Bindings are positional, and statement reports the affected row count and the last insert id.
import { Connection } from '@plinthjs/database'
import type { Binding, Driver, Row, StatementResult } from '@plinthjs/database'
class MyMysqlDriver implements Driver {
readonly dialect = 'mysql'
async select(sql: string, bindings: readonly Binding[]): Promise<Row[]> {
// run `sql` with `bindings` through your client and return the rows
return []
}
async statement(sql: string, bindings: readonly Binding[]): Promise<StatementResult> {
// run the write and return { changes, lastInsertId }
return { changes: 0, lastInsertId: 0 }
}
async close(): Promise<void> {}
}
const db = new Connection(new MyMysqlDriver())
db.table('users').where('id', 1).toSql()
// => { sql: 'select * from `users` where `id` = ?', bindings: [1] }Because the grammar is chosen from the dialect, toSql() already produces MySQL SQL even before a real server is involved. That makes it easy to unit test the SQL your code builds against any supported dialect.
Running raw statements
The query builder covers most needs, but you can always run SQL directly. Use select for statements that return rows, statement for everything else, and bind values with ? placeholders instead of concatenating them.
const rows = await db.select('select * from users where age > ?', [30])
// => [{ id: 1, name: 'Ada', age: 36 }]
const result = await db.statement('insert into users (name, age) values (?, ?)', ['Linus', 54])
// => { changes: 1, lastInsertId: 2 }Two shortcuts cover the common single-value cases:
await db.selectOne('select * from users where id = ?', [99]) // => null
await db.scalar('select count(*) from users') // => 2selectOne returns the first row or null. scalar returns the first column of the first row, or undefined when there are no rows.
Multiple connections
DatabaseManager keeps a set of named connections, creates each one the first time you ask for it, and caches it. createDatabaseManager() is a shortcut for new DatabaseManager().
import { createDatabaseManager } from '@plinthjs/database'
const manager = createDatabaseManager({
default: 'main',
connections: {
main: { driver: 'sqlite', filename: 'storage/main.sqlite' },
analytics: { driver: 'sqlite', filename: 'storage/analytics.sqlite' },
},
})
const users = await manager.connection().table('users').get() // the default connection
const events = await manager.connection('analytics').table('events').get()
manager.connection('main') === manager.connection() // => true (cached)Asking for a name that was never configured throws a helpful error:
manager.connection('nope')
// Error: Database connection [nope] is not configured. Known connections: main, analytics.You can also register connections after construction, change the default, and release them when you are done:
manager.addConnection('cache', { driver: 'sqlite' }) // in-memory
manager.setDefault('cache')
manager.getDefaultName() // => 'cache'
await manager.purge('cache') // close one and drop it from the cache
await manager.disconnectAll() // close every open connectionThe built-in config only understands the sqlite driver. For anything else, register a factory with extend, which returns a Connection built from any Driver. A factory wins over a config entry of the same name.
import { Connection } from '@plinthjs/database'
manager.extend('reporting', () => new Connection(new MyMysqlDriver()))
manager.connection('reporting').dialect // => 'mysql'Read and write connections
A connection can send reads to one database and writes to another. Give a SQLite config both a read and a write side and set sticky if reads should see data you have just written.
const manager = createDatabaseManager({
connections: {
default: {
driver: 'sqlite',
read: { filename: 'storage/replica.sqlite' },
write: { filename: 'storage/primary.sqlite' },
sticky: true,
},
},
})With your own drivers you build the same thing directly, passing the read driver as an option:
const db = new Connection(writeDriver, { read: readDriver, sticky: true })
db.hasReadWriteSplit() // => trueSelects go to the read driver. Writes, and every statement inside a transaction (including reads), go to the write driver. With sticky: true, once the connection has performed a write, all later reads also use the write driver so they observe that data.
You can force a read onto the write driver with useWritePdo(). Called with no argument it applies to the very next read; called with a callback it applies to every read made while the callback runs.
await db.useWritePdo().table('users').count() // the next read uses the write driver
await db.useWritePdo(() => db.table('users').count()) // every read inside the callback doesTransactions
transaction() runs a callback inside a database transaction. It commits when the callback resolves and rolls back when it throws, rethrowing the error.
await db.transaction(async (tx) => {
await tx.table('accounts').where('id', 1).update({ balance: 50 })
await tx.table('accounts').where('id', 2).update({ balance: 150 })
})
try {
await db.transaction(async (tx) => {
await tx.table('users').insert({ name: 'Temp' })
throw new Error('boom')
})
} catch {
// the insert was rolled back
}The callback receives the connection. Use it (or the original connection, which is the same object) for every query that should be part of the transaction. The callback's return value becomes the value of transaction().
Nested transactions and savepoints
Calling transaction() inside a transaction opens a savepoint instead. If the inner callback throws, only the work since that savepoint is rolled back, and the outer transaction can carry on.
await db.transaction(async (tx) => {
await tx.table('users').insert({ name: 'Outer' })
try {
await tx.transaction(async (inner) => {
await inner.table('users').insert({ name: 'Inner' })
throw new Error('x')
})
} catch {
// 'Inner' is gone; 'Outer' is still pending
}
tx.transactionCount() // => 1
})Manual control
When a callback does not fit, drive the transaction yourself with beginTransaction(), commit() and rollBack(). Nested calls become savepoints in the same way.
await db.beginTransaction()
try {
await db.table('users').insert({ name: 'Manual' })
await db.commit()
} catch (error) {
await db.rollBack()
throw error
}Retrying after a deadlock
Pass a number of attempts as the second argument and the outermost transaction re-runs the whole callback when it fails with a deadlock, lock timeout, "database is locked" or serialization error. Other errors are not retried.
await db.transaction(async (tx) => {
await tx.table('inventory').where('sku', 'A1').decrementEach({ stock: 1 })
}, 3) // up to three attempts in totalThe default is a single attempt. causedByConcurrencyError(error) is exported if you want to apply the same test to your own error handling.
Running code after commit
afterCommit() queues a callback that runs once the outermost transaction commits. It is discarded if the transaction rolls back, and it runs immediately when no transaction is open. Use it for side effects such as sending an email that must only happen if the data was saved.
await db.transaction(async (tx) => {
await tx.table('orders').insert({ total: 100 })
await tx.afterCommit(() => console.log('order committed'))
console.log('inside the transaction')
})
// inside the transaction
// order committedListening to queries
listen() registers a callback that is called after every query the connection runs, with the SQL, the bindings and the duration in milliseconds. It is the hook for query logging and slow-query detection.
db.listen(({ sql, bindings, durationMs }) => {
console.log(`${durationMs.toFixed(1)}ms`, sql, bindings)
})
await db.table('users').where('age', '>', 30).get()
// 0.2ms select * from "users" where "age" > ? [ 30 ]Transaction statements (begin, commit, savepoint ...) are reported as well. You can add several listeners; each receives every event.
Dry runs
pretend() runs a callback without executing anything. Each statement is recorded and returned instead, selects resolve to an empty array and writes report zero changes. The listeners are still notified, with a duration of 0.
const queries = await db.pretend(async (connection) => {
await connection.table('users').insert({ name: 'Ada' })
})
// => [{ sql: 'insert into "users" ("name") values (?)', bindings: ['Ada'] }]Migrations use the same mechanism for their --pretend mode; see Migrations.
Inspecting the schema
SchemaInspector reads a live database back and returns the same normalised shapes for every dialect, so you never branch on the engine. Give it a connection:
import { SchemaInspector } from '@plinthjs/database'
const inspector = new SchemaInspector(db)
await inspector.hasTable('users') // => true
await inspector.hasColumns('users', ['id', 'email']) // => true
await inspector.getColumnListing('users') // => ['id', 'email', 'created_at', 'updated_at']
await inspector.getColumnType('users', 'email') // => 'VARCHAR' (the engine's own type text)The Schema builder exposes the same methods (getTables, getColumns, hasIndex, ...) so a migration can inspect as it goes.
Tables and views
await inspector.getTables()
// => [{ name: 'posts', schema: null, size: null, comment: null }, { name: 'users', ... }]
await inspector.getViews()
// => [{ name: 'recent', schema: null, definition: 'CREATE VIEW recent as select ...' }]
await inspector.hasView('recent') // => truesize and comment are filled in where the engine reports them (not on SQLite). Pass a schema name, or a list of names, to getTables() and getViews() to narrow them on engines that have schemas.
Columns
await inspector.getColumns('posts')
// => [
// { name: 'id', type: 'INTEGER', nullable: false, default: null, autoIncrement: true, comment: null },
// { name: 'title', type: 'VARCHAR', nullable: false, default: null, autoIncrement: false, comment: null },
// ]Indexes
The primary key is included and is named primary.
await inspector.getIndexes('users')
// => [
// { name: 'primary', columns: ['id'], unique: true, primary: true },
// { name: 'users_name_age_index', columns: ['name', 'age'], unique: false, primary: false },
// ]
await inspector.hasIndex('users', 'users_name_age_index') // by name
await inspector.hasIndex('users', ['name', 'age']) // by exact column list
await inspector.hasIndex('users', ['email'], 'unique') // narrowed to a unique index
await inspector.getIndexListing('users') // => ['primary', 'users_name_age_index']Foreign keys
await inspector.getForeignKeys('posts')
// => [{
// name: null, // SQLite foreign keys are unnamed
// columns: ['user_id'],
// foreignTable: 'users',
// foreignColumns: ['id'],
// onDelete: 'cascade',
// onUpdate: 'no action',
// }]Schemas
getSchemas() lists the schemas (or attached databases, on SQLite) the connection can see. getCurrentSchemaName() and getCurrentSchemaListing() return null on engines where the concept does not apply.
await inspector.getSchemas() // => [{ name: 'main', path: null, default: true }]
await inspector.getCurrentSchemaName() // => null on SQLiteGotchas
- Only the SQLite driver is built in. For every other engine you provide the
Driver, and the generated app only wires up MySQL and MariaDB for you. - A connection created with
sqliteConnection()is one database handle. Close it withclose()(ormanager.disconnectAll()) when you are done so the process can exit. - Inside a transaction every read uses the write driver, even when a read/write split is configured.
transaction()only retries on the outermost level. A deadlock inside a savepoint propagates to the outer callback.