Backups

Backups

Copy an open database to a local file and repeat the copy on a schedule.

Sirannon can copy an open database while your application continues to read and write. SQLite copies pages in steps, so writes can commit between those steps.

Use a local copy for a portable snapshot. Use backup destinations to upload a copy, backup chains to capture later changes, and restoreBackup to rebuild an earlier state. A replication group can select one node to take the backups.

What your runtime can copy

db.backupCapabilities() reports the backup operations that the driver supports without accessing the filesystem. A driver needs both SQLite's stepped copy interface and a backup engine before fullCopy is true.

FieldMeaning
fullCopyThe driver can copy an open database.
streamedCopySirannon can send the copy to a destination without staging a local file.
stagedCopySirannon can copy to a local file before uploading it.
localDiskRequiredThe value is 'equal-to-backup' when Sirannon requires staging, and 'none' otherwise.
scheduleSirannon can repeat the full copy on a timetable.

The Node SQLite and better-sqlite3 drivers support full copies. The Bun, wa-sqlite, and Expo drivers lack a backup engine, so db.backup() fails with BACKUP_UNSUPPORTED on those drivers. For a device that uses sync, snapshot recovery can replace its local database contents from the server.

Copy the database to a file

This complete backup.ts example creates an isolated temporary directory, takes a copy, and checks the rows through a second registry. The cleanup removes only that temporary directory.

backup.ts
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { Sirannon } from '@delali/sirannon-db'
import { betterSqlite3 } from '@delali/sirannon-db/driver/better-sqlite3'
 
const directory = await mkdtemp(join(tmpdir(), 'sirannon-backup-'))
const source = new Sirannon({ driver: betterSqlite3() })
const check = new Sirannon({ driver: betterSqlite3() })
 
try {
  const db = await source.open('orders', join(directory, 'orders.db'))
  await db.execute('CREATE TABLE orders (id INTEGER PRIMARY KEY, total INTEGER NOT NULL)')
  await db.executeBatch('INSERT INTO orders VALUES (?, ?)', [[1, 12850], [2, 6400], [3, 24999]])
  const copyPath = join(directory, 'backups', 'orders.db')
  await db.backup(copyPath)
  const copy = await check.open('copy', copyPath)
  const rows = await copy.query('SELECT id, total FROM orders ORDER BY id')
  console.log(JSON.stringify(rows, (key: string, value: unknown): unknown =>
    typeof value === 'number' ? Number(value.toFixed(2)) : value, 2))
} finally {
  await check.shutdown()
  await source.shutdown()
  await rm(directory, { recursive: true, force: true })
}

Sirannon takes the writer lock before the first copy step and releases it after that step. Later writes through Sirannon can proceed between copy steps. Another connection that writes to the file or performs a restart checkpoint can make SQLite restart the copy from page one.

The returned report includes databaseId, sourcePath, the absolute destPath, runId, pageCount, pageSize, byteLength, and restarts. Sirannon also reports startedAt, finishedAt, and durationMs in milliseconds.

Sirannon creates the destination's parent directory recursively. It rejects a path with a control character, a path with a .. segment, or an existing destination file with BACKUP_ERROR. Choose a new destination for each copy so that an existing backup remains available.

For an encrypted database, the copy retains the database's encryption. Retain the matching key and use an encryption-enabled driver when you reopen the copy.

Repeat the copy on a schedule

A service can call scheduleBackup() after it opens its database. This complete scheduled-backup.ts keeps the process alive until a shutdown signal, because the scheduler's timer does not keep Node alive.

scheduled-backup.ts
import { mkdir } from 'node:fs/promises'
import { Sirannon } from '@delali/sirannon-db'
import { betterSqlite3 } from '@delali/sirannon-db/driver/better-sqlite3'
 
await mkdir('./data', { recursive: true })
const sirannon = new Sirannon({ driver: betterSqlite3() })
 
try {
  const db = await sirannon.open('orders', './data/orders.db')
  await db.execute('CREATE TABLE IF NOT EXISTS orders (id INTEGER PRIMARY KEY, total INTEGER NOT NULL)')
  db.scheduleBackup({
    cron: '0 */6 * * *',
    destDir: './data/backups',
    maxFiles: 5,
    timezone: 'Europe/London',
    onBackup: (copy): void => console.log(copy.destPath),
    onBackupTimeoutMs: 600_000,
    onError: (error): void => console.error('Scheduled backup failed', error),
  })
  await new Promise<void>((resolve): void => {
    process.once('SIGINT', resolve)
    process.once('SIGTERM', resolve)
  })
} finally {
  await sirannon.shutdown()
}

The five-field cron expression takes a copy every six hours in the configured time zone. A six-field expression adds seconds at the front, so */5 * * * * * takes a copy every five seconds. Closing the database cancels its schedule.

OptionDefaultBehaviour
cronRequired.Sirannon accepts five or six fields.
destDirRequired.Sirannon creates this directory recursively.
maxFiles5Sirannon keeps this many matching files; a value at or below zero disables rotation.
timezoneThe host's zone.Sirannon evaluates the expression in this IANA time zone.
onBackupAbsent.Sirannon calls this function with each completed copy's report.
onBackupTimeoutMs600000Sirannon waits this many milliseconds for the callback; zero removes the deadline.
onErrorAbsent.Sirannon reports schedule failures through this callback.

Sirannon creates files in the form backup-{ISO timestamp}.db, replacing colons and full stops with hyphens. Rotation considers files that match backup-*.db, sorts them by modification time, and removes the oldest files beyond maxFiles. Use a separate directory for each database's schedule.

An asynchronous onBackup callback can upload the completed file. Sirannon waits for its promise before rotating files and starting another copy. If the callback fails, Sirannon reports the error through onError and continues rotation.

When the callback exceeds onBackupTimeoutMs, Sirannon reports BACKUP_ERROR and continues without cancelling the callback. Rotation can then delete a file that the callback is uploading, so set the deadline to cover your upload's maximum supported duration.

The scheduler skips times during host suspension and during the missing hour of a daylight saving change. It fires once during a repeated hour. After a backward clock change, it waits until the clock passes the last fired time. It does not backfill missed copies.

When a copy cannot finish

  • BACKUP_RESTARTED means SQLite restarted the copy more than three times, or the copy made no progress across 256 steps. Reduce competing writes or use backupTo() with appropriate limits.
  • BACKUP_STALLED means no copy step completed within 30 seconds. Check whether synchronous work blocks the event loop.
  • BACKUP_ERROR includes refused paths and other copy failures.

Sirannon removes a failed copy's partial file. If SQLite continues copying after Sirannon reports a timeout, Sirannon waits for that copy to stop before removing the file.

backupTo() accepts restartLimit, stallTimeoutMs, noProgressStepLimit, and pagesPerStep. The destination guide explains those options.