SQLite adapter
@rolebook/sharing-sqlite: a driver-neutral SQLite storage adapter for local-first, edge, and desktop apps.
@rolebook/sharing-sqlite gives the same guarantees as the PostgreSQL adapter
on SQLite: tenant-scoped reads, fenced mutations, revision compare-and-increment, idempotency, audit, and
fail-closed migrations, verified by the same contract. It never imports a driver;
thin executors ship for bun:sqlite (@rolebook/sharing-sqlite/bun) and local @libsql/client
(@rolebook/sharing-sqlite/libsql), and better-sqlite3 or node:sqlite need a few lines.
Named authorized queries need the worker-backed Bun executor from
@rolebook/sharing-sqlite/bun-query.
Every mutation runs in BEGIN IMMEDIATE, which takes the database write lock before the first statement
and holds it to commit. No other connection or process can commit in between, so the write lock is the
fence: no row locks are needed. Requirements: SQLite 3.37 or later with JSON support (RETURNING needs
3.35, STRICT tables 3.37, and JSON is built in from 3.38), WAL mode for file databases, and foreign
keys enabled on every connection.
Set up with bun:sqlite
import { Database } from "bun:sqlite";
import { trustedResource } from "rolebook";
import {
applyResourceSharingMigrations,
createSqliteMembershipEligibilityFence,
createSqliteSharingAdapter,
type SqliteResourceDescriptor,
} from "@rolebook/sharing-sqlite";
import { createBunSqliteExecutor } from "@rolebook/sharing-sqlite/bun";
const database = new Database("app.db");
database.run("PRAGMA journal_mode = WAL");
const executor = createBunSqliteExecutor(database); // also runs PRAGMA foreign_keys = ON
const projectTable = {
resourceType: "project",
table: "project",
tenantColumn: "workspace_id",
idColumn: "id",
resourceVersionColumn: "version",
sharingTablePrefix: "project",
resourceColumns: ["visibility"],
resourceFromRow: (row) =>
trustedResource(
{ type: "project", id: String(row.id) },
[{ type: "workspace", id: String(row.workspace_id) }],
{ visibility: String(row.visibility) },
),
} as const satisfies SqliteResourceDescriptor;
await applyResourceSharingMigrations(executor, projectTable);
export const projectAdapter = createSqliteSharingAdapter({
executor,
resource: projectTable,
lockEligibleSubjects: createSqliteMembershipEligibilityFence({
table: "member", // your organization-member table, for example Better Auth's
tenantColumn: "organization_id",
subjectIdColumn: "user_id",
}),
}); The descriptor is the PostgreSQL one without SQL types: IDs are TEXT with BINARY collation, the
application table is one unqualified table in main, and sharingTablePrefix is lowercase and globally
unique. The row passed to resourceFromRow also carries the reserved aliases
__rolebook_sharing_revision (and __rolebook_resource_version for an INTEGER version), read back as
exact text.
With libSQL
import { createClient } from "@libsql/client";
import { createLibsqlExecutor } from "@rolebook/sharing-sqlite/libsql";
const client = createClient({ url: "file:app.db" });
await client.execute("PRAGMA journal_mode = WAL");
const executor = createLibsqlExecutor(client); Remote libSQL (Turso, sqld) is not supported: createLibsqlExecutor() throws a TypeError for any
client whose protocol is not "file", before any statement runs. An embedded replica (a file: URL with
a syncUrl) is a local client and is accepted, but it reads locally and can lag the primary: send sharing
reads to the primary, or sync first, when a revocation must take effect immediately.
Executors
A ParameterizedSqliteExecutor has two methods: query(sql, values) runs one statement with ?
parameters, and transaction({ behavior }, operation) runs operation on one connection between
BEGIN IMMEDIATE (or BEGIN DEFERRED) and COMMIT, rolls back on error, keeps other callers off that
connection, and rejects nested transactions. Values are strings, numbers, bigints, null, or
Uint8Array.
createBunSqliteExecutor(database, options?) accepts any synchronous driver with bun:sqlite’s shape:
prepare(sql) returning a newly prepared statement each call (never a cached one: a cached statement
keeps the column names it first read, so after an ALTER TABLE it would label values with the wrong
columns), plus inTransaction. For better-sqlite3:
import BetterSqlite3 from "better-sqlite3";
import { createBunSqliteExecutor } from "@rolebook/sharing-sqlite/bun";
const database = new BetterSqlite3("app.db");
database.pragma("busy_timeout = 0");
const executor = createBunSqliteExecutor({
prepare(sql) {
const statement = database.prepare(sql);
return {
columnNames: statement.reader ? statement.columns().map((column) => column.name) : [],
all: (...values) => statement.all(...values),
run: (...values) => statement.run(...values),
};
},
get inTransaction() {
return database.inTransaction;
},
}); This block is not type-checked because better-sqlite3 is not a dependency of any Rolebook package. For
node:sqlite, wrap DatabaseSync the same way with statement.columns() and database.isTransaction.
createBunSqliteExecutor option | Default | Meaning |
|---|---|---|
enableForeignKeys | true | Run PRAGMA foreign_keys = ON when the executor is created. |
allowBusyTimeout | false | Accept a connection whose busy_timeout is not 0. |
One synchronous Database is one connection: open one connection (and executor) per concurrent writer.
With several connections to one file in one process, keep PRAGMA busy_timeout at 0, because a
synchronous busy wait blocks the event loop the lock holder needs; the adapter’s busy retry waits
asynchronously instead. The bun executor throws unless the timeout is 0; set allowBusyTimeout only for
a connection alone in its process. Never open one file through two copies of SQLite in one process (for
example bun:sqlite and libSQL): a closing connection of one copy can delete the WAL files the other still
uses.
WAL and foreign keys are required
A file database must be in WAL mode (PRAGMA journal_mode = WAL; it persists in the file). In the
rollback-journal modes, an open read on one connection makes another’s COMMIT fail with SQLITE_BUSY,
so migrations and every write transaction throw SqliteJournalModeError unless the mode is wal.
In-memory databases are exempt.
SQLite ignores foreign keys unless each connection enables them, and the live sharing tables rely on
ON DELETE CASCADE: without enforcement a deleted resource leaves orphaned grants a later resource with
the same ID would inherit. Every write transaction checks PRAGMA foreign_keys and throws
SqliteForeignKeysDisabledError when it is off. Every connection that deletes or moves application rows
must enable it too.
The migration also installs a key guard trigger, <prefix>_rolebook_key_guard, that refuses to change the
(tenant, id) of an application row that still has sharing rows. Move resources through
resourceMovedInTransaction().