SQLite migrations
The migration runner, drift policy, rollback, upgrades, and policy-store tables on SQLite.
SQLite has no procedural SQL, so migrations are a function: applyResourceSharingMigrations(executor, descriptor, retry?) validates and applies the schema in one retried BEGIN IMMEDIATE transaction.
SQLite DDL is transactional, so a failed check leaves the database exactly as it was. Run it on every
deploy, before serving: there is no list of applied steps a later release could skip.
import {
applyPolicyStoreMigrations,
applyResourceSharingMigrations,
type ParameterizedSqliteExecutor,
type SqliteResourceDescriptor,
} from "@rolebook/sharing-sqlite";
declare const executor: ParameterizedSqliteExecutor;
declare const projectTable: SqliteResourceDescriptor;
await applyResourceSharingMigrations(executor, projectTable);
await applyPolicyStoreMigrations(executor); // only for versioned sharing createResourceSharingMigrations(descriptor) returns the DDL a fresh database receives, one statement per
step, for review and schema snapshots. Do not run those statements yourself: CREATE TABLE IF NOT EXISTS
would silently reuse a drifted table.
What the runner does
- Requires the application table to be an ordinary table in
mainwithTEXTtenant and ID columns and the resource-version column. - Binds
sharingTablePrefixto this exact descriptor inrolebook_sharing_descriptor_binding. A prefix bound to another descriptor is rejected. - Reuses an existing unique, non-partial, BINARY-collated index on exactly
(tenant, id)(a primary key qualifies) or creates one. - Validates every existing sharing table and the key guard, adds missing columns (the application’s
rolebook_sharing_revision, and columns added by later releases), creates missing tables, indexes, and the key guard, then validates everything again.
All sharing tables are STRICT. Timestamps are INTEGER milliseconds since the Unix epoch. Column
collations are probed once per changed table definition and cached in the binding table; clear its
collation_validation entry to force a full probe.
Drift policy
Reruns verify existing objects and fail closed instead of reusing a drifted one: table kind (must be
STRICT), columns and their types and nullability, BINARY collations on every TEXT column, primary
keys, lookup indexes, the invitation recipient check, live foreign keys
((tenant_id, resource_id) to (tenant, id) with ON DELETE CASCADE ON UPDATE CASCADE), the revision
column (INTEGER NOT NULL with a constant zero default), and the key guard trigger. Missing indexes and a
missing guard are created.
SQLite cannot alter a constraint in place, so repairing drift means rebuilding the table the documented
SQLite way (create, copy, drop, rename) before rerunning. Drop <prefix>_rolebook_key_guard first, in the
same transaction as the rebuild, and rerun the migration right after: until it runs, deletions through the
adapter refuse to start and nothing guards key changes.
Upgrades handled by reruns
A rerun adds, in place and without a rebuild:
expires_at INTEGERon the member table andmembership_expires_at INTEGERon the invitation table (existing rows stay permanent);incarnation_id TEXTon the owner and audit tables, its index, an identifier for every owner row, and (once) the attribution of earlier history by the lifecycle events of the time;- the key guard trigger and the revision-floor table, backfilled once;
expected_sharing_revision INTEGERon the lifecycle table;created_at INTEGERon the idempotency table, stamping existing rows with the run’s instant;policy_versionon the idempotency table, for versioned replays.
A column already present with another type, or declared NOT NULL, is rejected before any DDL. After the
key-guard upgrade, application code that changes an initialized resource’s tenant or ID directly fails.
The SQLite adapter always names created_at when it writes an idempotency record, so migrate before
serving this release.
Rolling upgrades: do not issue expiring grants or invitations until every instance runs a release with expiry. An older instance writes owner and audit rows without an incarnation identifier; its audit rows are never listed, and the next write through the new release (or a migration rerun) gives such an owner row an identifier.
Rollback
applyResourceSharingRollbackMigrations(executor, descriptor, options?, retry?) checks the retained
descriptor registry, then drops sharing-owned state in one transaction: the key guard first, then the
revision-floor, lifecycle, idempotency, invitation, member, and owner tables.
createResourceSharingRollbackMigrations(descriptor, options?) lists those steps with their data loss.
Audit history is kept unless { dropAudit: true }, and the registry row is always kept, so retained audit
history can never be rebound to another table. The application’s revision column and (tenant, id) index
are never dropped. Freeze sharing writes, export the sharing data, restore the old store, and verify
access-list parity before running it.
Policy-store tables
applyPolicyStoreMigrations(executor, { tablePrefix?, retry? }) creates the policy-version, activation,
active-pointer, tenant-role, tenant-role revision, and policy-audit tables in one BEGIN IMMEDIATE
transaction and fails closed on drift. createPolicyStoreMigrations() lists the DDL,
createPolicyStoreRollbackMigrations() the drops, and policyStoreTables(prefix) the names. The default
prefix is rolebook. Keep them in the same database file as the sharing tables.
They also create a permanent policy header (protocol version, the store identity ["main", prefix]
and a catalog generation) and an append-only hierarchy catalog in main. Every store operation and
the policy fence check the header first and refuse a temp shadow of any policy table; a store
migrated before this release answers HIERARCHY_UNAVAILABLE (policy_profile_mismatch) until
applyPolicyStoreMigrations runs again. An empty catalog is the normal flat state.
applyPolicyStoreRollbackMigrations(executor) runs the rollback in one transaction; its first step
refuses while the catalog holds any registered hierarchy descriptor.
applyPolicyCatalogRegistration() appends
control prefixes to that catalog.
hierarchyControlTables() names the control tables,
and createHierarchyControlMigrations()
installs them.
createSqliteGroupGraphControl() builds the
graph commands for that prefix and stores the configuration as sha256: plus 64 hexadecimal characters.