Every database handle exposes the same query API across drivers. Bind values through parameters so that SQLite treats them as data. Use a transaction when several writes need to commit together.
Open a database
The complete accounts.ts example creates a temporary database file, so repeated executions start with the same accounts. It creates the table, loads two accounts, reads one, and transfers 1,000 units between them.
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { Sirannon, type Transaction } from '@delali/sirannon-db'
import { betterSqlite3 } from '@delali/sirannon-db/driver/better-sqlite3'
interface Account {
id: number
holder: string
balance: number
}
const directory = await mkdtemp(join(tmpdir(), 'sirannon-accounts-'))
const sirannon = new Sirannon({ driver: betterSqlite3() })
try {
const db = await sirannon.open('ledger', join(directory, 'ledger.db'))
await db.execute('CREATE TABLE accounts (id INTEGER PRIMARY KEY, holder TEXT NOT NULL, balance INTEGER NOT NULL CHECK (balance >= 0))')
await db.executeBatch('INSERT INTO accounts (id, holder, balance) VALUES (?, ?, ?)', [
[1, 'Julie Hughes', 5000],
[2, 'Hiroki Sato', 2000],
])
const julie = await db.queryOne<Account>('SELECT id, holder, balance FROM accounts WHERE id = ?', [1])
if (julie === undefined) throw new Error('The source account is missing')
await db.transaction(async (tx: Transaction): Promise<void> => {
const debit = await tx.execute('UPDATE accounts SET balance = balance - ? WHERE id = ? AND balance >= ?', [1000, 1, 1000])
if (debit.changes !== 1) throw new Error('The source account cannot fund this transfer')
const credit = await tx.execute('UPDATE accounts SET balance = balance + ? WHERE id = ?', [1000, 2])
if (credit.changes !== 1) throw new Error('The destination account is missing')
})
const accounts = await db.query<Account>('SELECT id, holder, balance FROM accounts ORDER BY id')
console.log(JSON.stringify(accounts, (_key: string, value: unknown): unknown => typeof value === 'number' ? Number(value.toFixed(2)) : value, 2))
} finally {
try {
await sirannon.shutdown()
} finally {
await rm(directory, { recursive: true, force: true })
}
}The balance values use integer units. In a payment application, define the currency and its smallest unit separately.
Create a table
execute(sql, params?) executes one statement and returns changes and lastInsertRowId. Use it for schema statements and writes. The insert row ID can be a bigint when it exceeds JavaScript's safe integer range; see integer fidelity.
open(id, path, options?) associates the registry ID with a file path. Create a persistent file's parent directory before opening it. Opening an ID that is already registered fails with DATABASE_ALREADY_EXISTS. Use resolve(id) to retrieve an existing handle or open it through a configured lifecycle resolver.
Insert rows
Pass positional parameters as an array or named parameters through the supported parameter object. Keep SQL identifiers under application control, because value parameters cannot replace table or column identifiers.
The example supplies explicit account IDs so that its transfer addresses the intended rows. A database constraint prevents negative balances.
Load many rows in one call
executeBatch(sql, paramsBatch) reuses a prepared statement with each parameter set and returns a result for each execution. Use bulk loading when importing a dataset with a chosen durability policy.
Read rows back
query<T>() returns an array. queryOne<T>() returns its first matching row or undefined. Both accept the same value parameters as execute.
The TypeScript type argument describes the expected rows; it performs no runtime validation. Select the columns that the application needs and validate externally supplied data at its boundary.
Move money in a transaction
transaction(callback) passes a transaction handle to the callback. Its query, execute, and executeBatch methods use the transaction's connection. Await each operation before the callback finishes.
Sirannon commits when the callback resolves and rolls back when it throws. The callback's return value becomes the transaction's result. A failed commit raises TRANSACTION_ERROR.
The example checks both updates inside the transaction. If either account cannot take part, throwing rolls back the debit and credit together.
The transaction handle stops accepting statements when the callback returns or throws. A later call fails with TRANSACTION_CLOSED, including a call through a saved handle. Use the supplied tx inside the callback and a new database operation afterwards.
In browser and Expo runtimes, a database operation that needs the writer while a transaction callback holds it fails with WRITER_HELD_BY_CALLBACK. Use tx for those statements. bulkLoad inside a transaction fails with BULK_LOAD_IN_TRANSACTION; perform the load outside that callback.
A query hook refusal inside a transaction propagates through the transaction. Catching an error inside the callback permits later callback work to continue, so let the error escape when the whole operation must roll back.
Tune the connection pool
A driver with multiple connections opens one writer and a rotating read pool. The default read pool size is four, and at least one reader remains even when readPoolSize is zero. A single-connection driver uses its writer for reads too.
For a Node database with several connections, use a file path. Separate connections to :memory: do not share an ordinary SQLite in-memory database.
walMode defaults to true. readPoolSize changes the reader count, and readOnly opens connections read-only. Configuration lists the database options.
synchronous defaults to 'normal' and also accepts 'off', 'full', and 'extra'. Choose the durability level for the application's failure requirements. A bulk load restores that configured level after its temporary policy.
Handle errors
Catch SirannonError to inspect its machine-readable code. Query failures use QUERY_ERROR; transaction commit failures use TRANSACTION_ERROR. Driver messages can include SQL details, so keep them out of public error responses.
The server sanitises internal error details before returning remote errors. Error codes lists the structured refusals, including expired transactions and writer-worker failures.