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. fullCopy is true only when a driver has both SQLite's stepped copy interface and a backup engine.

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

The complete backup.ts program below creates an isolated temporary directory, takes a copy, and checks the rows through a second registry. Its finally block 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. Your application can write through Sirannon between the later 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 each copy leaves the earlier backups in place.

Sirannon encrypts the copy of an encrypted database under the key of that database. Retain the matching key, and use a driver with encryption turned on when you reopen the copy.

Repeat the copy on a schedule

A service can call scheduleBackup() after it opens its database. The complete scheduled-backup.ts program waits for a shutdown signal before it exits, because the scheduler's timer leaves Node free to exit.

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()
}

With the five-field cron expression 0 */6 * * *, Sirannon takes a copy every six hours in the configured time zone. A six-field expression adds seconds at the front, so with */5 * * * * * Sirannon takes a copy every five seconds. When you close the database, Sirannon cancels its schedule.

OptionDefaultBehaviour
cronRequired.Sirannon accepts five or six fields.
destDirRequired.Sirannon creates this directory recursively.
maxFiles5Sirannon retains this many matching files, and a value at or below zero turns rotation off.
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. When it rotates the files, Sirannon considers those 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. When the callback fails, Sirannon reports the error through onError and rotates the files all the same.

When the callback takes longer than onBackupTimeoutMs, Sirannon reports BACKUP_ERROR and moves on without cancelling the callback. During rotation, Sirannon can then delete a file that the callback is uploading, so set the deadline longer than the longest upload that you support.

The scheduler skips the times that pass while the host is suspended and the missing hour of a daylight saving change, while it fires once during a repeated hour. After a backward clock change, it waits until the clock passes the last time at which it fired. The scheduler takes no copy later for a time that it skipped.

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 higher limits.
  • BACKUP_STALLED means no copy step completed within 30 seconds. Check whether synchronous work blocks the event loop.
  • Sirannon reports BACKUP_ERROR for a refused path and for every other copy failure.

Sirannon removes a failed copy's partial file. When SQLite goes on 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.