Managed field updates
Apply a declared patch with field authorization before and after a PostgreSQL update.
withManagedUpdate() applies a declared patch using SQL generated by Rolebook. Every declared
field must be allowed by the canonical policy evaluator against both the authoritative before
state and the resulting state. A field-only grant can authorize this method. A deny covering
any declared field rejects the complete update.
The raw protected callback keeps its resource/action contract. Configuring managed updates does not make arbitrary callback SQL field-safe.
Configure the managed mapping
Add managed when binding the existing sharing adapter and VersionedSharing instance with
createPostgresProtectedWriteAdapter(). Keep the same checked executor, local identity
projection and fences described in protected updates.
import type { SharingResourceConfigurations, VersionedResourceSharing } from "@rolebook/sharing";
import { createPostgresLocalIdentityProjection, createPostgresProtectedWriteAdapter, type PostgresSharingAdapter } from "@rolebook/sharing-postgres";
const projection = createPostgresLocalIdentityProjection({table:["app", "authz_identity_projection"]});
declare const sharingAdapter: PostgresSharingAdapter;
declare const versionedSharing: VersionedResourceSharing<SharingResourceConfigurations>;
const protectedAdapter = createPostgresProtectedWriteAdapter({
adapter: sharingAdapter,
sharing: versionedSharing,
identity: projection.identity,
environmentId: "production",
authorityEpoch: "installation-epoch-1",
journalPrefix: "app_authorization",
managed: {
target: {
schema: "app",
table: "document",
// All user columns, in their actual catalog order, including migration-added columns.
userColumns: ["tenant_id", "id", "title", "visibility", "version", "rolebook_sharing_revision"],
},
fields: [
{ field: "title", column: "title", codec: "text" },
{ field: "visibility", column: "visibility", codec: "text" },
],
},
}); The target must match the original resource adapter. The trusted projection receives native
driver values; normalize policy attributes explicitly, such as PostgreSQL bigint text into a
safe integer where appropriate. Its trusted resourceFromRow projection
must include every policy-visible attribute, including attributes that cannot be written through
the patch. The adapter validates the live schema inside the owned transaction. Field names are
flat; nested paths and duplicate mappings are unsupported. Identity, version and sharing columns
cannot be mapped as writable fields.
Supported patch codecs are text, boolean and safe integer, with explicit nullable: true to
permit SQL NULL. Missing fields mean unchanged; NULL means set NULL. JSON, floating-point values,
binary data and timestamps are outside this managed scalar contract. The exact database column
type must match its configured codec. Unknown fields and unsupported values fail closed.
Apply a patch
const scoped = protectedAdapter.forScope({
tenantId: "workspace_1",
actor: { type: "user", id: "user_123" },
});
declare const incarnationId: string;
declare const currentVersion: string;
declare const nextVersion: string;
const intent = {
resource: { type: "document", id: "document_1" },
action: "update",
incarnationId,
expectedVersion: currentVersion,
postVersion: nextVersion,
idempotencyKey: "rename-document_1-once",
patch: { title: "New title" },
};
const outcome = await scoped.withManagedUpdate(intent); Versions are opaque application tokens. expectedVersion must match the locked resource and
postVersion must be nonempty and different. Rolebook does not derive a numeric version from the
lifecycle incarnation or claim global version ordering. Applications remain responsible for
avoiding version reuse when their concurrency model requires that.
All before-state field checks complete before the generated update. Rolebook then reloads the resulting row with a separate SELECT, checks the actual stored values and complete target-row change set, and evaluates the same action and fields against the resulting authoritative state. A failed field decision, unexpected mutation, stale version or seal rolls back the application update, receipt and outbox together.
An empty patch is invalid. An allowed patch whose values are already present still requires all field checks, advances the version and records one receipt/event. Denies on undeclared fields do not prevent a patch to unrelated fields.
Recovery and boundaries
Use scoped.lookupManagedReceipt(intent) to reconcile an uncertain commit. Exact replay returns
the original receipt without re-evaluating today’s policy or requiring today’s resource version.
The receipt binds the computed mapping, target, actor, namespace, patch and expected/post versions.
Reusing a key with another mapping or intent conflicts. Raw and managed operations are distinct.
No business operation is automatically replayed after a database failure.
The supported target is an ordinary permanent table with a complete verified column projection.
User triggers, rewrite rules, inheritance, generated columns and automatic derived-column updates are unsupported in this
PostgreSQL slice. Only version is exempt from the unchanged-column rule, and its stored value
must equal postVersion exactly. The physical-row check proves nothing about other rows, tables
or deferred triggers, including foreign-key ON UPDATE CASCADE effects on referencing rows. Trusted schema and participating source-writer contracts still apply.
This is an embedded transaction API; it does not extend a SQL transaction over HTTP.
Atomic managed batches
withManagedUpdates() applies 1–32 updates to distinct existing resources through the same
configured adapter and tenant scope. Each item uses the same field, incarnation and version
checks as a single managed update. The batch shares one transaction and lifetime; final
persisted-state and authority checks run after the last update. Any failure rolls back every
update, the single receipt and its single outbox event. There is no per-item partial success.
import type { ManagedUpdateBatchIntent } from "@rolebook/sharing-postgres";
declare const secondIncarnationId: string;
declare const secondCurrentVersion: string;
declare const secondNextVersion: string;
const batchIntent: ManagedUpdateBatchIntent = {
idempotencyKey: "rename-two-documents-once",
updates: [
{
resource: { type: "document", id: "document_1" },
action: "update", incarnationId,
expectedVersion: currentVersion, postVersion: nextVersion,
patch: { title: "First title" },
},
{
resource: { type: "document", id: "document_2" },
action: "update", incarnationId: secondIncarnationId,
expectedVersion: secondCurrentVersion, postVersion: secondNextVersion,
patch: { title: "Second title" },
},
],
};
const batchOutcome = await scoped.withManagedUpdates(batchIntent);
// After an uncertain commit, reconcile using the original complete batch intent:
const recoveredBatch = await scoped.lookupManagedUpdatesReceipt(batchIntent); Choose either the single-update or batch example for a given set of expected versions; do not
apply the preceding single update first and then reuse its stale expected version in this batch.
The receipt result contains updates entries with resource and resulting version, ordered
by resource ID. One environment/tenant/actor-bound key covers the entire batch. Input order is
canonicalized; reordered identical items replay the original receipt. A changed item, mapping
or complete intent under that key conflicts. Missing receipt evidence does not prove rollback.
PostgreSQL acquires resource locks in deterministic resource-ID order; SQLite retains its single-writer transaction behavior. No automatic retry, cross-adapter transaction, create, delete or move operation is added. The existing local-authority and supported-driver limits still apply.