Reference / SQL API for Bun and Node

SQL API for Bun and Node

Every public class, function and type of the SQL engine in @tinyshed/tinystore, generated from its source. The SQL guide explains how to use them, and the Python, Go and Rust pages list the same API.

Columns

ts
type Columns<T> = {
    [K in keyof T]: T[K][]
}

A row type's columns: an array of each of its fields.

Row

ts
type Row = Record<string, SqlValue>

A row as SQLite gave it, by its columns' names.

Migrations

ts
type Migrations = string | Record<string, string> | readonly {
    name: string
    sql: string
}[]

A database's migrations: a directory of .sql files named 0001_notes.sql, 0002_tags.sql, or the files themselves by name, for a program bundled into one file. A relative directory is the working directory's.

DatabaseOptions

ts
interface DatabaseOptions {
    /** applied when the file has not, and checked at every open; without them the file opens as it is */
    migrations?: Migrations
    /**
     * How far this database's commits go before they return, where the
     * store's own is not this file's: `'os'` for what may be lost to a power
     * loss, beside a store of what may not. Its buckets and queues commit
     * with it. A database open already keeps what it was opened with.
     */
    durability?: Durability
    /**
     * Whether backups take the database; `false` keeps its file and the
     * bytes of its files in `local/` rather than `sql/`, where no backup
     * looks, open or not, and no node copies it: each node that opens it
     * writes its own. A name lives in one folder: one whose file lies in the
     * other is InvalidError, naming both.
     */
    backup?: boolean
}

Column

ts
interface Column {
    name: string
    type?: string
}

A column a statement answers: its name as its rows name it, and the type its table declares for it where it is a table's own column, as SQLite keeps it, INTEGER or varchar(80); none for an expression.

Done

ts
interface Done {
    changes: number
    lastInsertRowid: number | bigint
}

What a write changed: the rows, and SQLite's rowid of the row it inserted, 0 when none.

Statement

ts
type Statement = [text: string | TemplateStringsArray | Sql, ...values: unknown[]]

A statement in any of the ways a call takes it: a template whose values are its values, the text and the values of its ?s, the text and one object of named values, or a piece of SQL from sql.

db.all`select * from notes where id = ${id}`
db.all('select * from notes where id = ?', id)
db.all('select * from notes where id = :id', { id })

Sql

ts
class Sql {
    readonly text: string
    readonly values: readonly SqlArg[]
    readonly bare: boolean
    readonly now: Unit | undefined
}

A piece of SQL and the values of its ?s, which are always values and never SQL. sql makes one; a call, a batch and a table's query take it.

BoundStatement

ts
class BoundStatement {
    readonly database: Home
    readonly text: string
    readonly values: readonly SqlArg[]
}

A statement bound to the database that runs it, from db.statement: what a stream's where keeps a key to, as SQL's in (select …) does. A stream lives in records.db and belongs to no database, so the statement says whose it is. Nothing runs until a query reads it.

SqlTag

ts
interface SqlTag {
    (strings: TemplateStringsArray, ...values: unknown[]): Sql
    (text: string, ...values: unknown[]): Sql
    /** conditions joined with or, in parentheses; an empty or finds nothing */
    or(...conditions: Condition[]): Sql
    /** conditions joined with and, in parentheses; an empty and finds everything */
    and(...conditions: Condition[]): Sql
    /** a list for in (…), as one value SQLite reads with json_each: any length, the same statement */
    list(values: readonly unknown[]): Sql
    /** a value kept as its JSON */
    json(value: unknown): Sql
    /** a name, quoted, never SQL: a column a request chooses */
    ident(name: string): Sql
    /** a JSON list in column `name` holding `value` */
    has(name: string, value: unknown): Sql
}

A piece of SQL: sql`total >= ${min}`, or sql('total >= ?', min). Its helpers build the pieces a query's conditions are made of.

sql

ts
const sql: SqlTag

Database

ts
class Database implements Runner, Home {
    readonly name: string
    readonly label: string
}

An application's database: await store.database('app', { migrations }). The verb says what comes back: all the rows, one or none, one value, or what a write changed. A write with returning goes through a read's verb and runs on the writer, its rows given once it is durable.

Database.handle

