integration.provider-database
Database provider implementations for ContractSpec.
@lssm-tech/integration.provider-databasebun add @lssm-tech/integration.provider-databaseManifest declarations describe the current workspace; they do not verify registry publication or runtime execution.
Package guide
Website: https://contractspec.io
Database provider implementations for ContractSpec.
Usage
Import the root entrypoint for the domain surface, or import a concrete implementation from the ./impls/* subpaths. Use ./governed-read when a contracts-spec DataViewQueryGenerator emits a database.query.readonly descriptor and you need to execute that governed read through a DatabaseProvider. The helper builds parameterized SQL from field mappings and keeps SQL construction inside this adapter package. Governed reads support offset descriptors and cursor descriptors from DataViewDatabaseBinding.pagination. Cursor descriptors add a parameterized cursorField > cursor predicate only when the cursor field is present in the contract-owned select mapping; unknown cursor fields fail before provider execution, and maxPageSize is enforced before the query reaches the provider. executeQuery exposes the governed read as a Transport-shaped resolver for the data-fetching engine: it executes a canonical QueryEnvelope and returns a ContractResult<QueryResultEnvelope> carrying a real versionToken (read from the entity's version column with versionTokenFromColumn()) for the engine's etag / optimistic-concurrency path.
Use ./governed-mutation for first-class database writes after the owning domain command has planned a portable database.mutation.execute@2.0.0 envelope. The helper validates actor, tenant, domain-command authority, policy decision, idempotency key, transaction boundary, expected write set, audit refs, replay ref, and correlation ref before running the provider transaction. Drizzle/PostgreSQL rendering remains in this integration package, not in contracts-spec core.
Reuse a caller-owned transaction
Pass an already-open transaction to withPinnedDatabaseProvider(transaction, run) from ./database. The provider view forwards queries and statements to that transaction. Nested transaction() callbacks reuse the same view without a savepoint. Await all work inside run. Once it settles, new queries, statements and nested callbacks through the view reject with DATABASE_TRANSACTION_SCOPE_CLOSED. The caller retains authority checks, commit, rollback and connection ownership. close() on the view is a no-op.
Version-governed entities
Declare the entities whose writes need optimistic concurrency once, at the composition root, and pass the registry to every governed mutation:
const versioning = createGovernedVersionRegistry([
{ entity: 'workspace', table: 'workspaces' }, // schema public, column version
]);
await applyVersionColumnMigration(provider, buildVersionColumnMigration(versioning));
await executeGovernedMutation({
descriptor: { ...renameDescriptor, expectedVersionToken: ctx.queryEnvelope?.versionToken },
provider,
versioning,
});buildVersionColumnMigration(registry)returns idempotentupstatements anddownstatements.upadds a missing column asbigint NOT NULL DEFAULT 1(existing rows start at 1) and marks it with a column comment, or normalizes an existingsmallint/integer/bigintcolumn (NULLs backfilled to 1,NOT NULL DEFAULT 1; any other type fails the migration). It then installs aBEFORE UPDATEtrigger that setsNEW.<column> = OLD.<column> + 1, so writers that bypass the store still advance the version.downremoves the triggers and functions and drops only the columnsupadded. Building the migration fails when two entities of one schema would share a trigger function name.- A descriptor without a schema matches the one registered schema that governs its table and fails when several do; the governed SQL always names the registered schema, so it never depends on the connection's
search_path. - On a governed table, insert returns the new
versionToken; update and delete must carryexpectedVersionToken, check it in the same statement (AND <column> = $n::bigint ... RETURNING <column>) and return the new token (update) or none (delete). Theirwheremust name one row by its key: the store refuses a write that returns more than one row, but it does not see rows the version filter excluded. - A missing, stale or non-integer token (BIGINT range only), or a row that no longer matches, throws
ContractSpecErrorwith the typed Core version conflict (CONFLICT409,metadata.versionConflict.reason=missing,staleorgone, and the stored version inversionTokenwhen the row exists). The transaction rolls back and the idempotency key is not stored. The data engine resolves it with the mutation's conflict policy; underclient-winsagonerow fails the mutation and rolls the optimistic write back. - A write that returns more than one row, a value for the version column itself, or an
expectedVersionTokenon a table that is not in the registry fails with an error. - Clients send the expected token as
MutationRequest.versionToken; the engine forwards it asQueryEnvelope.versionTokenand REST carries it as$versionToken, so handlers readctx.queryEnvelope?.versionToken.
Managed and BYOK Postgres/Supabase deployments are the production posture. Local/PgLite remains a provider-binding compatibility mode for deterministic tests and demos, not a separate ownership mode.
Postgres statement parameters preserve the shared DatabaseProvider contract: Date values are serialized as ISO-8601 timestamps before reaching postgres.js, while bigint, byte, JSON-object, and array parameters retain their existing normalized representations.
Public subpaths
.re-exports the provider surface plus governed read/mutation helpers../databasere-exports the sharedDatabaseProvidercontracts and exposeswithPinnedDatabaseProvider../governed-readexecutes portable DataView read descriptors through a provider../governed-mutationexecutes governed mutation descriptors with transaction, idempotency, audit hooks and, for version-governed tables, the version precondition../governed-versioningdeclares version-governed entities (createGovernedVersionRegistry)../version-column-migrationbuilds and applies the per-entity version-column rollout (buildVersionColumnMigration,applyVersionColumnMigration,VERSION_COLUMN_ROLLOUT_MARKER)../version-token-sourcemaps a stored version column to aVersionToken(versionTokenFromColumn,versionTokenFromValue) and a token back to its BIGINT bind value (parseVersionCounter)../implsand./impls/supabase-psqlexpose concrete PostgreSQL/Supabase implementations../postgres-json-semanticsexportswithPgJsonSemantics(client), which makes a raw postgres.js client pass JSON text through to json/jsonb parameters instead of double-encoding it (pg/PGlite semantics). It has no imports, so any runtime that builds its own postgres.js client can use it.
Compatibility
This package owns the database implementation slice split out of @lssm-tech/integration.providers-impls. The legacy package continues to re-export these subpaths for existing consumers.
Relationships
Arrows point from a package to its direct dependency. Counts are derived from captured workspace manifests.
5 declarations
@lssm-tech/integration.runtimeworkspace:^
Read the package manual ↗@lssm-tech/lib.contracts-spec-coreworkspace:^
Read the package manual ↗@lssm-tech/lib.contracts-integrationsworkspace:^
Read the package manual ↗@lssm-tech/lib.contracts-runtime-coreworkspace:^
Read the package manual ↗drizzle-ormcatalog:data
Declared capabilities
Database provider implementations for ContractSpec.
Scripts
buildcontractspec-bun-build buildbuild:bundlecontractspec-bun-build transpilebuild:typescontractspec-bun-build typesdevcontractspec-bun-build devcleanrimraf dist .turbolint:checknode ../../../scripts/biome.cjs check .lint:fixnode ../../../scripts/biome.cjs check --write --unsafe --only=nursery/useSortedClasses . && node ../../../scripts/biome.cjs check --write .testbun testprebuildcontractspec-bun-build prebuildtypechecktsgo --noEmit