Every database handle in Sirannon has the same query methods, whichever driver opens the file. Bind each value through a parameter so that SQLite treats it as data. When SQLite has to commit several writes together, group them in a transaction.
Open a database
The accounts.ts program below creates a temporary database file, so the program starts with the same two accounts on every execution. The program creates the table, loads the accounts, reads the first one back, and moves 1,000 units from the first account to the second.
open(id, path, options?) registers the database under the ID and opens the file at the path. Create the directory for a file before you open the file, because open fails with DATABASE_OPEN_FAILED for a path whose directory is missing. open fails with DATABASE_ALREADY_EXISTS for an ID that the registry contains, so call resolve(id) to get the handle of an open database. resolve also opens the database through a lifecycle resolver when you configure one.
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, 'customer-1', 5000],
[2, 'customer-2', 2000],
])
const source = await db.queryOne<Account>('SELECT id, holder, balance FROM accounts WHERE id = ?', [1])
if (source === 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 program stores each balance as a whole number of units, so a payment application will also have to record the currency and its smallest unit beside each balance.
Create a table
execute(sql, params?) executes one statement and returns changes and lastInsertRowId, so use it for schema statements and for writes. Sirannon returns lastInsertRowId as a bigint when the row ID is outside JavaScript's safe integer range, as integer fidelity explains.
Insert rows
Pass positional parameters as an array, or named parameters as an object. Take every table and column name from the code of your application, because a parameter can stand in for a value and only for a value.
The program gives each account an explicit ID so that the transfer updates the intended rows. Through the CHECK constraint on the table, SQLite refuses a negative balance as a second guard beside the balance >= ? condition of the debit.
Load many rows in one call
executeBatch(sql, paramsBatch) reuses one prepared statement for each set of parameters and returns a result for each execution. To import a whole dataset under a durability policy that you choose, use a bulk load.
Read rows back
query<T>() returns every matching row in an array, while queryOne<T>() returns the first matching row or undefined. Both take the same parameters as execute.
The type argument describes the rows that you expect, although Sirannon checks none of them at runtime. Validate the data that comes from outside your system at the point where it enters, because your code raises an error for a value of the wrong type only where it uses that value.
Read two columns that share a name
A row from query is an object keyed by column name, so a row can lose a value or contain a value in another position. When a join selects both t.id and a.id, Sirannon keeps only the second value in the row. JavaScript also moves a key called "1" ahead of the other keys in any object, so a column with that name comes first wherever the statement selects it. queryWithColumns(sql, params?, options?) returns each row as an array of values in the order in which the statement selects them, together with the details of every result column, so the row contains both IDs.
The next version of accounts.ts records the transfer in a transfers table and reads it back through a join. The green lines are the lines that this step adds.
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.execute('CREATE TABLE transfers (id INTEGER PRIMARY KEY, from_account INTEGER NOT NULL, to_account INTEGER NOT NULL, amount INTEGER NOT NULL)')
await db.executeBatch('INSERT INTO accounts (id, holder, balance) VALUES (?, ?, ?)', [
[1, 'customer-1', 5000],
[2, 'customer-2', 2000],
])
const source = await db.queryOne<Account>('SELECT id, holder, balance FROM accounts WHERE id = ?', [1])
if (source === 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')
await tx.execute('INSERT INTO transfers (from_account, to_account, amount) VALUES (?, ?, ?)', [1, 2, 1000])
})
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))
const statement = await db.queryWithColumns(
'SELECT t.id, a.id, a.holder, t.amount FROM transfers t JOIN accounts a ON a.id = t.to_account ORDER BY t.id',
[],
{ maxRows: 500, maxBytes: 1_048_576 },
)
console.log(JSON.stringify(statement, (_key: string, value: unknown): unknown => typeof value === 'number' ? Number(value.toFixed(2)) : value, 2))
const firstAccount = await db.queryWithColumns('SELECT id, holder FROM accounts ORDER BY id', [], { maxRows: 1 })
console.log(JSON.stringify({ rows: firstAccount.rows, truncated: firstAccount.truncated }, (_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 })
}
}Both result columns are called id, but the row contains the transfer's ID of 1 and the account's ID of 2 in separate slots. Each entry of columns has five fields, which are name, declaredType, table, column, and database. Sirannon sets a field to null when it has no value to report, which covers the last four fields of a column that an expression such as count(*) produces and any field that the driver can't report, as Drivers shows. Sirannon executes the read on the same connections as query, with the same hooks, metrics, read concern, and integer handling, so it refuses every statement that it refuses in query.
Set maxRows or maxBytes when someone else writes the statement, such as a person who types SQL into a console, so that Sirannon returns no more rows from one read than your process has memory for. Set each limit to a whole number from 0 to 2^53-1, because Sirannon refuses any other value with INVALID_READ_LIMIT before SQLite reads a row. With a limit, Sirannon steps through the result one row at a time and stops at whichever limit the rows reach first, so Sirannon returns from a recursive query that has no end as well. It then sets truncated to 'rows' or 'bytes', or to null when the answer contains every row. Sirannon reads one row past maxRows to tell a stopped read from a complete one, which is why Sirannon returns truncated: 'rows' with the first account alone for the second call above. For the same reason, Sirannon answers a read with maxRows: 0 with the column details and no rows, and with truncated: 'rows' when the result has a row. To stop a statement that takes too long, set an execution time limit on the call.
Sirannon counts 8 bytes towards maxBytes for every value, to which it adds the length of the UTF-8 encoding of each TEXT value and the length of each BLOB. It leaves out the first row that takes the total past the limit, so the answer contains at most maxBytes bytes by that count. Because Sirannon counts 8 bytes for every value, Sirannon can reach the limit on a result of many NULL or empty values too.
Without a limit, Sirannon fetches every row in one driver call, as query does. With a limit, Sirannon allocates memory only for the rows that the answer returns, although on better-sqlite3 and Bun each step can take longer than one row of the single call. On Bun, Sirannon fails a read with a limit whose result has two columns of the same name with COLUMN_DETAILS_UNSUPPORTED, because bun:sqlite steps through rows only as objects keyed by column name. Give each column a distinct name with AS, or read without limits.
Move money in a transaction
transaction(callback) passes the callback a transaction handle, whose query, execute, and executeBatch methods use the connection of the transaction. Await each statement before the callback finishes.
Sirannon commits when the callback resolves and rolls back when it throws. transaction() returns the value that the callback returns. When SQLite refuses the commit, Sirannon raises TRANSACTION_ERROR.
The program checks both updates inside the transaction, so when SQLite changes no row for either update, the callback throws and Sirannon rolls the debit and the credit back together.
Sirannon refuses statements through the transaction handle once the callback returns or throws, so it fails a later call through a saved handle with TRANSACTION_CLOSED. Use the tx that Sirannon passes inside the callback, and use the database handle for work after it.
On the wa-sqlite and Expo drivers, Sirannon fails a database call that needs the writer while a transaction callback is in progress with WRITER_HELD_BY_CALLBACK, so send those statements through tx. Call bulkLoad and checkpoint once the callback ends, because Sirannon fails them inside a transaction with BULK_LOAD_IN_TRANSACTION and CHECKPOINT_IN_TRANSACTION.
Group statements through transaction() or executeTransaction(), because Sirannon executes every call on shared connections. Sirannon refuses BEGIN, COMMIT, END, ROLLBACK, SAVEPOINT, and RELEASE in query and execute with FORBIDDEN_SQL, since SQLite can add the writes of the next caller to a transaction that one caller opens that way. Sirannon refuses a CREATE or a DROP of a temporary table, view, index, or trigger in those methods with the same code, because SQLite attaches the object to the connection, where later callers can find it in place of a table of the same name.
When a query hook refuses a statement inside a transaction, Sirannon raises the refusal through the transaction. When you catch an error inside the callback, the callback executes its later statements, so let the error escape when the whole operation has to roll back.
You can also pass executionTimeoutMs to transaction(callback, options?), so that Sirannon counts the callback and every statement in it against one limit. When SQLite stops a statement at that limit, Sirannon rolls the whole transaction back, even when the callback catches the error, as Execution time limits explains.
Copy the write-ahead log into the database file
By default, Sirannon opens each database in SQLite's WAL mode, in which SQLite writes every change first to a log file beside the database. checkpoint() asks SQLite to copy the log into the database file and to empty the log. The last version of accounts.ts calls it once the reads finish, and it prints a warning when the log contains frames after the checkpoint.
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.execute('CREATE TABLE transfers (id INTEGER PRIMARY KEY, from_account INTEGER NOT NULL, to_account INTEGER NOT NULL, amount INTEGER NOT NULL)')
await db.executeBatch('INSERT INTO accounts (id, holder, balance) VALUES (?, ?, ?)', [
[1, 'customer-1', 5000],
[2, 'customer-2', 2000],
])
const source = await db.queryOne<Account>('SELECT id, holder, balance FROM accounts WHERE id = ?', [1])
if (source === 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')
await tx.execute('INSERT INTO transfers (from_account, to_account, amount) VALUES (?, ?, ?)', [1, 2, 1000])
})
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))
const statement = await db.queryWithColumns(
'SELECT t.id, a.id, a.holder, t.amount FROM transfers t JOIN accounts a ON a.id = t.to_account ORDER BY t.id',
[],
{ maxRows: 500, maxBytes: 1_048_576 },
)
console.log(JSON.stringify(statement, (_key: string, value: unknown): unknown => typeof value === 'number' ? Number(value.toFixed(2)) : value, 2))
const firstAccount = await db.queryWithColumns('SELECT id, holder FROM accounts ORDER BY id', [], { maxRows: 1 })
console.log(JSON.stringify({ rows: firstAccount.rows, truncated: firstAccount.truncated }, (_key: string, value: unknown): unknown => typeof value === 'number' ? Number(value.toFixed(2)) : value, 2))
const checkpoint = await db.checkpoint()
if (!checkpoint.emptied) console.warn('A reader kept the log in place, so try the checkpoint again once it finishes')
console.log(JSON.stringify(checkpoint, (_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 })
}
}SQLite reports zero frames once it empties the log, so both counts are zero beside emptied: true. Sirannon executes the checkpoint on the writer connection under the writer lock, which means that Sirannon starts the checkpoint once the writes in progress finish. A reader that has a transaction open can prevent SQLite from emptying the log. On a database without backups, checkpoint() then reports busy: true at once, so call it again once the reader finishes. When another connection holds the checkpoint lock, SQLite reports no counts, so Sirannon sets both counts to zero and busy to true.
On a database that you open with the backups option, Sirannon performs checkpoint() in a turn of the backup cycle, in which it captures the log before it checkpoints the log. Sirannon fails the call with BACKUP_ERROR when it skips that turn of the cycle, as it does while the replication group is out of reach. Sirannon refuses PRAGMA wal_checkpoint in query and execute with FORBIDDEN_SQL, because SQLite can restart a backup copy from its first page after a checkpoint on a reader connection. On a database with backups, SQLite can also discard log frames that no backup contains yet when you checkpoint outside the cycle.
To copy the database while writes continue, call backup(), because after a checkpoint, SQLite can start a new log for later writes before a separate copy of the file finishes.
Tune the connection pool
On a driver that opens several connections, Sirannon gives each database one writer and a pool of readers, which it uses in turn. Sirannon opens up to four readers by default, and at least one even when readPoolSize is zero. Sirannon opens the first reader of a writable database on its first read, and another reader whenever every open reader is busy at the start of a read, while it opens the first reader of a read-only database together with the database. On a driver with a single connection, Sirannon serves reads from the writer as well.
For a Node.js database with several connections, use a file path, because separate connections to :memory: each open a separate in-memory database.
connectionIdleTimeout is 30,000 milliseconds by default. Once a database goes that long without a read, Sirannon closes its readers. Once the database goes that long without a read or a write, Sirannon closes the writer as well, so that every connection of an idle database is closed. Subscriptions and device connections remain open in the meantime, because Sirannon opens a connection again on the next read, write, or change to the file. Sirannon leaves the writer open on a database with backups or writerWorker, an in-memory or URI path, a driver with a single connection, or an active replication engine, and while a backup copy or a key change is under way. It also leaves the first reader of a read-only database open. Set connectionIdleTimeout to zero to leave every connection open until the database closes.
A setting that a PRAGMA statement changes on a connection lasts until Sirannon closes that connection, so Sirannon opens the next connection without that setting once connectionIdleTimeout passes. Configure durability through the synchronous option, because Sirannon applies that level to every writer that it opens.
Configure the connections through four options. With walMode, which is true by default, Sirannon turns WAL mode on. readPoolSize sets the most readers that Sirannon opens for a database, while connectionIdleTimeout sets how long Sirannon leaves an unused connection open. With readOnly, Sirannon opens every connection read-only. Every database option is in Configuration.
synchronous is 'normal' by default and also takes 'off', 'full', and 'extra'. Choose the level that matches the failures that your application has to survive. Sirannon restores the level that you configure once the temporary policy of a bulk load ends.
Handle errors
Catch SirannonError to compare its code in your program. When SQLite fails a statement, Sirannon raises QUERY_ERROR. A driver message can include details of the SQL, so leave those messages out of public error responses.
The server removes internal details from an error before it returns the error to a remote caller. Every structured refusal is in Error codes, including expired transactions, execution time limits, and failures of the writer worker.