ts
handle(connection: Connection): Promise<number>

Database.keep

ts
keep(method: number, bytes: Uint8Array, make: (connection: Connection) => Promise<Uint8Array>): Open

Database.via

ts
via(what: string): Via

Database.statement

ts
statement(...given: Statement): BoundStatement

A statement bound to this database, for a stream's where, which keeps a key to the values its one column gives: nothing runs until a query reads it, once as the query starts, on a reader of this file.

const teachers = db.statement`select id from teachers`
await events.count({ since: '1d', where: { userId: teachers } })

Database.bucket

ts
bucket<T = unknown>(name: string, options?: BucketOptions): Bucket<T>

A bucket of values by key kept in this database's file, beside its tables, as store.bucket keeps one in kv.db: the same calls, and its writes commit with the rows in db.tx, through tx.with(bucket).

const sessions = db.bucket<Session>('sessions', { idle: '30d' })

Database.queue

ts
queue<S extends StandardSchemaV1>(name: string, options: QueueOptions & {
        schema: S
    }): Queue<StandardSchemaV1.InferOutput<S>>
queue<T = unknown>(name: string, options?: QueueOptions): Queue<T>

A queue of jobs kept in this database's file, as store.queue keeps one in jobs.db: the same calls and workers, and its jobs commit with the rows in db.tx, through tx.with(queue). It shares the database's writer, which is the point and its cost.

const emails = db.queue<Email>('emails', { attempts: 5 })

Database.files

ts
files(name: string, options?: FilesOptions): Files

A set of files kept in this database's file, as store.files keeps one in blobs.db: the same calls, and its writes commit with the rows in db.tx, through tx.with(files). A file's bytes past 16 KiB lie in the folder beside the database's file.

const packages = db.files('packages', { maxFileSize: '10MiB' })

Database.events

ts
events(stream: string, options?: EventsOptions): Events

The store's stream of events stream, opened through this database: the same calls and reads as store.events(stream) gives, the stream in records.db where every stream lives. Its appends inside db.tx, through tx.with(audit), and in db.batch, through audit.appending, are kept in this database's file with the rows and reach the stream once they commit, before the call returns: an event exists exactly when the change it records does.

const audit = db.events('audit')

Database.searchIndex

ts
searchIndex<T = Row>(name: string, options: TableIndexOptions): TableIndex<T>

An index of a table of this database, kept in its file: its rows found again by their words, vectors or both, each hit's value its row as all reads it. The table owns the rows and the index follows them: every change of a row, by any statement, trigger or migration, reaches it in the commit that makes it, and one by a process beside the store within a second. Change it by opening it with other options under the same name, and never version its name.

const articles = db.searchIndex<Article>('articles_search', { table: 'articles', fields: { title: 2, body: 1 } })

Database.mirror

ts
mirror<T = Row>(table: string, options: MirrorOptions): Mirror<T>

A table that mirrors another system: its replace takes the source's list of a scope and its upsert a change of some rows, and each answers what was added, changed and gone, writing only the difference.

const works = db.mirror<Work>('works', { key: ['course_id', 'id'], gone: 'gone_at', changeOn: ['grade'] })

Database.dropSearchIndex

ts
dropSearchIndex(name: string): Promise<boolean>

Drops a table's index this database keeps, its triggers off the table; says whether there was one.

Database.all

ts
all<T = Row>(...statement: Statement): Promise<T[]>

Every row a statement gives: db.all<Note>\select * from notes where author_id = ${id}``

Database.one

ts
one<T = Row>(...statement: Statement): Promise<T | undefined>

The one row a statement gives, or undefined; two are InvalidError, and a write that gave them rolls back.

Database.scalar

ts
scalar<T = SqlValue>(...statement: Statement): Promise<T>

The one value of the one row a statement gives, as count(*) does; null as SQL answers it.

Database.describe

ts
describe(...statement: Statement): Promise<Column[]>

The columns a statement answers, in its order, whether or not it answers a row: the server compiles it and runs nothing. Values of its ?s are not read and may be left out; a statement that writes is InvalidError.

const columns = await db.describe`select id, title from notes where author_id = ${id}`
// [{ name: 'id', type: 'TEXT' }, { name: 'title', type: 'TEXT' }]

