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, SQLite blocks the calling thread while it writes and flushes to disk. Enable a writer worker when your process has to go on answering requests during an import.

Load a dataset

bulkLoad(sql, paramsBatch, options?) accepts one statement and an array of parameter arrays. Each inner array contains 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 each execution of the example starts from an empty file.

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 is the number of parameter sets, while changes is the number of affected rows. Sirannon returns this summary without materialising one result object for every row.

Choose the durability used during the import

Set durability to 'off' or 'normal', of which 'off' is the default. 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 you can rebuild the whole file from the source data.

After the load, Sirannon restores the level of the database's synchronous option. That option is 'normal' by default, so set it at open when your ordinary writes need another level.

Restore the writer settings before later writes

Sirannon serialises the import through the writer, so SQLite commits no other write under the temporary durability setting of the import. Sirannon restores the configured synchronous level whether the load succeeds or fails.

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. In a synchronous checkpoint, SQLite can block the calling thread while it flushes the log.

On an open database with continuous backups, Sirannon checkpoints only in a turn of the backup cycle, whatever the load's checkpoint option is set to, so that it keeps the log frames until it captures them.

If Sirannon fails to restore durability after a committed import, it fails the call with DURABILITY_RESTORE_FAILED. Check the rows before you retry the import, because SQLite can apply a non-idempotent statement twice when you replay it. 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, because Sirannon fails a call inside one with BULK_LOAD_IN_TRANSACTION. Use the callback's tx.executeBatch for rows that have to share that transaction.

Stop an import that takes too long

Pass executionTimeoutMs in the options of bulkLoad to cap how long SQLite can spend on the import, on a database that you open through betterSqlite3({ executionTimeouts: true }). When SQLite stops the import at that limit, Sirannon rolls every row of the import back and fails the call with EXECUTION_TIMEOUT, so you can retry the import without loading a row twice. Execution time limits contains a complete example.

Load over the server

The server serves POST /db/{id}/load and a load WebSocket message only with acceptSql: true, because both contain SQL. In both, the server accepts the statement, the parameter sets, and the durability. Keep each request under maxBodyBytes.

RemoteDatabase.loadAll divides an iterable or async iterable into requests and returns the combined { rowsLoaded, changes }. The server commits each batch separately, so it commits a remote import in several transactions.

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. The server restores durability after every batch, while on a database with continuous backups it checkpoints only in a turn of the cycle. For explicit batching, db.load(sql, paramsBatch, durability?, checkpoint?) exposes the checkpoint flag directly.

Handle refusals and uncertain outcomes

CodeWhat it means
INVALID_DURABILITYThe requested level is neither 'off' nor 'normal'.
BULK_LOAD_IN_TRANSACTIONA transaction callback calls bulkLoad.
DURABILITY_RESTORE_FAILEDSirannon cannot restore the configured writer setting.
SQL_NOT_ACCEPTEDThe server keeps SQL access disabled.
BULK_LOAD_UNSUPPORTEDThe execution target offers no bulk-load method.
PAYLOAD_TOO_LARGEThe request is larger than the server's body limit.
EXECUTION_TIMEOUTSQLite stops the import at its executionTimeoutMs, and Sirannon rolls every row of the import back.
INVALID_EXECUTION_TIMEOUTThe executionTimeoutMs is something other than a whole number from 1 to 2,147,483,647.
EXECUTION_TIMEOUT_UNSUPPORTEDYou set executionTimeoutMs on a driver that can't stop a statement.

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