PostgreSQL migrations
Generating, applying, upgrading, and rolling back the sharing and policy-store schema on PostgreSQL.
createResourceSharingMigrations(descriptor) returns the ordered steps for one resource table: the
sharing tables, their indexes and foreign keys, the generated rolebook_sharing_revision column, and a
unique (tenant, id) index on the application table (PostgreSQL requires the referenced composite key
to be unique; review that index before applying it to a large table).
import {
applyPostgresMigrations,
createPolicyStoreMigrations,
createResourceSharingMigrations,
type ParameterizedSqlExecutor,
type PostgresResourceDescriptor,
} from "@rolebook/sharing-postgres";
declare const executor: ParameterizedSqlExecutor;
declare const projectTable: PostgresResourceDescriptor;
declare const folderTable: PostgresResourceDescriptor;
// On every deploy, the complete lists:
await applyPostgresMigrations(executor, createResourceSharingMigrations(projectTable));
await applyPostgresMigrations(executor, createResourceSharingMigrations(folderTable));
await applyPostgresMigrations(executor, createPolicyStoreMigrations()); // only for versioned sharing How the runner applies steps
applyPostgresMigrations(executor, steps, options?) runs each step as its own transaction, so a step
that has to lock a table holds the lock only until that step commits:
- Each step starts with
SET LOCAL lock_timeout(lockTimeoutMs, 5 seconds by default). A step that cannot get its lock in time, deadlocks, or hits a serialization failure rolls back whole and is retried after a backoff (attempts, 5 by default;backoffMs,wait). - Any other error, or the last failed attempt, throws
PostgresMigrationErrorwith thestepname,attempts,sqlState, and the driver error ascause. The steps before it stay committed. - Every step validates the existing schema before it changes anything and is idempotent, so the next run resumes where the last stopped.
- Each step is one parameterless
executor.query()call, run by PostgreSQL as one implicitREAD COMMITTEDtransaction. A driver that prepares every call refuses the first step before anything changes.
Run one migration process at a time. If you apply the steps with your own migration tool, do the same:
one transaction per step, each starting with SET LOCAL lock_timeout, at READ COMMITTED, retried on a
lock timeout. Do not apply the whole list in one transaction.
Re-run every step on every deploy
Step names are stable across releases while their SQL changes: tightened validation, new columns, and foreign-key upgrades arrive as new SQL under existing names. A runner that records step names and skips the ones it has applied misses those changes. Re-run the complete list each time, or key recorded names by package version.
Re-running is cheap on an up-to-date schema: every step that adds a column, sets a default, or creates an index first checks the catalog (no table lock) and runs DDL only when something is missing.
What a rerun validates
Existing sharing tables are validated before reuse: column types and nullability, primary keys, the
invitation recipient constraint, and index shapes (columns, uniqueness, operator classes, collation, sort
order). Missing lookup indexes are recreated; incompatible ones are rejected. The sharing revision column
must be bigint NOT NULL with a constant zero default. Repair incompatible drift explicitly before
retrying.
The tenant and resource SQL types must match the application columns exactly. text and uuid are the
only accepted values, and both default to text.
Upgrades handled by reruns
Each of these arrives as new SQL in existing steps, applied by an ordinary rerun:
- Restricting keys. Live foreign keys become
ON DELETE CASCADE ON UPDATE RESTRICT. Re-adding a key validates every row under aSHARE ROW EXCLUSIVElock, so schedule it like any foreign-key addition. Afterwards, application code that changes an initialized resource’s tenant or ID directly fails with23001: move it throughresourceMovedInTransaction(). Deploy the adapter before running this migration. - Revision floors.
<prefix>_rolebook_revision_floorkeeps the highest sharing revision each key has held, outliving deletions and moves, so a resource re-created under a reused ID never repeats a revision a stale authorization expects. It is backfilled once. Never prune it, and grant the adapter’s role the same privileges as on the other sharing tables. - Membership expiry. Nullable
timestamptzcolumnsexpires_at(member) andmembership_expires_at(invitation). Existing rows stay permanent. - Audit incarnations. An
incarnation_idon the owner row (defaultgen_random_uuid()::text) and on audit rows, plus an index. The run that adds the audit column attributes existing history by the lifecycle events of the time; it rewrites the owner and audit tables underACCESS EXCLUSIVElocks, measured at about 10 seconds for 20,000 owners and 400,000 audit rows on PGlite. Plan a window for it. - Idempotency
created_at.created_at timestamptz NOT NULL DEFAULT now()and two indexes, needed by pruning. On a large table you can build the indexes concurrently first; see the package README for the exact statements. - Policy version on idempotency rows. A nullable
policy_versioncolumn, for versioned replays.
During a rolling upgrade, an instance on an older release keeps working against the upgraded schema, with the effects the package README describes (for example audit rows it writes carry no incarnation and are not listed).
Rollback
createResourceSharingRollbackMigrations(descriptor, { dropAudit? }) produces ordered DROP TABLE
statements for sharing-owned state. Its first step verifies the retained descriptor registry: a
mismatched descriptor, or a missing registry while sharing tables remain, aborts before any drop. It keeps
audit history by default and never drops the application’s revision column or (tenant, id) unique
index. Each step may carry a dataLoss note. { dropAudit: true } destroys audit history.
Rollback is a deliberate operation: freeze sharing writes, export owner, member, invitation, audit, lifecycle, idempotency, and revision-floor data, restore the previous store, verify access-list parity, then execute the steps. It cannot restore application rows deleted or moved since, nor raw invitation secrets (never stored). A default rollback followed by a migration for the same descriptor preserves the audit history.
Hierarchy control tables
createResourceSharingMigrations() also installs the descriptor’s hierarchy control profile: the
tenant writer barrier, hierarchy admission, hierarchy tenant, link, inventory and principal-generation
tables, the profile’s descriptor registry, and a tenant-key codec header. Unlike the sharing tables,
these are always schema-qualified by the profile and never resolved through search_path. The
profile is the descriptor’s hierarchyControl: { schema, prefix? } (prefix default
rolebook_control), or the schema of a schema-qualified table. An unqualified table without
hierarchyControl is unbound: its migration throws.
hierarchyControlTables() returns those
qualified names. createHierarchyControlMigrations()
installs the profile, including the group-graph tables.
createPolicyCatalogRegistrationMigrations()
appends the profile to the policy catalog. A graph command built with
createPostgresGroupGraphControl()
uses that same profile and stores its configuration as sha256: plus 64 hexadecimal characters.
The control tables, registry rows and bindings are permanent: no rollback removes them, and per-resource rollback leaves them in place. The first successful migration binds the family to its profile for good; a later migration naming another profile refuses (“already bound to another hierarchy control profile”).
Upgrading. Rerun the resource migrations for every sharing family before deploying the new
adapter. Until then every writer and read answers HIERARCHY_UNAVAILABLE (profile_unbound), and
a refused write inside a registered caller-owned transaction marks that transaction rollback-only.
Tenant-key codec header. One permanent row (<prefix>_tenant_key_codec) records how the
profile’s control tables key tenants. It is unbound until the first tenant enrollment binds it
to text or uuid from the registered descriptors’ tenant column type. If the codec step installs
the header on a profile that already has admitted tenants (enrolled by a binary that predates the
header), it records repair_required instead. In that state every reader and writer bound to the
profile, for flat and enrolled tenants alike, answers HIERARCHY_UNAVAILABLE (profile_mismatch)
until an offline, trusted first-party repair runs. This release has no public repair API.
The codec step and descriptor adoption run at READ COMMITTED whatever the session default (their
first statement sets it), so an enrollment committed while they wait on the profile registry lock is
seen, never missed.
Policy-store tables
createPolicyStoreMigrations({ tablePrefix? }) and createPolicyStoreRollbackMigrations({ tablePrefix? })
create and drop the policy-version, activation, active-pointer, tenant-role, tenant-role revision, and
policy-audit tables; policyStoreTables(prefix) names them. The default prefix is rolebook. Apply them
with applyPostgresMigrations() on every deploy, in the same database as the sharing tables. See
policy fence.
The migrations also create a permanent policy header (<prefix>_policy_header: protocol version,
the store’s qualified identity [schema, prefix] and a catalog generation) and an append-only
hierarchy catalog (<prefix>_policy_catalog) beside those tables. Every store operation and the
policy fence check the header first; a store migrated before this release answers
HIERARCHY_UNAVAILABLE (policy_profile_mismatch) until its policy migrations are rerun. An empty
catalog is the normal flat state. The rollback is one step that refuses while the catalog holds any
registered hierarchy descriptor.