Database.columns

ts
columns<T = Row>(...statement: Statement): Promise<Columns<T>>

What all gives, by its columns: an array a column where all gives an object a row, for rows by the thousand, a chart's points. It comes faster, and a chart takes it as it is.

const { ts, cpu } = await db.columns<Sample>`select ts, cpu from samples where host = ${host} order by ts`

Database.each

ts
each<T = Row>(...statement: Statement): AsyncGenerator<T>

The rows a statement gives, one at a time as their parts arrive: an export that holds a part, not every row, however many there are. The server reads them a part at a time from one snapshot, which lasts five seconds at most: a walk that takes longer fails limit, and is read a page at a time with a table's list, or ordered by its key with a table's each, which reads on past it.

Database.[walk]

ts
[walk]<T = Row>(piece: Sql, order: readonly Ordered[] | undefined): AsyncGenerator<T>

A statement's rows as the server reads them, want: each; ordered by order, a unique column last, the server reads on past one snapshot.

Database.table

ts
table<S extends StandardSchemaV1>(name: string, options: TableOptions & {
        schema: S
    }): Table<StandardSchemaV1.InferOutput<S>>
table<T = Row>(name: string, options?: TableOptions): Table<T>

A table of the database, typed where it opens: its rows' inserts and upserts, and queries built without SQL text. It costs nothing until its first call; open each once, in the module that owns it.

const notes = db.table<Note>('notes', { types: { done: 'bool', created_at: 'time' } })

Database.batch

ts
batch(writes: readonly (Sql | Adding | Appending)[]): Promise<Done[]>

Writes known before they run, written as one: all of them or none, in a shared commit, and what each did, in their order. A write is a statement, a job's add of a queue opened from the database, queue.adding, which commits with the rows and changed 1 job, or 0 when its id was taken, or an event's append of a stream opened from it, audit.appending, which reaches the stream before the batch returns.

await db.batch([sql`update notes set body = ${body} where id = ${id}`, indexing.adding({ noteId: id })])

Database.tx

ts
tx<T>(fn: (tx: SqlTx) => T | Promise<T>): Promise<T>

Runs fn in a transaction that holds the writer, for writes that depend on what its reads found: returning commits, a throw rolls back. It runs once, five seconds at most, past which the server rolls it back; inside it, call nothing that waits on the world.

await db.tx(async tx => {
  const left = await tx.scalar<number>`select stock from items where sku = ${sku}`
  if (left < 1) throw new SoldOut()
  await tx.exec`update items set stock = stock - 1 where sku = ${sku}`
})

Database.rows

ts
rows(statement: Sql, want: Want): Promise<Answered>

Database.exec

ts
exec(...statement: Statement): Promise<Done>

Runs a write once it is durable; writes from many callers share a commit, each failing alone.

SqlTx

ts
class SqlTx implements Runner {
    readonly label: string
}

A database's transaction, from db.tx: its reads see its writes, and a call that fails leaves it as it was before the call. Its calls go one at a time, in order.

SqlTx.with

ts
with<T>(bucket: Bucket<T>): Bucket<T>
with<T>(queue: Queue<T>): TxQueue<T>
with<T>(channel: Channel<T>): TxChannel<T>
with(files: Files): Files
with(events: Events): TxEvents

A bucket or a queue opened from this database, inside the transaction: what it writes commits with the rows or not at all, and what it reads sees what the transaction wrote.

await db.tx(async tx => {
  const order = await tx.table<Order>('orders').insert({ user_id, total })
  await tx.with(emails).add({ order: order.id, to })
})

SqlTx.all

ts
all<T = Row>(...statement: Statement): Promise<T[]>

SqlTx.one

ts
one<T = Row>(...statement: Statement): Promise<T | undefined>

SqlTx.scalar

ts
scalar<T = SqlValue>(...statement: Statement): Promise<T>

SqlTx.exec

ts
exec(...statement: Statement): Promise<Done>

SqlTx.table

ts
table<T = Row>(name: string, options?: TableOptions): Table<T>

A table inside the transaction: its calls are the transaction's.

SqlTx.rows

ts
rows(statement: Sql, want: Want): Promise<Answered>

