API reference

node:sqlite

18/18Coverage16/18Strict (zero caveats)

Node's built-in node:sqlite, ported from Node's own src/node_sqlite.cc to TypeScript over the system libsqlite3 (linked only when a program imports the module). DatabaseSync and StatementSync are synchronous; rows are null-prototype objects, user functions, aggregates, the authorizer, sessions, serialization, tag stores and backup() all work as in Node. The one difference: Node bundles its own SQLite, while this uses the system library, so sessions and extension loading are as available as that library makes them.

Exact Works, with caveats Not supported

DatabaseSync

Exact
new DatabaseSync(path: string | Uint8Array | URL, options?: DatabaseSyncOptions)

Opens (or creates) a database: a file path, a file: URL, or ':memory:'. Every Node option is honoured — open, readOnly, enableForeignKeyConstraints, enableDoubleQuotedStringLiterals, allowExtension, timeout, readBigInts, returnArrays, allowBareNamedParameters, allowUnknownNamedParameters, defensive.

const db = new DatabaseSync(':memory:');
See it in a full example →

open / close / isOpen / isTransaction

Exact
db.open(): void; db.close(): void; db.isOpen: boolean; db.isTransaction: boolean

Opening, closing and state. Closing finalizes the database's statements; using one afterwards is ERR_INVALID_STATE, as in Node.

db.close();
See it in a full example →

exec / prepare

Exact
db.exec(sql: string): void; db.prepare(sql: string): StatementSync

exec runs one or more statements; prepare compiles a reusable statement.

const insert = db.prepare('INSERT INTO tasks (title) VALUES (?)');
See it in a full example →

location

Exact
db.location(dbName?: string): string | null

The backing file of an attached database, or null for an in-memory or temporary one.

db.location();
See it in a full example →

function

Exact
db.function(name: string, options?: FunctionOptions, fn: Function): void

Registers a SQL function written in TypeScript (deterministic, directOnly, useBigIntArguments, varargs). An exception it throws is rethrown from the statement that called it.

db.function('shout', (s: string) => s.toUpperCase() + '!');
See it in a full example →

aggregate

Exact
db.aggregate(name: string, options: AggregateOptions): void

Registers an aggregate (start, step, result) or, with inverse, a window function.

db.aggregate('total', { start: 0, step: (acc: number, v: number) => acc + v });
See it in a full example →

setAuthorizer

Exact
db.setAuthorizer(callback: ((action: number, ...args: (string | null)[]) => number) | null): void

Approves, denies or ignores each action SQLite compiles (sqlite.constants.SQLITE_OK/DENY/IGNORE).

db.setAuthorizer(() => constants.SQLITE_OK);
See it in a full example →

createSession / applyChangeset

Works, with caveats
db.createSession(options?): Session; db.applyChangeset(changeset: Uint8Array, options?): boolean

Records changes as a changeset or patchset and applies one elsewhere, with filter and conflict handlers.

const session = db.createSession();
See it in a full example →
⚠ Differences from standard
  • Available only where the system libsqlite3 is built with sessions (macOS's is); elsewhere ERR_INVALID_STATE — Node bundles its own SQLite

enableLoadExtension / loadExtension

Works, with caveats
db.enableLoadExtension(allow: boolean): void; db.loadExtension(path: string, entryPoint?: string): void

Loads a SQLite extension, when the database was opened with allowExtension.

db.enableLoadExtension(true);
See it in a full example →
⚠ Differences from standard
  • The system libsqlite3 on macOS omits extension loading, so loading one there is ERR_INVALID_STATE — Node bundles its own SQLite

serialize / deserialize / enableDefensive

Exact
db.serialize(dbName?: string): Uint8Array; db.deserialize(buffer: Uint8Array, options?): void

Snapshots a database to bytes and restores one from them.

const image = db.serialize();
See it in a full example →

createTagStore

Exact
db.createTagStore(maxSize?: number): SQLTagStore

Prepared statements cached by tagged-template SQL.

const sql = db.createTagStore();
See it in a full example →

run / get / all / iterate

Exact
stmt.run(...params): { changes, lastInsertRowid }; stmt.get(...params): object | undefined; stmt.all(...params): object[]; stmt.iterate(...params): Iterator

Rows are null-prototype objects (arrays with returnArrays); get() is undefined without a row; iterate() steps lazily.

const rows = db.prepare('SELECT * FROM tasks').all();
See it in a full example →

columns / sourceSQL / expandedSQL

Exact
stmt.columns(): ColumnDescription[]; stmt.sourceSQL: string; stmt.expandedSQL: string

Each result column's name, declared type and origin database/table/column; the statement's SQL, and its SQL with the bound values.

stmt.columns();
See it in a full example →

statement options

Exact
stmt.setReadBigInts(enabled: boolean): void

Per-statement versions of the database's reading and binding options.

stmt.setReadBigInts(true);
See it in a full example →

Parameter binding

Exact
stmt.get({ id: 2 })

Positional ? parameters, or a leading object binding :x/@x/$x (and the bare key). Numbers bind as REAL and bigints as INTEGER, as in Node.

db.prepare('SELECT title FROM tasks WHERE id = :id').get({ id: 2 });
See it in a full example →

Column value mapping

Exact
INTEGER → number | bigint, REAL → number, TEXT → string, BLOB → Uint8Array, NULL → null

An INTEGER past 2^53 is ERR_OUT_OF_RANGE unless readBigInts is set.

stmt.setReadBigInts(true);
See it in a full example →

Errors

Exact
ERR_SQLITE_ERROR { errcode, errstr }

SQLite failures throw an Error with code ERR_SQLITE_ERROR, errcode and errstr, as Node's.

try { db.exec('bogus'); } catch (e) { e.errcode; }
See it in a full example →

backup / constants

Exact
backup(sourceDb: DatabaseSync, path: string, options?): Promise<number>

Copies a database into a file a few pages per turn of the event loop, reporting progress; resolves the total page count.

await backup(db, 'copy.db');
See it in a full example →