Sirannon records the changes to each watched table through SQLite triggers and delivers them to subscribers once they commit. A subscriber therefore receives inserts, updates, and deletes without querying the tables of your application again and again.
Open a database and watch a table
Create the table before you call watch(table), and watch it before the writes that you want to capture. A second watch on the same table reuses the installed triggers. Call unwatch to remove those triggers when you want to stop capturing changes from that table.
Sirannon matches table names under SQLite's ASCII case rules, while each event contains the table name as SQLite stores it in the schema. watch fails with CDC_ERROR for a missing table, a view, or a virtual table.
Subscribe to every change
The complete watch.ts program below creates a temporary file and awaits its three changes before it shuts the registry down. Node.js can exit a process whose only pending work is Sirannon's timers and file watch, so a standalone process can end before Sirannon delivers the changes. For that reason, the program awaits a promise that resolves once Sirannon delivers the third change to the subscriber.
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { type ChangeEvent, Sirannon } from '@delali/sirannon-db'
import { betterSqlite3 } from '@delali/sirannon-db/driver/better-sqlite3'
const directory = await mkdtemp(join(tmpdir(), 'sirannon-changes-'))
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, status TEXT NOT NULL)')
await db.watch('orders')
const events: ChangeEvent[] = []
const delivered = Promise.withResolvers<void>()
const deadline = setTimeout((): void => delivered.reject(new Error('Change delivery exceeded the example deadline')), 5000)
const subscription = db.on('orders').subscribe((event: ChangeEvent): void => {
events.push(event)
if (events.length === 3) delivered.resolve()
})
const writeOrders = async (): Promise<void> => {
await db.execute('INSERT INTO orders (id, status) VALUES (?, ?)', [1, 'pending'])
await db.execute('INSERT INTO orders (id, status) VALUES (?, ?)', [2, 'shipped'])
await db.execute('UPDATE orders SET status = ? WHERE id = ?', ['shipped', 1])
}
try {
await Promise.all([writeOrders(), delivered.promise])
console.log(JSON.stringify(events.map((event: ChangeEvent): Record<string, unknown> => ({
type: event.type,
id: event.row.id,
status: event.row.status,
oldStatus: event.oldRow?.status,
})), (_key: string, value: unknown): unknown => typeof value === 'number' ? Number(value.toFixed(2)) : value, 2))
} finally {
clearTimeout(deadline)
subscription.unsubscribe()
}
} finally {
try {
await sirannon.shutdown()
} finally {
await rm(directory, { recursive: true, force: true })
}
}event.type is insert, update, or delete. row contains the current row, while oldRow contains the previous row for an update or a delete. seq is a bigint sequence, so convert it before you serialise an event to JSON. txId and txEnd mark the boundaries of each transaction for a consumer that applies changes together.
Filter to the changes that you care about
db.on('orders').filter({ status: 'shipped' }) subscribes to changes in the membership of the set that the filter matches. With the writes of the example, the second order enters the set as an insert, while the first order enters the set as an insert too once its status changes to shipped.
A row that leaves the set produces a delete with an empty row and its last matching value in oldRow, while Sirannon reports a change between two matching versions as an update. Read each event as a change to the filtered set, because a filtered insert can stand for an update to the table underneath.
Capture replacement writes and schema changes
When REPLACE conflict handling deletes a stored row, Sirannon records that delete before the write that replaces the row. Sirannon applies that rule to INSERT OR REPLACE, REPLACE, UPDATE OR REPLACE, and constraints that declare ON CONFLICT REPLACE.
A BEFORE trigger that you define can insert or update a row after Sirannon captures the conflicting rows, in which case Sirannon can miss the delete of that row when the same statement then replaces it. Allow for this limit when you combine replacement writes with such triggers.
For a table without a declared primary key, a change to the rowid produces a delete for the old rowid followed by an insert for the new one. When you drop a watched column, Sirannon removes and rebuilds the capture triggers inside a savepoint so that it can restore the earlier triggers when the alteration fails.
Capture changes through migrations
Sirannon captures changes through a migration or a rollback on every table that a process or an earlier session watches, because it restores the capture triggers of those tables after each schema statement. Sirannon therefore goes on capturing changes through a migration that copies a watched table into a new one, drops the old table, and renames the new table to the old name, as Migrations shows.
When a migration creates a table, Sirannon installs its triggers at the next statement that alters or drops a table, an index, a trigger, or a view, or at the end of the migration. Sirannon installs no triggers after a CREATE statement, so a migration can create its tables and indexes before it copies rows into them. Until it installs the triggers, Sirannon leaves every write to the new table out of the change log, including the copied rows, although it captures every write that follows. A subscriber to a watched table therefore receives no events for the rows that a migration copies, while it receives the writes after the migration as usual.
Choose how quickly changes reach subscribers
cdcPollInterval, which is 50 milliseconds by default, sets the shortest gap between the starts of two queries of the change log. While a table has a subscriber, Sirannon queries the log after each write through the database and after the driver reports a write to the file from another process, so it sends no query to the log while nobody writes to the database.
The Node.js, better-sqlite3, and Bun drivers report writes from another process through a watch on the directory of each database file. Every 30 seconds, they also compare the size and the modification time of the file and its write-ahead log with the last values that they recorded, so that they report a write whose file event the operating system drops. With the wa-sqlite and Expo drivers, with a URI path, and after a watch fails, Sirannon also queries the log once per interval while a table has a subscriber.
A lower interval shortens the longest delay between a commit and its delivery, although Sirannon can then query the log more often while your application writes in quick succession.
cdcRetention is 3,600,000 milliseconds by default. It sets how long Sirannon stores the captured changes, although Sirannon stores a change beyond that period until every active subscription, device cursor, and replication peer moves past it. A consumer whose cursor falls outside the stored history has to reload its state. When you delete a row from a watched table, _sirannon_changes contains the deleted row until Sirannon removes it at the end of the retention period, so set cdcRetention with the data that you have to erase in mind.
Sirannon validates the table and column identifiers before it generates the trigger SQL, so watch ordinary application tables whose identifiers pass that validation.
Change data capture over the network
The server delivers changes to WebSocket subscribers, while the client SDK can resume a subscription after it reconnects. When the server refuses the subscription while the client restores it, the client calls the onError callback and ends the subscription. After a temporary connection failure, however, the client can reconnect.
Sirannon reports each delivery of changes through the onCDCEvent metrics callback, with the number of subscribers, which can be zero when no filter matches.
When you want the current answer
A change subscription reports events for your application to apply, while a live query updates the result of a query from those events and gives you its rows and its updates.