SqlTx.end

ts
end(commit: boolean): Promise<void>

Sends the last call: commit, or roll back, and waits for the server's word. A commit that left and was not answered, its connection lost or its wait cancelled, may have committed: its outcome is unknown. One that never left, its signal aborted or its connection lost first, was rolled back by the server, and fails as it ended.

ColumnType

ts
type ColumnType = 'bool' | 'time' | 'json' | 'bigint'

How a column SQLite keeps otherwise reads in JavaScript.

Mark

ts
interface Mark {
    column: string
    unit?: Unit | undefined
}

A column that marks a row with when it was marked, by the store's clock, and the unit it keeps that time in: { column: 'deleted_at', unit: 's' }. A column's name alone, or no unit, keeps milliseconds.

TableOptions

ts
interface TableOptions {
    /** the columns SQLite keeps as 0 or 1, unix milliseconds, JSON text or an integer past 2^53 */
    types?: Record<string, ColumnType>
    /** a Standard Schema, zod's or valibot's, that checks each row read */
    schema?: StandardSchemaV1
    /**
     * a nullable integer column that marks a row deleted with the store's
     * time, in unix milliseconds or, with `{ column, unit: 's' }`, seconds:
     * every query and write of the handle passes the marked rows by, unless
     * `withDeleted` or `deletedOnly` asks for them, and `delete` marks rather
     * than deletes
     */
    deleted?: string | Mark
    /**
     * an integer column, not null, default 0, that every update of the handle
     * raises by one; an update or a delete with `ifVersion` writes only rows at
     * the version it names
     */
    version?: string
}

UpsertOptions

ts
interface UpsertOptions<T> {
    /** the columns whose value, taken, makes the insert an update: the key */
    conflict: string | readonly string[]
    /** the columns the update sets from the row; none other changes */
    update: readonly (keyof T & string)[]
    /** the condition the row that holds the key must meet, its owner's, or it stays as it is */
    where?: Condition | undefined
}

What an upsert does when the row's key is taken.

RowPage

ts
interface RowPage<T> {
    rows: T[]
    next?: string
}

A page of a query's rows, and the cursor that reads the next; none after the last.

Query

ts
class Query<T = Row> implements Embeddable {}

A query on a table: a value, each call returning a new one, so that the first stays as it was. all, one, scalar, count, each and list read; update and delete write.

const urgent = await orders
  .where({ status: 'pending', deleted: false })
  .where(sql.or(sql`amount >= ${1000}`, { priority: 'high' }))
  .orderBy('created_at', 'desc')
  .limit(50)
  .all()

Query.where

ts
where(condition: Condition | string, ...values: unknown[]): Query<T>

Adds a condition with and: equal values, null as is null and a list as in (…); a piece of SQL from sql; or text and the values of its ?s. undefined is InvalidError, never a filter left out.

Query.select

ts
select<R = Row>(columns: string | Sql): Query<R>

The columns a row holds, as SQL text, and the shape of the row they make.

Query.include

ts
include<N extends string, C>(name: N, query: Query<C>): Query<T & Record<N, C[]>>

Gives each row the rows of another query as a list under name, from the same statement: the query names the row it belongs to in its where, by this table's alias, names its columns with select, and has a limit, which counts for each row. Every value comes back as it is kept, bytes and integers past 2^53 among them.

const latest = db.table<Post>('posts as p').select<{ id: string; title: string }>('p.id, p.title')
  .where('p.author_id = u.id').orderBy('p.id', 'desc').limit(3)
const authors = await db.table<User>('users as u').include('posts', latest).all()

Query.join

ts
join(table: string, on: string | Sql): Query<T>

Joins a table, 'users as u', on a condition as SQL text or a piece of SQL.

Query.leftJoin

ts
leftJoin(table: string, on: string | Sql): Query<T>

Joins a table whose columns may be null where no row of it meets the condition.

Query.groupBy

ts
groupBy(...columns: string[]): Query<T>

Groups the rows by columns, quoted as names.

Query.having

ts
having(condition: Condition | string, ...values: unknown[]): Query<T>

A condition on the groups, as where takes one.

Query.orderBy

ts
orderBy(column: string | Sql, direction?: Direction): Query<T>

