Core features

Change data capture

Subscribe to committed row changes, filter by row membership, and handle replacement writes and schema changes.

Sirannon records changes to watched tables through SQLite triggers and delivers them to subscribers after commit. A subscriber can observe inserts, updates, and deletes without repeatedly querying the application's tables.

Open a database and watch a table

Create the table before calling watch(table), and watch it before making the writes that need capture. Repeating watch reuses the installed triggers. unwatch removes them when capture is no longer needed.

Table matching follows SQLite's ASCII case rules, while events use the table spelling stored in the schema. A missing table, view, or virtual table fails watch with CDC_ERROR.

Subscribe to every change

The complete watch.ts example creates a temporary file and waits for its three changes before closing. That wait matters because the polling timer does not keep a standalone process alive.

watch.ts
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 identifies an insert, update, or delete. row describes the current row, and oldRow includes the previous row for updates and deletes. seq is a bigint sequence; convert it before JSON serialisation. txId and txEnd identify transaction boundaries for consumers that apply changes together.

Filter to the changes you care about

db.on('orders').filter({ status: 'shipped' }) subscribes to changes in membership of that matching set. With the example's writes, the second order enters as an insert, and the first order also enters as an insert when its status changes to shipped.

A row that leaves the set produces a delete with an empty row and its previous matching value in oldRow. An update between two matching versions remains an update. Interpret the event as a change to the filtered set, because a filtered insert can represent an update to the underlying table.

Capture replacement writes and schema changes

When REPLACE conflict handling deletes a stored row, Sirannon records that delete before the replacement write. This applies to INSERT OR REPLACE, REPLACE, UPDATE OR REPLACE, and constraints configured with ON CONFLICT REPLACE.

A user-defined BEFORE trigger can insert or update a row after Sirannon captures the conflicting rows. If the same statement then replaces that row, Sirannon can miss its delete. Account for this limit when combining replacement writes with such triggers.

For a table without a declared primary key, changing the rowid produces a delete for the old rowid followed by an insert for the new one. When dropping a watched column, Sirannon removes and rebuilds the capture triggers inside a savepoint; a failed alteration restores the earlier triggers.

Tune the polling pipeline

cdcPollInterval defaults to 50 milliseconds. A lower interval performs the polling query more frequently, which can reduce delivery delay while increasing polling work.

cdcRetention defaults to 3,600,000 milliseconds. It controls how long Sirannon retains captured changes, subject to active consumers that retain history. A consumer whose cursor falls outside the available history needs to reload its state.

Sirannon validates table and column identifiers before generating trigger SQL. Use ordinary application tables with identifiers accepted by that validation.

Change data capture over the network

The server delivers changes to WebSocket subscribers. The client SDK can resume subscriptions after reconnection. A server refusal during restoration ends that subscription and reaches its onError callback; a transient connection failure can retry.

onCDCEvent reports change delivery through the metrics callbacks. The callback includes the subscriber count, which can be zero when no filter matches.

When you want the current answer

A change subscription reports events for your application to apply. A live query maintains a query result from those events and exposes its current rows and updates.