A backup destination stores numbered pieces through an object that you supply. Sirannon includes no storage client, so your destination controls credentials, access permissions, and storage retries.
Use db.backupTo() for a full copy. Use the same destination with continuous backups to capture later changes.
What a destination has to do
The BackupDestination interface requires writePiece, readPiece, and listPieces. The optional writePieceIfAbsent provides an atomic conditional write.
writePiece(name, index, bytes)stores the bytes and replaces an earlier piece at the same name and index.readPiece(name, index)returns the most recently stored bytes or throws when the piece is absent.listPieces(name)returns{ index, byteLength }entries for that exact name, or an empty array when none exist.writePieceIfAbsent(name, index, bytes)atomically stores an absent piece and returnstrue; an existing piece remains unchanged and producesfalse.
Accept pieces in any order, because SQLite writes its first page last. Keep separate backup names independent, because chains also store their records as pieces. List every page of an object-storage listing so that recovery can find every piece.
The conditional write is necessary when several nodes claim entries in one chain list. For example, S3 accepts IfNoneMatch: '*', Google Cloud Storage accepts ifGenerationMatch: 0, and Azure Blob Storage accepts If-None-Match: *. Use the storage client's documented conflict response to return false; propagate other errors.
Copy a database into external storage
This complete folder-destination.ts publishes each piece through a temporary file. A rename replaces an ordinary piece, while an atomic hard link publishes a piece only when its final path is free. The hashed backup name prevents a storage name from becoming a filesystem path.
import { createHash, randomUUID } from 'node:crypto'
import { link, mkdir, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises'
import { join } from 'node:path'
import type { BackupDestination, BackupPiece } from '@delali/sirannon-db'
const hasCode = (error: unknown, code: string): boolean =>
typeof error === 'object' && error !== null && 'code' in error && error.code === code
export const folderDestination = (root: string): BackupDestination => {
const directoryFor = (name: string): string =>
join(root, createHash('sha256').update(name).digest('hex'))
const publish = async (name: string, index: number, bytes: Uint8Array, exclusive: boolean): Promise<boolean> => {
if (!Number.isSafeInteger(index) || index < 0) throw new Error('Invalid backup piece index')
const directory = directoryFor(name)
await mkdir(directory, { recursive: true, mode: 0o700 })
const target = join(directory, String(index))
const temporary = join(directory, `pending-${randomUUID()}`)
try {
await writeFile(temporary, bytes, { flag: 'wx', mode: 0o600, flush: true })
if (exclusive) {
try {
await link(temporary, target)
} catch (error) {
if (hasCode(error, 'EEXIST')) return false
throw error
}
} else {
await rename(temporary, target)
}
return true
} finally {
await rm(temporary, { force: true })
}
}
return {
async writePiece(name, index, bytes): Promise<void> {
await publish(name, index, bytes, false)
},
async writePieceIfAbsent(name, index, bytes): Promise<boolean> {
return publish(name, index, bytes, true)
},
async readPiece(name, index): Promise<Uint8Array> {
if (!Number.isSafeInteger(index) || index < 0) throw new Error('Invalid backup piece index')
return new Uint8Array(await readFile(join(directoryFor(name), String(index))))
},
async listPieces(name): Promise<BackupPiece[]> {
const directory = directoryFor(name)
let entries: string[]
try {
entries = await readdir(directory)
} catch (error) {
if (hasCode(error, 'ENOENT')) return []
throw error
}
const pieces: BackupPiece[] = []
for (const entry of entries) {
if (!/^(0|[1-9][0-9]*)$/.test(entry)) continue
const index = Number(entry)
if (!Number.isSafeInteger(index)) throw new Error('Invalid stored backup piece index')
const info = await stat(join(directory, entry))
if (!info.isFile()) throw new Error('A backup piece is not a file')
pieces.push({ index, byteLength: info.size })
}
return pieces
},
}
}Use an application-controlled directory with restricted permissions. The example requires a filesystem with hard-link support. A backup on the database's disk does not protect against losing that disk, so use an independent storage location for disaster recovery.
Save this complete copy-to-storage.ts beside the helper. Its temporary directory keeps the demonstration separate from existing databases.
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { Sirannon } from '@delali/sirannon-db'
import { assembleFromDestination } from '@delali/sirannon-db/backup'
import { betterSqlite3 } from '@delali/sirannon-db/driver/better-sqlite3'
import { folderDestination } from './folder-destination.ts'
const directory = await mkdtemp(join(tmpdir(), 'sirannon-destination-'))
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)')
const ORDER_COUNT = 5000
await db.executeBatch('INSERT INTO orders VALUES (?, ?)',
Array.from({ length: ORDER_COUNT }, (_, index): [number, number] => [index + 1, (index % 400) * 100]))
const destination = folderDestination(join(directory, 'pieces'))
const report = await db.backupTo({
destination,
name: 'orders-full.db',
pieceBytes: 32_768,
onProgress: (progress): void => console.log(progress),
})
await source.shutdown()
const rebuiltPath = join(directory, 'rebuilt.db')
await assembleFromDestination(destination, report, rebuiltPath)
const rebuilt = await check.open('rebuilt', rebuiltPath)
console.log(await rebuilt.queryOne('SELECT COUNT(*) AS orders FROM orders'))
} finally {
await check.shutdown()
await source.shutdown()
await rm(directory, { recursive: true, force: true })
}The example uses 32 KiB pieces so that this generated dataset spans several pieces. A deployed service can use the default 16 MiB size. Choose a new backup name for each independent copy, because reusing a name for a smaller copy can leave older trailing pieces.
BackupRunReport includes the destination name, chain and backup identifiers, piece count, byte count, page count, page size, restarts, route, and optional fingerprint. It also includes timestamps and the copy and transfer durations. backupTo() takes one full copy; it does not start a recurring change capture cycle.
Watch a large copy as it moves
onProgress receives copy and transfer reports. Use totalPages and remainingPages for the copy, and piecesWritten and bytesWritten for the transfer. The report also includes runId and restarts.
On the staged route, the copy finishes before transfer starts, so transfer reports have zero remaining pages. On the streamed route, copy and transfer updates can interleave. The number of callbacks depends on the copy steps and stored pieces.
Turn the pieces back into a database
assembleFromDestination(destination, report, path) reconstructs one full copy from its numbered pieces. It checks the listing before opening the target, then writes each piece at index * pieceBytes and verifies the recorded byte count and fingerprint.
Choose a new output path, because assembly opens that file for replacement. If a download or verification fails after the file opens, Sirannon removes the incomplete output. Missing or extra pieces, incorrect byte counts, and digest mismatches produce BACKUP_DESTINATION_ERROR.
Assembly reconstructs a backupTo() copy. Use restoreBackup for a chain containing a full copy and later change files. An encrypted full copy remains encrypted after assembly, so reopening it requires an encryption-enabled driver and the matching key provider.
Which route the bytes take
The streamed route sends pieces through Sirannon's compiled SQLite virtual filesystem extension as SQLite writes them. It requires no staged full copy on local disk. The staged route copies to a local temporary file before uploading it, so it requires free space for that copy.
db.backupCapabilities() reports streamedCopy, stagedCopy, and localDiskRequired. The report's route identifies which route a particular copy used.
The Node driver can stream on Node 23 and later; Node 22 uses staging. better-sqlite3 requires SQLITE_USE_URI=1 before its module loads. That setting enables URI interpretation for paths beginning with file:, so validate application database paths before enabling it.
Sirannon installs a platform-specific VFS binary through optional dependencies. If your platform has no published binary, build the extension and supply vfsExtensionPath to the driver. Both Node SQLite and better-sqlite3 accept that option. One process can load the extension into only one SQLite build, so use separate processes for streamed copies through different builds.
A streamed copy requires pieceBytes to be a positive multiple of 512. With fingerprinting enabled, Sirannon downloads every stored piece to compute the digest, so allow for that additional read traffic. fingerprint: false removes the digest check.
Options
| Option | Default | Behaviour |
|---|---|---|
destination | Required. | Sirannon stores and reads pieces through this object. |
name | A timestamp-based backup-*.db name. | Sirannon stores pieces under this name. |
chainId | A random identifier. | Sirannon includes this chain identifier in the report. |
pieceBytes | 16777216 | Sirannon uses this positive whole-number size for each complete piece. |
fingerprint | true | Sirannon records a SHA-256 digest. |
pagesPerStep | 256 | SQLite copies this many pages per step. |
restartLimit | 3 | Sirannon fails after more restarts with BACKUP_RESTARTED. |
noProgressStepLimit | 256 | Sirannon limits consecutive steps without copying a new page. |
stallTimeoutMs | 30000 | Sirannon limits the time without a completed step. |
destinationTimeoutMs | 600000 | Sirannon limits each destination call to these milliseconds; zero removes the deadline. |
stagingDir | The system's temporary directory. | Sirannon stages a full copy here when required. |
onProgress | Absent. | Sirannon reports copy steps and stored pieces through this callback. |
When a destination call hangs
A destination call that exceeds its deadline fails with BACKUP_DESTINATION_ERROR. The same code covers rejected destination calls. The error identifies the backup name and piece when those values are available.
The deadline limits Sirannon's wait; your storage client must also bound its network requests and handle cancellation. Over the server, a destination failure produces HTTP 502.