Orders the rows by a column, quoted as a name, so that a sort a request chooses cannot be SQL, or by a piece of SQL: orderBy(sql`lower(title)`).

Query.limit

ts
limit(rows: number): Query<T>

Query.offset

ts
offset(rows: number): Query<T>

Query.toSQL

ts
toSQL(): {
        text: string
        values: SqlArg[]
    }

The text and the values the query sends, to read or to log.

Query.embedded

ts
embedded(): Sql

The query inside another piece of SQL: a subquery, in parentheses.

Query.all

ts
all(): Promise<T[]>

Query.one

ts
one(): Promise<T | undefined>

Query.scalar

ts
scalar<V = SqlValue>(): Promise<V>

Query.count

ts
count(): Promise<number>

Every row the conditions match, without the order and the limit.

Query.each

ts
each(): AsyncGenerator<T>

The rows one at a time, as their parts arrive: for more than fits in memory. The server reads them from one snapshot of five seconds at most; ordered by columns by their names, a unique one last, as list is, it reads on past that after the last row it sent, and any other walk fails limit there. Inside a transaction it reads the rows all does.

Query.list

ts
list(options?: {
        limit?: number | undefined
        after?: string | undefined
    }): Promise<RowPage<T>>

A page after the last row of the one before, by the query's order, which ends in a unique column so that no row is read twice or skipped. next reads the next page, and only of this query.

const first = await orders.orderBy('created_at', 'desc').orderBy('id', 'desc').list({ limit: 50 })
const second = await orders.orderBy('created_at', 'desc').orderBy('id', 'desc').list({ limit: 50, after: first.next })

Query.explain

ts
explain(): Promise<string[]>

SQLite's plan for the query, a line a step.

Query.update

ts
update(values: {
        [K in keyof T]?: T[K] | Sql
    } & Record<string, unknown>, options?: EditOptions): Promise<Done>

Sets columns of the rows the conditions match, and says how many changed. A versioned table's version goes up by one; with ifVersion, the update writes every row only if each is at that version, and otherwise nothing, failing ConflictError.

await tasks.where({ id: 1 }).update({ title: 'from b' }, { ifVersion: seen.version })

Query.delete

ts
delete(options?: EditOptions): Promise<Done>

Deletes the rows the conditions match, and says how many it deleted. On a table with a deleted column it marks the live ones instead, with the store's time in the mark's unit, and raises a versioned table's version; ifVersion is update's.

Query.withDeleted

ts
withDeleted(): Query<T>

The query of every row, those the deleted column marks among them.

Query.deletedOnly

ts
deletedOnly(): Query<T>

The query of the rows the deleted column marks, and of no other.

Query.restore

ts
restore(): Promise<Done>

Clears the mark of the marked rows the conditions match, whichever rows the handle shows, and says how many came back; a versioned table's version goes up by one.

Query.purge

ts
purge(): Promise<Done>

Deletes for good the rows the conditions match of those the handle shows: the marked ones of deletedOnly(), or every one of withDeleted(). A handle that shows the live rows alone refuses it, so that nothing live is purged by a handle that forgot to ask.

await tasks.deletedOnly().where`deleted_at < ${monthAgo}`.purge()

Table

ts
class Table<T = Row> extends Query<T> {
    readonly name: string
}

A table: its queries, and its rows' inserts and upserts.

const notes = db.table<Note>('notes', { types: { done: 'bool', tags: 'json', created_at: 'time' } })
const note = await notes.insert({ id: uuidv7(), author_id: userId, title: 'Buy milk', done: false, tags: [], created_at: new Date() })

Table.insert

ts
insert(row: Partial<T>): Promise<T>
insert(rows: readonly Partial<T>[]): Promise<T[]>

Inserts a row and gives it back as the file keeps it; a list of rows is one write, all of them or none. On a versioned table the row starts at version 0, whatever it gives for the column.

Table.upsert

ts
upsert(row: Partial<T>, options: UpsertOptions<T>): Promise<T | undefined>
upsert(rows: readonly Partial<T>[], options: UpsertOptions<T>): Promise<T[]>

