Core features

Bulk load

Import rows in one transaction, choose the import's durability, and handle a failure to restore the configured writer settings.

bulkLoad imports parameter sets in one transaction under a selected durability level. SQLite can then commit the whole import together, which avoids a separate commit for each row.

On a synchronous driver, writes and disk flushes block the calling thread. Enable a writer worker when the serving thread needs to continue answering requests during an import.

Load a dataset

bulkLoad(sql, paramsBatch, options?) accepts one statement and an array of parameter arrays. Each inner array supplies the values for one execution of the statement.

The complete import-events.ts file below generates its data with one editable count. It uses a temporary database file so that repeating the example does not collide with an earlier import.

import-events.ts
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { Sirannon, SirannonError } from '@delali/sirannon-db'
import { betterSqlite3 } from '@delali/sirannon-db/driver/better-sqlite3'
 
const directory = await mkdtemp(join(tmpdir(), 'sirannon-import-'))
const EVENT_COUNT = 10_000
const paramsBatch = Array.from({ length: EVENT_COUNT }, (_value: unknown, index: number): [number, string] => [
  index + 1,
  JSON.stringify({ type: 'page_view', path: '/products', sessionId: index % 5000 }),
])
 
const sirannon = new Sirannon({ driver: betterSqlite3() })
 
try {
  const db = await sirannon.open('analytics', join(directory, 'analytics.db'))
  await db.execute('CREATE TABLE events (id INTEGER PRIMARY KEY, payload TEXT NOT NULL)')
  const summary = await db.bulkLoad('INSERT INTO events (id, payload) VALUES (?, ?)', paramsBatch, {
    durability: 'normal',
  })
  console.log(JSON.stringify(summary, null, 2))
} catch (error) {
  if (error instanceof SirannonError && error.code === 'DURABILITY_RESTORE_FAILED') {
    console.error('Check the committed rows before retrying the import')
  }
  throw error
} finally {
  try {
    await sirannon.shutdown()
  } finally {
    await rm(directory, { recursive: true, force: true })
  }
}

rowsLoaded counts the parameter sets, while changes counts the affected rows. Sirannon returns this summary without materialising one result object for every row.

Choose the durability used during the import

durability accepts 'off' or 'normal' and defaults to 'off'. The example uses a file with write-ahead logging enabled.

Use 'normal' with a WAL database when the file contains data that you need to retain. SQLite preserves corruption safety under that configuration, although a power loss can discard recent commits. With 'off', a crash can corrupt the database, so use it only where the whole file can be rebuilt from the source data.

The database's synchronous option determines the level to restore after loading. It defaults to 'normal'; set it at open when ordinary writes require another level.

Restore the writer settings before later writes

Sirannon serialises the import through the writer, so other writes cannot commit under its temporary durability setting. The loader restores the configured synchronous level on success and failure.

After a committed load that changes rows, Sirannon can checkpoint the WAL at the restored level. A reader can prevent a complete checkpoint, so Sirannon retries up to three times and leaves any remaining pages for a later checkpoint. A synchronous checkpoint can block the calling thread while it flushes the log.

An open database with continuous backups leaves checkpointing to its backup cycle, whatever the load's checkpoint option says. This preserves the log frames until the cycle captures them.

If restoring durability fails after a committed import, the call raises DURABILITY_RESTORE_FAILED. Check the rows before retrying the import, because replaying a non-idempotent statement can duplicate writes. Sirannon tries to restore the configured setting before every later write and refuses that write with the same code while restoration fails.

Call bulkLoad outside a transaction callback. A call inside one fails with BULK_LOAD_IN_TRANSACTION; use the callback's tx.executeBatch for rows that must share that transaction.

Load over the server

The server exposes POST /db/{id}/load and a load WebSocket message. Both require acceptSql: true, because they contain SQL, and both accept the statement, parameter sets, and durability. Each request must fit under maxBodyBytes.

RemoteDatabase.loadAll divides an iterable or async iterable into requests and returns the combined { rowsLoaded, changes }. Each batch commits separately, so the whole remote import is not one transaction.

For a service that already exposes the analytics database with SQL enabled, save this separate client file as remote-import.ts. Set SIRANNON_URL to that service's URL and SIRANNON_TOKEN to its accepted credential. The server guide describes authentication and TLS.

remote-import.ts
import { SirannonClient } from '@delali/sirannon-db/client'
 
const url = process.env.SIRANNON_URL
const token = process.env.SIRANNON_TOKEN
if (!url || !token) throw new Error('Set SIRANNON_URL and SIRANNON_TOKEN')
 
const EVENT_COUNT = 10_000
const rows = Array.from({ length: EVENT_COUNT }, (_value: unknown, index: number): [number, string] => [
  index + 1,
  JSON.stringify({ type: 'page_view', path: '/products', sessionId: index % 5000 }),
])
 
const client = new SirannonClient(url, {
  transport: 'http',
  headers: { Authorization: `Bearer ${token}` },
})
 
try {
  const db = client.database('analytics')
  await db.execute('CREATE TABLE IF NOT EXISTS events (id INTEGER PRIMARY KEY, payload TEXT NOT NULL)')
  const summary = await db.loadAll(
    'INSERT INTO events (id, payload) VALUES (?, ?) ON CONFLICT(id) DO UPDATE SET payload = excluded.payload',
    rows,
    { batchSize: 1000, durability: 'normal' },
  )
  console.log(JSON.stringify(summary, null, 2))
} finally {
  client.close()
}

loadAll retains at most two batches in memory. The default batchSize is 1000. The client rejects a non-positive or non-integer size with INVALID_ARGUMENT before sending a request. Choose a size whose encoded rows fit the server's body limit.

The client requests a checkpoint only for the last batch. Every batch restores durability on the server, and a database with continuous backups continues to leave checkpointing to its cycle. For explicit batching, db.load(sql, paramsBatch, durability?, checkpoint?) exposes the checkpoint flag directly.

Handle refusals and uncertain outcomes

CodeWhat happened
INVALID_DURABILITYThe requested level was neither 'off' nor 'normal'.
BULK_LOAD_IN_TRANSACTIONA transaction callback called bulkLoad.
DURABILITY_RESTORE_FAILEDSirannon could not restore the configured writer setting.
SQL_NOT_ACCEPTEDThe server kept SQL access disabled.
BULK_LOAD_UNSUPPORTEDThe execution target offers no bulk-load method.
PAYLOAD_TOO_LARGEThe request exceeded the server's body limit.

An import can also receive the writer-worker errors. Reconcile an indeterminate outcome before retrying, and use explicit keys with idempotent statements when the application needs safe retries.