A live query maintains the rows returned by a SQL statement as the underlying table changes. Use getState() to render the current rows, or apply the reported splices when another part of the application maintains a separate array.
Open a live query and read the result
live(sql, params?, options?) watches the table, reads its rows, and subscribes from that read's position. This sequence prevents a change between the first read and subscription from disappearing.
The complete live.ts example opens a temporary file and selects pending orders. It maintains a separate array from the subscription's splices, then waits until the committed writes appear before closing.
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { type LiveUpdate, Sirannon } from '@delali/sirannon-db'
import { betterSqlite3 } from '@delali/sirannon-db/driver/better-sqlite3'
interface PendingOrder {
id: number
total: number
}
const directory = await mkdtemp(join(tmpdir(), 'sirannon-live-'))
const sirannon = new Sirannon({ driver: betterSqlite3() })
try {
const db = await sirannon.open('shop', join(directory, 'shop.db'))
await db.execute('CREATE TABLE orders (id INTEGER PRIMARY KEY, total INTEGER NOT NULL, status TEXT NOT NULL)')
await db.executeBatch('INSERT INTO orders (id, total, status) VALUES (?, ?, ?)', [
[1, 4999, 'pending'],
[2, 12500, 'shipped'],
[3, 890, 'pending'],
])
const orders = await db.live<PendingOrder>('SELECT id, total FROM orders WHERE status = ? ORDER BY id', ['pending'])
const first = orders.getState()
if (first.status !== 'ready') throw new Error('The first live-query read did not finish')
const held: PendingOrder[] = [...first.rows]
const delivered = Promise.withResolvers<void>()
const deadline = setTimeout((): void => delivered.reject(new Error('Live delivery exceeded the example deadline')), 5000)
const unsubscribe = orders.subscribe((update: LiveUpdate<PendingOrder>): void => {
if (update.kind === 'ops') {
for (const operation of update.ops) {
if (operation.op === 'insert') held.splice(operation.index, 0, operation.row)
else if (operation.op === 'update') held[operation.index] = operation.row
else held.splice(operation.index, 1)
}
} else {
const state = orders.getState()
if (state.status === 'error') {
delivered.reject(state.error)
return
}
if (state.status === 'ready') held.splice(0, held.length, ...state.rows)
}
if (held.length === 2 && held[0]?.id === 3 && held[1]?.id === 4) delivered.resolve()
})
try {
await db.execute('INSERT INTO orders (id, total, status) VALUES (?, ?, ?)', [4, 2400, 'pending'])
await db.execute('UPDATE orders SET status = ? WHERE id = ?', ['shipped', 1])
await delivered.promise
console.log(JSON.stringify(held, (_key: string, value: unknown): unknown => typeof value === 'number' ? Number(value.toFixed(2)) : value, 2))
} finally {
clearTimeout(deadline)
unsubscribe()
await orders.close()
}
} finally {
try {
await sirannon.shutdown()
} finally {
await rm(directory, { recursive: true, force: true })
}
}Opening a live query requires write access because capture installs triggers. A read-only database fails with READ_ONLY.
Listen for updates
getState() returns a discriminated union. A pending state means the first read has not finished. A ready state contains rows and revalidating. An error state contains an error.
subscribe(listener) reports updates and returns a function that removes the listener. close() ends the query and drops its temporary probe table. Keep the service or screen active while observing changes, because the capture timer alone does not keep a Node process alive.
An onError option receives listener failures. Sirannon does not wait for a listener's returned promise, so coordinate asynchronous application work explicitly.
The update kinds are ops, rows, revalidating, and error. An ops update contains ordered splices for one transaction. A rows update follows a replacement read. While revalidating is true, the previous complete rows remain readable.
Apply the splices yourself
Seed a separate array from the first ready state before subscribing, as the example does. Apply each insert, update, and delete operation in order. Each operation supplies an index, and inserts and updates also supply a row.
For replacement reads, refill that array from getState().rows. Code that only renders the query can read getState() on every notification without maintaining another array.
How a change becomes a splice
Sirannon creates a temporary probe table with the base table's column types and collations. It evaluates the query's selection, filtering, and ordering against the changed rows, so that SQLite applies the same affinity and collation rules as a full read.
Sirannon rereads the table when a transaction contains more changes than the current result has rows, when a LIMIT window loses a row that the retained rows cannot replace, or when buffered transaction changes exceed their bound.
maxTransactionChanges defaults to 10,000, and an internal byte bound also limits buffering. rereadJitterMs defaults to 25 milliseconds and bounds a random delay before rereading, so that several queries can spread their read work.
What a live query can maintain
A live query supports a single-table statement. It refuses joins, aggregates, GROUP BY, HAVING, DISTINCT, compound selects, window functions, subqueries, and LIMIT without ORDER BY with CDC_ERROR.
It also refuses expressions whose value can change without a row event, such as random(), changes(), or a clock expression. For unsupported queries, subscribe through change data capture and recompute the application result.
Queries can reference rowid, oid, or _rowid_ when those identifiers are not declared columns. This requires either a table without a declared primary key or an INTEGER PRIMARY KEY, because capture must supply the base rowid. A rowid query against another primary-key shape fails with CDC_ERROR.
Run one over the network
A remote live query uses a registered read. Open it through RemoteDatabase.live(operation, args) on the WebSocket transport. HTTP fails with TRANSPORT_ERROR.
The server sends the first rows with the subscription reply, then sends updates that the client applies in order. The handle provides the same state, subscription, and close methods as a local query.
During a disconnect, the client retains the earlier rows and marks the query as revalidating. Reconnection creates another subscription and replaces the rows with the server's fresh answer. A server refusal ends restoration and reaches the error handler; a temporary connection failure can retry.
The client sends the digest from its cached capability report. After REGISTRY_MISMATCH, it refreshes capabilities once and subscribes again. A second refusal fails the query. Code generation produces typed references and a separate digest constant for application contract checks.
Local reread options configure a local db.live. Remote queries use the server's defaults.
Render one in React
useLiveQuery from @delali/sirannon-db/react subscribes through useSyncExternalStore and closes the query when the component unmounts. Pass the database, a registered read reference, and its arguments. The hook returns the same pending, ready, and error states.
The hook compares arguments by value, so an equivalent argument object does not reopen the query on each render. Set enabled: false when the query needs to wait for application data.
useCommand returns a stable callback for a registered write. Invoke that callback with the write's arguments and handle its rejected promise in the application. Registered operations and code generation explain the typed references that both hooks accept.