Inserts a row, or, when its key is taken, sets the columns update names on the row that holds it, if that row meets where. It gives back the row as the file keeps it, or undefined when where kept it. A list of rows is one statement, all of them or none, and gives back the rows it wrote, without those whose key where kept. On a table with a deleted column the update clears a row's mark, since the row came back, and on a versioned one it raises the version.

MirrorOptions

ts
interface MirrorOptions {
    /** the columns that name a row at the source: a unique index or the table's primary key covers them */
    key: string | readonly string[]
    /** a column that marks what the source dropped with the store's time instead of deleting it: unix milliseconds, or seconds with `{ column, unit: 's' }` */
    gone?: string | Mark | undefined
    /** the columns whose change makes a row changed: every column the rows carry but the key's when absent */
    changeOn?: readonly string[] | undefined
    /** the columns SQLite keeps as 0 or 1, unix milliseconds, JSON text or an integer past 2^53, as a table's */
    types?: Record<string, ColumnType> | undefined
}

How a mirror opens: what names a row at the source, what marks it gone, and what makes it changed.

ReplaceOptions

ts
interface ReplaceOptions {
    /** writes nothing, and answers `suspect`, when fewer than this fraction of the scope's live rows would stay live */
    minKept?: number | undefined
}

How a replace guards against a list that cannot be right.

Diff

ts
interface Diff<T> {
    added: T[]
    changed: {
        before: T
        after: T
    }[]
    gone: T[]
    same: number
    suspect: boolean
}

What a mirror's call changed. A suspect answer wrote nothing.

Mirror

ts
class Mirror<T = Record<string, SqlValue>> {
    readonly table: string
}

A table that mirrors another system, from db.mirror: its replace takes the source's list of a scope, its upsert a change of some rows, and each answers what was added, changed and gone. A row the list gives as it is held is not written at all.

const works = db.mirror<Work>('works', { key: ['course_id', 'id'], gone: { column: 'gone_at', unit: 's' } })
const diff = await works.replace({ course_id: 1 }, fetched)

Mirror.replace

ts
replace(scope: Record<string, unknown>, rows: readonly Partial<T>[], options?: ReplaceOptions): Promise<Diff<T>>

Makes the scope, the rows whose columns hold its values, {} for the whole table, what rows lists: adds what the table lacks, writes what changed, and deletes, or marks gone, what the list leaves out. A row outside the scope is InvalidError, and so is one whose key holds a null. Values compare as the table keeps them: 4 given to a text column is '4', and a key's text compares by its unique index's collation. A list, or an answer, past one message goes in the parts of a run, as begin makes one, and writes in one commit all the same.

Mirror.upsert

ts
upsert(rows: readonly Partial<T>[]): Promise<Diff<T>>

Writes what rows adds and changes, a delta of the source's; its gone is always empty.

Mirror.begin

ts
begin(scope: Record<string, unknown>, options?: ReplaceOptions): MirrorRun<T>

Begins a replace of the scope whose list comes in parts: each add gives a part, and commit makes the scope what every part listed, in one write, so that only what no part named is gone. A run never committed writes nothing: closed, dropped, idle for five minutes, its connection lost or the store closed.

await using run = works.begin({ course_id: 1 })
for await (const page of pages) await run.add(page)
const diff = await run.commit()

MirrorRun

ts
class MirrorRun<T = Record<string, SqlValue>> implements AsyncDisposable {}

A mirror's replace whose list comes in parts, from mirror.begin. Its parts wait on the server, outside the table, until commit; one never committed writes nothing, and close lets go of it at once.

MirrorRun.add

ts
add(rows: readonly Partial<T>[]): Promise<void>

Gives a part of the list: rows of the first part's shape, inside the scope, each key once in the whole run. A part past one message goes as several. A part that fails ends the run.

MirrorRun.commit

ts
commit(): Promise<Diff<T>>

Makes the scope what every part listed, in one write, and answers what changed.

MirrorRun.close

ts
close(): Promise<void>

Lets go of a run not committed, which writes nothing; nothing after a commit.

MirrorRun.[Symbol.asyncDispose]

ts
[Symbol.asyncDispose](): Promise<void>

Generated from the source Updated 27 November 2026

esc
↑↓ navigate ↵ open ⇥ filter 0 results