Skip to content
This repository was archived by the owner on Nov 25, 2026. It is now read-only.

TML-2851: enforce enum value-sets via Postgres check constraints (additive) - #755

Merged
wmadden-electric merged 18 commits into
mainfrom
tml-2851-check-constraint-realization
Jun 8, 2026
Merged

wmadden-electric merged 18 commits into
mainfrom
tml-2851-check-constraint-realization

Conversation

@wmadden-electric

@wmadden-electric wmadden-electric commented Jun 7, 2026 •

Copy link
Copy Markdown
Contributor

At a glance

Slice 2 of Enums as a domain concept (TML-2851). Slice 1 made an enum a domain concept that emits a valueSet into the contract; this slice makes that restriction real in Postgres — a check constraint, migrated and verified.

The same enum, two authoring surfaces that map to one contract shape — PSL:

enum Role {
  user
  admin
}

model User {
  role Role
}

…and the TS block builder (equivalent):

const Role = enumType('Role', text, member('user'), member('admin'));
model('User', { fields: { role: field.namedType(Role) } });

Each member maps name → stored value: user / member('user') use the name as the value; a distinct stored value is active @map("A") in PSL ≡ member('active', 'A') in the builder. (The builder names the codec explicitly — text; PSL's codec annotation is finalized with the cutover.)

Authored through the TS builder, this lowers to the contract and migrates to:

CREATE TABLE public.users (
  role text NOT NULL,
  CONSTRAINT "User_role_check" CHECK (role IN ('user', 'admin'))
);

db verify confirms the live constraint matches the contract; inserting a non-member value is rejected by the database; and adding/removing a member drops and recreates the check — a plain ALTER TABLE, no native-type rebuild.

Dark/additive — read the PSL above as the surface mapping, not as wired-up behavior. In this slice the value-set + check realization is reached only through the TS enumType builder; PSL enum still lowers to the native Postgres enum. The cutover (TML-2853) repoints the PSL keyword to this shape, at which point both surfaces produce the check. The PSL is shown so the surface-to-builder correspondence is legible.

The realization, end to end

  • Contract IR — a structured CheckConstraint { name, column, valueSet } (references the value-set, not a raw SQL string — the contract stays target-agnostic), emitted into the table's optional checks (omitted-when-empty, so no table fixture changes).
  • Verify — the contract's expected check (its value-set resolved to values) is compared against the live constraint, introspected from pg_constraint contype='c'. The comparison is set equality, normalizing Postgres's rewrite of col IN (a,b) to col = ANY (ARRAY[a,b]) — so the rendering difference never false-mismatches. The introspection parser is scoped to exactly the two shapes this slice emits and returns nothing for arbitrary user checks (it never mis-parses price > 0).
  • Migrate — a checkConstraintPlanCallStrategy (mirroring the native-enum planner) diffs expected vs live: add a missing check, drop a removed one, and drop-before-add on a member change (guaranteed by the planner's bucket order). A dropped check is classified destructive, matching the other constraint drops.

Additivity proof

pnpm build → pnpm i → pnpm fixtures:check is byte-identical, zero diff; lint:casts net-zero; full suites green (adapter-postgres 579, target-postgres 306, family-sql 362), including a 4-step PGlite integration test (create → verify → enforce → member-change re-issue) against a live database.

Scope — deliberately out (sibling/later slices)

  • Enum member defaults (@default(member)) → TML-2855 (split out of this slice for review coherence).
  • Typed reads / db.enums / ORDER BY → TML-2852.
  • The cutover: repoint PSL enum to the new shape + delete the native machinery (incl. verifyEnumType) → TML-2853. The native path is untouched here.

Notes

  • check_mismatch grades as valueDrift, not a hard incompatibility — symmetric with how native enums grade a member change, so the external control policy suppresses both identically. This matters because checks replace native enums at the cutover; asymmetric grading would change db verify behavior for externally-managed enums.
  • One shared resolveValueSetValues is used by lowering, the planner, and verification, so all three agree on a malformed-ref error rather than one throwing and another silently returning an empty set.

Refs TML-2851.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added SQL CHECK constraint support (definition, IR, and contract types)
    • Auto-generates CHECKs for enum-restricted columns and verifies value sets
    • Schema verification classifies and reports check_missing/check_mismatch/check_removed
    • Migration planner and Postgres target produce add/drop CHECK DDL and ordered ops
    • Postgres introspection parses and exposes CHECK constraints
  • Tests

    • Extensive unit/integration tests covering construction, validation, verification, planning, introspection, and end-to-end migrations

@wmadden-electric
wmadden-electric requested a review from a team as a code owner June 7, 2026 16:15
@coderabbitai

coderabbitai Bot commented Jun 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: c61ad786-4e27-403b-aa55-980c30c50bf0

📥 Commits

Reviewing files that changed from the base of the PR and between 430cc70 and baacb52.

⛔ Files ignored due to path filters (5)
  • projects/enums-as-domain-concept/design-notes.md is excluded by !projects/**
  • projects/enums-as-domain-concept/plan.md is excluded by !projects/**
  • projects/enums-as-domain-concept/slices/check-constraint-realization/plan.md is excluded by !projects/**
  • projects/enums-as-domain-concept/slices/check-constraint-realization/spec.md is excluded by !projects/**
  • projects/enums-as-domain-concept/spec.md is excluded by !projects/**
📒 Files selected for processing (32)
  • packages/1-framework/1-core/framework-components/src/control/control-result-types.ts
  • packages/2-sql/1-core/contract/src/exports/types.ts
  • packages/2-sql/1-core/contract/src/ir/check-constraint.ts
  • packages/2-sql/1-core/contract/src/ir/storage-table.ts
  • packages/2-sql/1-core/contract/src/types.ts
  • packages/2-sql/1-core/contract/src/validators.ts
  • packages/2-sql/1-core/contract/test/check-constraint.test.ts
  • packages/2-sql/1-core/contract/test/validators.test.ts
  • packages/2-sql/1-core/schema-ir/src/exports/types.ts
  • packages/2-sql/1-core/schema-ir/src/ir/sql-check-constraint-ir.ts
  • packages/2-sql/1-core/schema-ir/src/ir/sql-table-ir.ts
  • packages/2-sql/1-core/schema-ir/src/types.ts
  • packages/2-sql/2-authoring/contract-ts/src/build-contract.ts
  • packages/2-sql/2-authoring/contract-ts/test/check-constraint.authoring.test.ts
  • packages/2-sql/9-family/src/core/migrations/contract-to-schema-ir.ts
  • packages/2-sql/9-family/src/core/schema-verify/verifier-disposition.ts
  • packages/2-sql/9-family/src/core/schema-verify/verify-helpers.ts
  • packages/2-sql/9-family/src/core/schema-verify/verify-sql-schema.ts
  • packages/2-sql/9-family/src/exports/control.ts
  • packages/2-sql/9-family/test/schema-verify.check-constraints.test.ts
  • packages/2-sql/9-family/test/verifier-disposition.test.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/issue-planner.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/op-factory-call.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/operations/constraints.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/planner-strategies.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/planner-target-details.ts
  • packages/3-targets/3-targets/postgres/src/exports/migration.ts
  • packages/3-targets/3-targets/postgres/src/exports/op-factory-call.ts
  • packages/3-targets/3-targets/postgres/test/migrations/planner.check-constraints.test.ts
  • packages/3-targets/6-adapters/postgres/src/core/control-adapter.ts
  • packages/3-targets/6-adapters/postgres/test/control-adapter.check-constraints.test.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/enum-check-constraint.integration.test.ts
💤 Files with no reviewable changes (1)
  • packages/3-targets/6-adapters/postgres/test/migrations/enum-check-constraint.integration.test.ts
✅ Files skipped from review due to trivial changes (2)
  • packages/2-sql/1-core/schema-ir/src/types.ts
  • packages/2-sql/1-core/schema-ir/src/exports/types.ts
🚧 Files skipped from review as they are similar to previous changes (24)
  • packages/2-sql/9-family/src/exports/control.ts
  • packages/3-targets/3-targets/postgres/src/exports/op-factory-call.ts
  • packages/3-targets/3-targets/postgres/src/exports/migration.ts
  • packages/2-sql/9-family/src/core/schema-verify/verifier-disposition.ts
  • packages/1-framework/1-core/framework-components/src/control/control-result-types.ts
  • packages/2-sql/1-core/schema-ir/src/ir/sql-check-constraint-ir.ts
  • packages/2-sql/2-authoring/contract-ts/src/build-contract.ts
  • packages/2-sql/1-core/contract/src/exports/types.ts
  • packages/3-targets/6-adapters/postgres/test/control-adapter.check-constraints.test.ts
  • packages/3-targets/3-targets/postgres/test/migrations/planner.check-constraints.test.ts
  • packages/2-sql/1-core/contract/src/ir/check-constraint.ts
  • packages/2-sql/9-family/src/core/schema-verify/verify-sql-schema.ts
  • packages/2-sql/1-core/contract/src/types.ts
  • packages/2-sql/9-family/test/schema-verify.check-constraints.test.ts
  • packages/2-sql/1-core/contract/test/check-constraint.test.ts
  • packages/2-sql/9-family/test/verifier-disposition.test.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/issue-planner.ts
  • packages/2-sql/9-family/src/core/schema-verify/verify-helpers.ts
  • packages/2-sql/9-family/src/core/migrations/contract-to-schema-ir.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/op-factory-call.ts
  • packages/2-sql/1-core/contract/src/ir/storage-table.ts
  • packages/2-sql/1-core/schema-ir/src/ir/sql-table-ir.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/operations/constraints.ts
  • packages/3-targets/6-adapters/postgres/src/core/control-adapter.ts

📝 Walkthrough

Walkthrough

Adds table-level SQL CHECK constraint support end-to-end: new contract and schema IR types, validators, automatic lowering from enum-backed columns, contract→IR projection resolving value-set contents, verification emitting three new issue kinds, Postgres introspection/parsing, migration DDL ops/planner wiring, and tests.

Changes

Check Constraint Implementation

Layer / File(s) Summary
Check Constraint Types & Table fields
packages/2-sql/1-core/contract/src/ir/check-constraint.ts, packages/2-sql/1-core/contract/src/ir/storage-table.ts, packages/2-sql/1-core/contract/src/types.ts
Adds CheckConstraintInput/CheckConstraint, optional checks on storage table inputs/instances, and re-exports.
Validators & Contract tests
packages/2-sql/1-core/contract/src/validators.ts, packages/2-sql/1-core/contract/test/check-constraint.test.ts, packages/2-sql/1-core/contract/test/validators.test.ts
Adds CheckConstraintSchema, accepts optional checks on StorageTableSchema, detects duplicate names/definitions, enforces referenced column existence, and includes unit tests.
Schema IR types
packages/2-sql/1-core/schema-ir/src/ir/sql-check-constraint-ir.ts, packages/2-sql/1-core/schema-ir/src/ir/sql-table-ir.ts, packages/2-sql/1-core/schema-ir/src/types.ts, packages/2-sql/1-core/schema-ir/src/exports/types.ts
Adds SqlCheckConstraintIR and input, optional checks on SqlTableIR, normalization/freezing and re-exports.
Authoring: derive checks from enums
packages/2-sql/2-authoring/contract-ts/src/build-contract.ts, packages/2-sql/2-authoring/contract-ts/test/check-constraint.authoring.test.ts
Derives checks for valueSet-backed columns with generated names, includes checks when present, and tests emission and JSON serialize→hydrate round-trip.
Contract → Schema IR projection
packages/2-sql/9-family/src/core/migrations/contract-to-schema-ir.ts, packages/2-sql/9-family/src/exports/control.ts
Adds resolveValueSetValues to resolve value-set contents from contract storage and converts contract CheckConstraint entries into SqlCheckConstraintIRInput with concrete permitted values.
Schema verification
packages/2-sql/9-family/src/core/schema-verify/verify-helpers.ts, packages/2-sql/9-family/src/core/schema-verify/verify-sql-schema.ts, packages/2-sql/9-family/src/core/schema-verify/verifier-disposition.ts, packages/2-sql/9-family/test/schema-verify.check-constraints.test.ts, packages/2-sql/9-family/test/verifier-disposition.test.ts
Adds verifyCheckConstraints and unordered value-set equality; emits check_missing, check_mismatch, and (in strict mode) check_removed; maps kinds to disposition categories; includes unit and integration tests.
Postgres adapter introspection & parsing
packages/3-targets/6-adapters/postgres/src/core/control-adapter.ts, packages/3-targets/6-adapters/postgres/test/control-adapter.check-constraints.test.ts
Adapter queries pg_constraint, parses enum-style CHECK predicates (IN (...), = ANY (ARRAY[...])), unescapes literals/identifiers, and attaches parsed checks to SqlTableIR; parser and adapter tests added.
Postgres migration planner & DDL ops
packages/3-targets/3-targets/postgres/src/core/migrations/issue-planner.ts, packages/3-targets/3-targets/postgres/src/core/migrations/op-factory-call.ts, packages/3-targets/3-targets/postgres/src/core/migrations/operations/constraints.ts, packages/3-targets/3-targets/postgres/src/core/migrations/planner-target-details.ts, packages/3-targets/3-targets/postgres/src/exports/migration.ts, packages/3-targets/3-targets/postgres/src/exports/op-factory-call.ts, packages/3-targets/3-targets/postgres/test/migrations/planner.check-constraints.test.ts
Extends planner issue ordering and mapping; adds addCheckConstraint/dropCheckConstraint ops (with escaped literals and pre/post checks), op-factory call classes, integrates into planner classification and tests verify call lists and ordering.
Exports & Integration tests
packages/2-sql/9-family/src/exports/control.ts, packages/3-targets/6-adapters/postgres/test/migrations/enum-check-constraint.integration.test.ts
Exports resolveValueSetValues; end-to-end integration tests validate migration creation, verification, runtime enforcement, and enum-member-change migrations that drop and re-add constraints with correct ordering.

Sequence Diagram

sequenceDiagram
  participant Contract
  participant Authoring
  participant StorageTable
  participant ContractToIR
  participant SchemaIR
  participant Verifier
  participant PostgresAdapter
  participant Planner
  Contract->>Authoring: build contract with enum-backed columns
  Authoring->>StorageTable: derive CheckConstraintInput[] into tableInput
  StorageTable->>ContractToIR: include checks referencing valueSet
  ContractToIR->>ContractToIR: resolveValueSetValues using storage
  ContractToIR->>SchemaIR: emit SqlCheckConstraintIR(permittedValues)
  PostgresAdapter->>PostgresAdapter: introspect pg_constraint and parse checks
  Verifier->>Verifier: compare contract checks ↔ schema checks (by name + set)
  Verifier->>Planner: emit check_missing / check_mismatch / check_removed issues
  Planner->>Planner: plan addCheckConstraint / dropCheckConstraint operations
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested reviewers

  • saevarb

Poem

🐰 I nibble on enums and hop through the trees,

I stitch name, column, and values with ease.
From contract to DB the check blooms bright,
Drop then add — migration done right.
Hooray — constraints keep your data polite!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 39.47% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely summarizes the main change: implementing Postgres check constraints to enforce enum value-sets, with the '(additive)' qualifier indicating backward compatibility.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch tml-2851-check-constraint-realization

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@pkg-pr-new

pkg-pr-new Bot commented Jun 7, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@prisma-next/extension-author-tools

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/extension-author-tools@755

@prisma-next/mongo-runtime

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-runtime@755

@prisma-next/family-mongo

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/family-mongo@755

@prisma-next/sql-runtime

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-runtime@755

@prisma-next/family-sql

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/family-sql@755

@prisma-next/extension-arktype-json

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/extension-arktype-json@755

@prisma-next/middleware-cache

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/middleware-cache@755

@prisma-next/mongo

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo@755

@prisma-next/extension-paradedb

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/extension-paradedb@755

@prisma-next/extension-pgvector

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/extension-pgvector@755

@prisma-next/extension-postgis

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/extension-postgis@755

@prisma-next/postgres

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/postgres@755

@prisma-next/sql-orm-client

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-orm-client@755

@prisma-next/sqlite

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sqlite@755

@prisma-next/extension-supabase

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/extension-supabase@755

@prisma-next/target-mongo

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/target-mongo@755

@prisma-next/adapter-mongo

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/adapter-mongo@755

@prisma-next/driver-mongo

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/driver-mongo@755

@prisma-next/contract

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/contract@755

@prisma-next/utils

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/utils@755

@prisma-next/config

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/config@755

@prisma-next/errors

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/errors@755

@prisma-next/framework-components

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/framework-components@755

@prisma-next/operations

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/operations@755

@prisma-next/ts-render

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/ts-render@755

@prisma-next/contract-authoring

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/contract-authoring@755

@prisma-next/ids

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/ids@755

@prisma-next/psl-parser

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/psl-parser@755

@prisma-next/psl-printer

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/psl-printer@755

@prisma-next/cli

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/cli@755

@prisma-next/cli-telemetry

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/cli-telemetry@755

@prisma-next/emitter

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/emitter@755

@prisma-next/migration-tools

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/migration-tools@755

prisma-next

npm i https://pkg.pr.new/prisma/prisma-next@755

@prisma-next/vite-plugin-contract-emit

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/vite-plugin-contract-emit@755

@prisma-next/mongo-codec

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-codec@755

@prisma-next/mongo-contract

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-contract@755

@prisma-next/mongo-value

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-value@755

@prisma-next/mongo-contract-psl

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-contract-psl@755

@prisma-next/mongo-contract-ts

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-contract-ts@755

@prisma-next/mongo-emitter

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-emitter@755

@prisma-next/mongo-schema-ir

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-schema-ir@755

@prisma-next/mongo-query-ast

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-query-ast@755

@prisma-next/mongo-orm

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-orm@755

@prisma-next/mongo-query-builder

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-query-builder@755

@prisma-next/mongo-lowering

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-lowering@755

@prisma-next/mongo-wire

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-wire@755

@prisma-next/sql-contract

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-contract@755

@prisma-next/sql-errors

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-errors@755

@prisma-next/sql-operations

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-operations@755

@prisma-next/sql-schema-ir

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-schema-ir@755

@prisma-next/sql-contract-psl

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-contract-psl@755

@prisma-next/sql-contract-ts

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-contract-ts@755

@prisma-next/sql-contract-emitter

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-contract-emitter@755

@prisma-next/sql-lane-query-builder

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-lane-query-builder@755

@prisma-next/sql-relational-core

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-relational-core@755

@prisma-next/sql-builder

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-builder@755

@prisma-next/target-postgres

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/target-postgres@755

@prisma-next/target-sqlite

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/target-sqlite@755

@prisma-next/adapter-postgres

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/adapter-postgres@755

@prisma-next/adapter-sqlite

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/adapter-sqlite@755

@prisma-next/driver-postgres

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/driver-postgres@755

@prisma-next/driver-sqlite

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/driver-sqlite@755

commit: baacb52

@github-actions

github-actions Bot commented Jun 7, 2026 •

Copy link
Copy Markdown

size-limit report 📦

Path Size
postgres / no-emit 149.05 KB (+0.78% 🔺)
postgres / emit 118.32 KB (+0.53% 🔺)
mongo / no-emit 76.67 KB (0%)
mongo / emit 70.96 KB (0%)
cf-worker / no-emit 179.11 KB (+0.71% 🔺)
cf-worker / emit 145.03 KB (+0.43% 🔺)

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/2-sql/1-core/contract/src/validators.ts (1)

214-223: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Add semantic/consistency validation for table.checks.

Line 222 wires checks into structural validation, but validateStorageSemantics / validateSqlStorageConsistency still don’t validate check constraints. A malformed contract can pass validation and fail later when planning/applying DDL.

💡 Suggested fix
diff --git a/packages/2-sql/1-core/contract/src/validators.ts b/packages/2-sql/1-core/contract/src/validators.ts
@@
     for (const fk of table.foreignKeys) {
       registerNamedObject('foreign key', fk.name);
     }
+    for (const check of table.checks ?? []) {
+      registerNamedObject('check constraint', check.name);
+    }
@@
     for (const index of table.indexes) {
       for (const colName of index.columns) {
         if (!columnNames.has(colName)) {
@@
       }
     }
+
+    for (const check of table.checks ?? []) {
+      if (!columnNames.has(check.column)) {
+        throw new ContractValidationError(
+          `Namespace "${namespaceId}" table "${tableName}" check constraint "${check.name}" references non-existent column "${check.column}"`,
+          'storage',
+        );
+      }
+    }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/2-sql/1-core/contract/src/validators.ts` around lines 214 - 223, The
StorageTableSchema includes a 'checks' field but semantic validators don't
validate those constraints; update validateStorageSemantics and
validateSqlStorageConsistency to iterate table.checks (using the
CheckConstraintSchema) and perform the same semantic/consistency checks you do
for uniques/indexes/foreignKeys (e.g., validate referenced columns exist, types
are appropriate, names are unique and SQL-safe, and constraint expressions are
well-formed). Locate functions validateStorageSemantics and
validateSqlStorageConsistency and add a new validation branch that reads each
table.checks entry, validates it via CheckConstraintSchema parsing/validation,
and emits the same error/warning patterns used elsewhere so malformed check
constraints fail early.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/2-sql/1-core/contract/test/check-constraint.test.ts`:
- Around line 161-178: The test currently asserts a generic Error/object for
storageSchema(makeRawStorage(...)) failure; change the assertion to match the
project pattern by checking that the result is an Arktype errors instance (use
the Arktype error type check used by validateStorage), e.g. replace the existing
expect(...) with an assertion that result is an instance of the Arktype errors
type (the same pattern used elsewhere when calling storageSchema/storage
validation), referencing the storageSchema and makeRawStorage call in this test.

In `@packages/2-sql/9-family/src/core/schema-verify/verify-helpers.ts`:
- Around line 743-752: The check-constraint mismatch logic currently only
compares permittedValues via valueSetsEqual; update the conditional to also
compare the constraint column (compare contractCheck.column !==
liveCheck.column) so a same-name/value constraint on a different column is
flagged, and include the column in the reported SchemaIssue (add a column:
contractCheck.column or appropriate property) alongside indexOrConstraint,
expected and actual to ensure repair DDL is generated; modify the block around
valueSetsEqual(contractCheck.permittedValues, liveCheck.permittedValues) and the
SchemaIssue construction to reference contractCheck and liveCheck column
properties.
- Around line 673-677: The function valueSetsEqual currently treats arrays with
duplicates as distinct elements and can return true for different arrays (e.g.
['a','a'] vs ['a','b']); update valueSetsEqual to compare the unique element
sets instead of raw arrays: convert both inputs to Set (e.g. setA = new Set(a),
setB = new Set(b)), check setA.size === setB.size, and then ensure every element
of setA exists in setB; adjust the implementation in valueSetsEqual accordingly
so duplicates no longer cause false-equal results.

In `@packages/2-sql/9-family/src/core/schema-verify/verify-sql-schema.ts`:
- Around line 717-737: The current guard skips calling verifyCheckConstraints
when contractTable.checks is empty, which in strict mode prevents detection of
extra live CHECKs; update the condition so verifyCheckConstraints is invoked
either when contractTable.checks has entries or when strict is true (i.e. run
verifyCheckConstraints if strict || (contractTable.checks &&
contractTable.checks.length > 0)), construct contractCheckIRs as an empty array
when no contract checks, and keep passing schemaTable.checks, tableName,
namespaceId, tablePath, tableControlPolicy, issues so extra checks produce
check_removed issues in strict mode; append returned statuses to tableChildren
as before.

In `@packages/3-targets/6-adapters/postgres/src/core/control-adapter.ts`:
- Around line 1318-1339: The regexes used for anyArrayMatch and inMatch in
parseCheckConstraintDef only anchor the start and thus can match
sub-expressions; update both patterns to require full-expression matches by
anchoring the end as well (use ^...$) and allow optional surrounding whitespace
and enclosing parentheses if needed (e.g.,
/^\s*(?:"((?:[^"]|"")*)"|(\w+))\s*=\s*ANY\s*\(\s*ARRAY\s*\[(.+)\]\s*\)\s*$/i and
similarly for the IN form), so the code paths in the anyArrayMatch and inMatch
branches only run when the entire inner expression is exactly that shape.

In
`@packages/3-targets/6-adapters/postgres/test/control-adapter.check-constraints.test.ts`:
- Around line 34-42: Add a negative test to parseCheckConstraintDef that ensures
mixed/composite predicates which start with an IN (...) or = ANY (...) and then
include extra clauses are treated as unparseable and return undefined; update
the test suite (in control-adapter.check-constraints.test.ts) to call
parseCheckConstraintDef with a composite predicate like 'CHECK ((col IN (1,2)
AND col > 0))' (or 'CHECK ((col = ANY (ARRAY[...] ) AND ...))') and assert the
result is undefined to lock the parser boundary and prevent partial-match
regressions.

---

Outside diff comments:
In `@packages/2-sql/1-core/contract/src/validators.ts`:
- Around line 214-223: The StorageTableSchema includes a 'checks' field but
semantic validators don't validate those constraints; update
validateStorageSemantics and validateSqlStorageConsistency to iterate
table.checks (using the CheckConstraintSchema) and perform the same
semantic/consistency checks you do for uniques/indexes/foreignKeys (e.g.,
validate referenced columns exist, types are appropriate, names are unique and
SQL-safe, and constraint expressions are well-formed). Locate functions
validateStorageSemantics and validateSqlStorageConsistency and add a new
validation branch that reads each table.checks entry, validates it via
CheckConstraintSchema parsing/validation, and emits the same error/warning
patterns used elsewhere so malformed check constraints fail early.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: 9ba86e5a-29a7-4bd6-a0eb-ebbfd0225c06

📥 Commits

Reviewing files that changed from the base of the PR and between 13cd3a3 and 09b2489.

⛔ Files ignored due to path filters (3)
  • projects/enums-as-domain-concept/plan.md is excluded by !projects/**
  • projects/enums-as-domain-concept/slices/check-constraint-realization/plan.md is excluded by !projects/**
  • projects/enums-as-domain-concept/slices/check-constraint-realization/spec.md is excluded by !projects/**
📒 Files selected for processing (31)
  • packages/1-framework/1-core/framework-components/src/control/control-result-types.ts
  • packages/2-sql/1-core/contract/src/exports/types.ts
  • packages/2-sql/1-core/contract/src/ir/check-constraint.ts
  • packages/2-sql/1-core/contract/src/ir/storage-table.ts
  • packages/2-sql/1-core/contract/src/types.ts
  • packages/2-sql/1-core/contract/src/validators.ts
  • packages/2-sql/1-core/contract/test/check-constraint.test.ts
  • packages/2-sql/1-core/schema-ir/src/exports/types.ts
  • packages/2-sql/1-core/schema-ir/src/ir/sql-check-constraint-ir.ts
  • packages/2-sql/1-core/schema-ir/src/ir/sql-table-ir.ts
  • packages/2-sql/1-core/schema-ir/src/types.ts
  • packages/2-sql/2-authoring/contract-ts/src/build-contract.ts
  • packages/2-sql/2-authoring/contract-ts/test/check-constraint.authoring.test.ts
  • packages/2-sql/9-family/src/core/migrations/contract-to-schema-ir.ts
  • packages/2-sql/9-family/src/core/schema-verify/verifier-disposition.ts
  • packages/2-sql/9-family/src/core/schema-verify/verify-helpers.ts
  • packages/2-sql/9-family/src/core/schema-verify/verify-sql-schema.ts
  • packages/2-sql/9-family/src/exports/control.ts
  • packages/2-sql/9-family/test/schema-verify.check-constraints.test.ts
  • packages/2-sql/9-family/test/verifier-disposition.test.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/issue-planner.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/op-factory-call.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/operations/constraints.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/planner-strategies.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/planner-target-details.ts
  • packages/3-targets/3-targets/postgres/src/exports/migration.ts
  • packages/3-targets/3-targets/postgres/src/exports/op-factory-call.ts
  • packages/3-targets/3-targets/postgres/test/migrations/planner.check-constraints.test.ts
  • packages/3-targets/6-adapters/postgres/src/core/control-adapter.ts
  • packages/3-targets/6-adapters/postgres/test/control-adapter.check-constraints.test.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/enum-check-constraint.integration.test.ts

@wmadden-electric
wmadden-electric force-pushed the tml-2851-check-constraint-realization branch from 09b2489 to 430cc70 Compare June 8, 2026 05:52

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
packages/2-sql/1-core/contract/src/validators.ts (2)

593-735: ⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Add semantic validation for check constraints.

The validateStorageSemantics function validates duplicate names and definitions for primary keys, unique constraints, indexes, and foreign keys, but does not validate the newly added checks array. This allows contracts with duplicate check constraint names or duplicate check definitions to pass validation.

Consider adding:

  • Duplicate name registration for check constraints (similar to lines 604-613 for other constraints)
  • Duplicate definition detection for checks (similar to lines 641-703 for uniques/indexes/FKs)
🛡️ Recommended validation additions

After line 613, register check constraint names:

     for (const fk of table.foreignKeys) {
       registerNamedObject('foreign key', fk.name);
     }
+    for (const check of table.checks ?? []) {
+      registerNamedObject('check constraint', check.name);
+    }

After line 703, add duplicate check definition validation:

       seenForeignKeyDefinitions.add(signature);
     }
+
+    const seenCheckDefinitions = new Set<string>();
+    for (const check of table.checks ?? []) {
+      const signature = JSON.stringify({
+        column: check.column,
+        valueSet: check.valueSet,
+      });
+      if (seenCheckDefinitions.has(signature)) {
+        errors.push(
+          `Namespace "${namespaceId}" table "${tableName}": duplicate check constraint definition on column "${check.column}" with valueSet "${check.valueSet.name}"`,
+        );
+        continue;
+      }
+      seenCheckDefinitions.add(signature);
+    }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/2-sql/1-core/contract/src/validators.ts` around lines 593 - 735,
validateStorageSemantics is missing validation for table.checks: add check
constraint names to the namedObjects registration (call
registerNamedObject('check', check.name) when iterating table.checks alongside
uniques/indexes/foreignKeys) and add duplicate-definition detection for checks
(create a seenCheckDefinitions Set and for each check build a stable signature
of its defining properties — e.g. {expression: check.expression, options: ...}
or JSON.stringify of sorted entries — then push an error if the signature is
already seen, similar to
seenUniqueDefinitions/seenIndexDefinitions/seenForeignKeyDefinitions). Ensure
you reference table.checks and use the existing registerNamedObject and error
message style used in validateStorageSemantics.

802-895: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Add consistency validation for check constraint column references.

The validateSqlStorageConsistency function validates that columns referenced by primary keys, unique constraints, indexes, and foreign keys exist in the table, but does not validate the column field of check constraints. This allows checks referencing non-existent columns to pass validation, which would later fail during migration DDL generation.

🛡️ Recommended validation addition

After line 838, add check constraint column validation:

       }
     }
 
+    for (const check of table.checks ?? []) {
+      if (!columnNames.has(check.column)) {
+        throw new ContractValidationError(
+          `Namespace "${namespaceId}" table "${tableName}" check constraint "${check.name}" references non-existent column "${check.column}"`,
+          'storage',
+        );
+      }
+    }
+
     for (const [colName, column] of Object.entries(table.columns)) {
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/2-sql/1-core/contract/src/validators.ts` around lines 802 - 895, In
validateSqlStorageConsistency, add validation for check constraints so they
don't reference non-existent columns: after the index validation loop, iterate
table.checks and for each check if it has a column (e.g., check.column) assert
columnNames.has(check.column), and if it has multiple columns (e.g.,
check.columns) assert every name exists in columnNames; on missing columns throw
a ContractValidationError with a message consistent with the others (include
namespaceId, tableName, check identifier/column name) and use the 'storage'
error area; reference validateSqlStorageConsistency, table.checks, and
ContractValidationError to locate and implement this change.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@packages/2-sql/1-core/contract/src/validators.ts`:
- Around line 593-735: validateStorageSemantics is missing validation for
table.checks: add check constraint names to the namedObjects registration (call
registerNamedObject('check', check.name) when iterating table.checks alongside
uniques/indexes/foreignKeys) and add duplicate-definition detection for checks
(create a seenCheckDefinitions Set and for each check build a stable signature
of its defining properties — e.g. {expression: check.expression, options: ...}
or JSON.stringify of sorted entries — then push an error if the signature is
already seen, similar to
seenUniqueDefinitions/seenIndexDefinitions/seenForeignKeyDefinitions). Ensure
you reference table.checks and use the existing registerNamedObject and error
message style used in validateStorageSemantics.
- Around line 802-895: In validateSqlStorageConsistency, add validation for
check constraints so they don't reference non-existent columns: after the index
validation loop, iterate table.checks and for each check if it has a column
(e.g., check.column) assert columnNames.has(check.column), and if it has
multiple columns (e.g., check.columns) assert every name exists in columnNames;
on missing columns throw a ContractValidationError with a message consistent
with the others (include namespaceId, tableName, check identifier/column name)
and use the 'storage' error area; reference validateSqlStorageConsistency,
table.checks, and ContractValidationError to locate and implement this change.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: b0e492d1-dcd7-489e-9103-ef4cdfeebf1f

📥 Commits

Reviewing files that changed from the base of the PR and between 09b2489 and 430cc70.

⛔ Files ignored due to path filters (3)
  • projects/enums-as-domain-concept/plan.md is excluded by !projects/**
  • projects/enums-as-domain-concept/slices/check-constraint-realization/plan.md is excluded by !projects/**
  • projects/enums-as-domain-concept/slices/check-constraint-realization/spec.md is excluded by !projects/**
📒 Files selected for processing (31)
  • packages/1-framework/1-core/framework-components/src/control/control-result-types.ts
  • packages/2-sql/1-core/contract/src/exports/types.ts
  • packages/2-sql/1-core/contract/src/ir/check-constraint.ts
  • packages/2-sql/1-core/contract/src/ir/storage-table.ts
  • packages/2-sql/1-core/contract/src/types.ts
  • packages/2-sql/1-core/contract/src/validators.ts
  • packages/2-sql/1-core/contract/test/check-constraint.test.ts
  • packages/2-sql/1-core/schema-ir/src/exports/types.ts
  • packages/2-sql/1-core/schema-ir/src/ir/sql-check-constraint-ir.ts
  • packages/2-sql/1-core/schema-ir/src/ir/sql-table-ir.ts
  • packages/2-sql/1-core/schema-ir/src/types.ts
  • packages/2-sql/2-authoring/contract-ts/src/build-contract.ts
  • packages/2-sql/2-authoring/contract-ts/test/check-constraint.authoring.test.ts
  • packages/2-sql/9-family/src/core/migrations/contract-to-schema-ir.ts
  • packages/2-sql/9-family/src/core/schema-verify/verifier-disposition.ts
  • packages/2-sql/9-family/src/core/schema-verify/verify-helpers.ts
  • packages/2-sql/9-family/src/core/schema-verify/verify-sql-schema.ts
  • packages/2-sql/9-family/src/exports/control.ts
  • packages/2-sql/9-family/test/schema-verify.check-constraints.test.ts
  • packages/2-sql/9-family/test/verifier-disposition.test.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/issue-planner.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/op-factory-call.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/operations/constraints.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/planner-strategies.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/planner-target-details.ts
  • packages/3-targets/3-targets/postgres/src/exports/migration.ts
  • packages/3-targets/3-targets/postgres/src/exports/op-factory-call.ts
  • packages/3-targets/3-targets/postgres/test/migrations/planner.check-constraints.test.ts
  • packages/3-targets/6-adapters/postgres/src/core/control-adapter.ts
  • packages/3-targets/6-adapters/postgres/test/control-adapter.check-constraints.test.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/enum-check-constraint.integration.test.ts
✅ Files skipped from review due to trivial changes (2)
  • packages/2-sql/1-core/schema-ir/src/exports/types.ts
  • packages/3-targets/6-adapters/postgres/test/control-adapter.check-constraints.test.ts
🚧 Files skipped from review as they are similar to previous changes (24)
  • packages/2-sql/1-core/schema-ir/src/types.ts
  • packages/2-sql/1-core/contract/src/ir/check-constraint.ts
  • packages/2-sql/9-family/src/core/schema-verify/verifier-disposition.ts
  • packages/3-targets/3-targets/postgres/src/exports/migration.ts
  • packages/2-sql/9-family/test/verifier-disposition.test.ts
  • packages/2-sql/1-core/contract/src/types.ts
  • packages/2-sql/1-core/contract/test/check-constraint.test.ts
  • packages/2-sql/1-core/contract/src/ir/storage-table.ts
  • packages/3-targets/3-targets/postgres/src/exports/op-factory-call.ts
  • packages/2-sql/9-family/src/exports/control.ts
  • packages/2-sql/1-core/schema-ir/src/ir/sql-check-constraint-ir.ts
  • packages/1-framework/1-core/framework-components/src/control/control-result-types.ts
  • packages/2-sql/2-authoring/contract-ts/src/build-contract.ts
  • packages/2-sql/1-core/schema-ir/src/ir/sql-table-ir.ts
  • packages/3-targets/6-adapters/postgres/src/core/control-adapter.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/issue-planner.ts
  • packages/2-sql/9-family/src/core/migrations/contract-to-schema-ir.ts
  • packages/2-sql/9-family/test/schema-verify.check-constraints.test.ts
  • packages/3-targets/3-targets/postgres/test/migrations/planner.check-constraints.test.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/enum-check-constraint.integration.test.ts
  • packages/2-sql/2-authoring/contract-ts/test/check-constraint.authoring.test.ts
  • packages/2-sql/9-family/src/core/schema-verify/verify-sql-schema.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/op-factory-call.ts
  • packages/2-sql/9-family/src/core/schema-verify/verify-helpers.ts

wmadden and others added 8 commits June 8, 2026 09:44
Scope TML-2851 to check-constraint enforcement only (CheckConstraint IR +
PG check DDL + introspection + verification); split enum member defaults to
sibling slice TML-2855 (one coherent review each). Pin the additivity
constraint: StorageTable.checks is optional (omitted-when-empty) so existing
table fixtures are unchanged.

Refs TML-2851, TML-2855.

Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Four additive dispatches: CheckConstraint IR + lowering → schema-IR
projection + introspection + verification → PG check DDL + planner →
integration + additivity gate.

Refs TML-2851.

Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 4.8 <[email protected]>
… (TML-2851)

- Add CheckConstraint frozen IR node (name, column, valueSet: ValueSetRef) in
  packages/2-sql/1-core/contract/src/ir/check-constraint.ts
- Add optional checks?: ReadonlyArray<CheckConstraint> to StorageTable /
  StorageTableInput; omitted when empty so existing fixtures stay unchanged
- Add CheckConstraintSchema arktype fragment in validators.ts; wire optional
  checks into StorageTableSchema
- Export CheckConstraint + CheckConstraintInput from types.ts / exports/types.ts
- Extend build-contract.ts lowering: for each column carrying a valueSet
  (enum-restricted), emit one CheckConstraint into the owning table's checks;
  name = <tableName>_<columnName>_check
- Tests: check-constraint.test.ts (IR shape, StorageTable constructor, validator)
  and check-constraint.authoring.test.ts (lowering, round-trip through
  StorageTable constructor after JSON serialization)

Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 4.8 <[email protected]>
…2851)

- Add SqlCheckConstraintIR to schema-ir (new node carrying name, column, permittedValues)
- Export SqlCheckConstraintIR from schema-ir/types
- Add checks field to SqlTableIR
- Add check_missing / check_mismatch / check_removed to SchemaIssue and ControlResultTypes
- Project CheckConstraint → SqlCheckConstraintIR in contract-to-schema-ir (resolves StorageValueSet ref)
- Add verifyCheckConstraints helper with value-set comparison (order-insensitive; normalises IN vs = ANY (ARRAY[...]))
- Wire verifyCheckConstraints into verifySqlSchema
- Add check_missing / check_mismatch / check_removed classifications to verifier-disposition
- Introspect pg_constraint (contype='c') in PostgresControlAdapter; add parseCheckConstraintDef that handles both = ANY (ARRAY[...]) and IN (...) shapes, strips ::cast suffixes, returns undefined for free-form predicates
- Tests: verifyCheckConstraints unit (equal/missing/removed/mismatch/normalization/unordered-sets), verifySqlSchema integration (wiring), parseCheckConstraintDef unit, PostgresControlAdapter.introspect mock round-trip

Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ift (TML-2851)

F1: extractArrayLiterals/extractQuotedLiterals now collapse Postgres doubled
single-quotes ('' → ') so a value like O'Brien round-trips correctly instead
of returning O''Brien. Tests added for both ARRAY and IN shapes.

F2: parseCheckConstraintDef column-name capture widens from \w+ to also
accept double-quoted identifiers ("my-col"), so hyphenated or otherwise
non-identifier column names no longer silently drop the check. Tests added
for both shapes.

F4: check_mismatch reclassified from declaredIncompatible to valueDrift in
classifySqlVerifierIssueKind, symmetric with enum_values_changed. The
external control policy now suppresses both identically — a check value-set
drift and a native enum member change are governed by the same rule.
Tests updated and new external-policy suppression test added.

Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 4.8 <[email protected]>
…sue) (TML-2851)

Add AddCheckConstraintCall / DropCheckConstraintCall op-factory-call classes and
checkConstraintPlanCallStrategy. The strategy diffs contract-expected checks against
live-introspected checks and emits: AddCheckConstraintCall for a missing check,
Drop + Add for a value-set change, and DropCheckConstraintCall for a removed check.
Extracts resolveValueSetValues from contract-to-schema-ir.ts and exports it for
reuse in the strategy. Registers the strategy in postgresPlannerStrategies between
nativeEnumPlanCallStrategy and storageTypePlanCallStrategy. Adds addCheckConstraint
and dropCheckConstraint pure ops to operations/constraints.ts. Seven planner unit
tests cover all three migration cases plus the planIssues integration path.

Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ver (TML-2851)

`verifySqlSchema` was resolving the value-set ref inline with `?? []`,
so an unresolvable ref silently produced an empty permitted-values set
and an incorrect `check_mismatch` / `check_removed` verdict. The same
missing-ref case already threw a clear malformed-contract error in
`convertCheck` and `checkConstraintPlanCallStrategy` via
`resolveValueSetValues`.

Route the verification path through the same exported
`resolveValueSetValues` so all three sites agree: a well-formed contract
resolves exactly as before; a malformed/unresolvable ref now throws
consistently everywhere.

Also removes the redundant `instanceof StorageTable` guard in the
`checkConstraintPlanCallStrategy` loop body — `collectContractChecks`
already performs that check and returns `[]` for non-`StorageTable`
slots, so the outer guard was dead code.

Adds a test that confirms `verifySqlSchema` throws (not silently
misfires) when a check references a value-set absent from the contract.

Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 4.8 <[email protected]>
…L-2851)

PGlite integration test covering the full check-constraint realization round:

- Initial migration from empty schema creates the table with a
  CHECK (role IN ('user','admin')) constraint (verified via pg_constraint).
- db verify passes against the migrated DB with no check issues.
- The constraint is enforced: permitted values insert cleanly; a
  non-member value is rejected by the database.
- Member change (add 'guest', remove 'admin'): planner emits
  dropCheckConstraint + checkConstraint ops in order, re-apply succeeds,
  verify passes for the new value set, old member is rejected, new member
  inserts cleanly, and pre-existing rows survive unchanged.

Slice-DoD gate: pnpm build → pnpm i → pnpm fixtures:check zero diff;
pnpm typecheck 138/138 clean; lint:casts delta=0; adapter-postgres 579
passed + 4 expected failures; target-postgres 306/306; family-sql 362/362.

Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 4.8 <[email protected]>
@wmadden-electric
wmadden-electric force-pushed the tml-2851-check-constraint-realization branch from 430cc70 to 7245b14 Compare June 8, 2026 07:47
wmadden and others added 5 commits June 8, 2026 09:59
CheckConstraint construction is idempotent by design (reads plain named
properties), so the `cc instanceof CheckConstraint` guard was unnecessary
and violated the repo's no-instanceof rule. Always call `new CheckConstraint(cc)`.

Update the idempotency test to assert structural equality (toEqual) rather
than reference identity (toBe), which was only valid under the old instanceof
branch.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…pe.errors)

The old assertion `expect(result instanceof Error || typeof result === 'object').toBe(true)`
was always true — arktype success results are also objects. Replace with
`expect(result).toBeInstanceOf(type.errors)` to match the pattern used in
foreign-key-cross-space.test.ts.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
The old implementation compared array lengths then checked membership,
returning true for ['a','a'] vs ['a','b'] (same length, 'a' present in
both). Build a Set from each side and compare set sizes + membership so
duplicate values in either side are deduplicated before comparison.

Add a regression test for the duplicate-masking case.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…k contract tables

The guard `if (contractTable.checks && contractTable.checks.length > 0)` skipped
verifyCheckConstraints entirely when the contract declared no checks, so in strict
mode an extra live CHECK on a zero-check table never emitted check_removed.

Build contractCheckIRs unconditionally (defaulting to []) and call
verifyCheckConstraints when strict || contractCheckIRs.length > 0.

Add a strict-mode regression test for this case.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…t composite predicates

Both the = ANY (ARRAY[...]) and IN (...) regexes were anchored only at the
start, so a composite predicate like `status IN ('a','b') AND amount > 0`
partial-matched and was mis-introspected as a plain enum check. Add `\s*$`
end anchors so composite predicates return undefined instead.

Add negative tests for both composite-predicate shapes.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
@wmadden-electric

Copy link
Copy Markdown
Contributor Author

On it — adding semantic (name registration + duplicate-definition) and consistency (column-existence) validation for table.checks in validators.ts 👍

A06a — validateStorageSemantics: register each check constraint name via
registerNamedObject so duplicate names across constraints are detected.
Track duplicate check definitions (same column + valueSet signature) in a
seenCheckDefinitions Set and emit an error for any repeat.

A06b — validateSqlStorageConsistency: iterate table.checks and throw
ContractValidationError (area 'storage') when check.column is not in
columnNames, matching the existing index/unique/FK column-existence checks.

Add tests for both validations.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
@wmadden-electric

Copy link
Copy Markdown
Contributor Author

Done — A06a + A06b implemented in validators.ts (commit c63625d):

A06a (validateStorageSemantics): registered check names via registerNamedObject('check constraint', check.name) so name collisions with other constraints are detected. Added a seenCheckDefinitions Set keyed on {column, valueSet} to catch duplicate definitions.

A06b (validateSqlStorageConsistency): iterates table.checks and throws ContractValidationError (area 'storage') when check.column is not in columnNames, matching the existing index/unique/FK column-existence checks.

Tests added for both.

Resolve the open PSL question: declare the codec as a required block attribute @@type(<codecId>) and each member value with =. The RHS is the codec JSON-encoded form (encodeJson), validated via JSON.parse + codec.decodeJson on the existing PSL-extension value path. Value defaults to the member name for string codecs, required otherwise. Records @Map and the parameterized-header form as rejected (follow-up: TML-2864).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>

@wmadden wmadden left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One small nit, otherwise merge when green

wmadden and others added 2 commits June 8, 2026 11:57
…able.checks (TML-2851)

checks is a general table-level field, not enum-specific; the typed optional field is self-describing.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
@wmadden-electric
wmadden-electric enabled auto-merge (squash) June 8, 2026 09:59
biome 2.4.15 (pulled in via main) escalates noNonNullAssertion to a failing warning, surfacing col.valueSet! in the check-constraint emit. Narrow valueSet with flatMap instead of asserting — no assertion, no cast, identical behavior.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
@wmadden-electric
wmadden-electric merged commit 60b2ed9 into main Jun 8, 2026
20 checks passed
@wmadden-electric
wmadden-electric deleted the tml-2851-check-constraint-realization branch June 8, 2026 10:18
paulwer pushed a commit to paulwer/prisma-next that referenced this pull request Jun 11, 2026
…risma#805)

## Linked issue

Refs
[TML-2882](https://linear.app/prisma-company/issue/TML-2882/slice-transitional-psl-enum2-block-author-the-new-enum-through-psl).
Builds on the merged enum substrate (TML-2850, prisma#750), check enforcement
(TML-2851, prisma#755), and typed read surface (TML-2852, prisma#769).
Hands to TML-2855 (member defaults) and TML-2853 (cutover, now reduced
to rename + migrate + delete).

## At a glance

The demo's PSL schema now authors the new domain-concept enum directly —
while native `enum` keeps working untouched:

```prisma
enum2 Priority {
  @@type("pg/text@1")
  Low    = "low"
  High   = "high"
  Urgent = "urgent"
}

model Post {
  priority Priority
}
```

Emit it and the real app uses it end-to-end through the emitted contract
— `post.priority` reads as `'low' | 'high' | 'urgent'`,
`db.enums.public.Priority.values` returns the ordered tuple, `ORDER BY
priority` sorts by declaration order, and the migration adds the
`CHECK`:

```ts
export async function getPostsByPriority(limit = 10) {
  const plan = db.sql.public.post
    .select('id', 'title', 'priority')
    .orderBy('priority')          // declaration order: low, high, urgent
    .limit(limit)
    .build();
  return db.runtime().execute(plan);
}
```

Before this PR, the new enum mechanism was reachable only through the TS
`enumType` DSL — unreachable from PSL, and therefore from the demo's
real emitted-contract app.

## Decision

Add a **parallel transitional PSL keyword** (`enum2`) that lowers to the
new enum mechanism — domain `enum` entity + storage `valueSet` entity +
field/column `valueSet` restriction refs + check constraint — **reusing
the lowering the TS `enumType` path already has**. Native `enum` is
byte-for-byte untouched.

The point is to dissolve the constraint that forced an atomic cutover:
`enum` is one keyword and can't mean both native and the new shape at
once, so the new mechanism was unreachable through PSL until the very
end of the project. The second keyword makes it PSL-authorable
**additively**, takes it live through the product path (PSL → emit →
app) now, and shrinks the cutover (TML-2853) to a rename + migrate +
delete with the risky lowering already proven in live use.

The keyword is deliberately disposable: it is retired at the cutover,
when `enum` itself repoints at this lowering.

## Reviewer notes

- **The central guarantee is parity:** for the same schema, the PSL
`enum2` path and the TS `enumType` path emit **identical contract JSON,
including `storageHash`**. The parity test
([interpreter.enum2.test.ts](packages/2-sql/2-authoring/contract-psl/test/interpreter.enum2.test.ts))
asserts strict deep equality on every emitted slice plus hash equality —
it started life as `toMatchObject` and was hardened to `toEqual` after
subset matching let a divergence escape (next bullet).
- **Two correction arcs are visible in the history, kept honest rather
than rewritten.** (1) `ead068f57` patched the SQL-family schema verifier
and codec-ref resolver to tolerate a stray `typeRef` the PSL path was
leaking onto emitted columns; review caught that the leak was the bug,
so `3ec205e9e` fixed it at the source and reverted both patches
byte-identically. (2) The first round built a dedicated
`parseEnum2Block` grammar production and a per-target
`entityTypes.enum2` presence stub; review (correctly) rejected both, and
`aad4e15b3`–`99fc662dc` rework enum2 onto the generic extension-block
grammar and delete the stub mechanism entirely.
- **A latent interpreter bug is fixed in passing:** the final contract
reconstruction in `interpretPslDocumentToSqlContract` rebuilt domain
namespace slices copying only `models`/`valueObjects`, silently dropping
`enum` entities. Nothing PSL-authored produced domain enums until now,
so it was unobservable before this PR.
- **The PSL printer silently drops `enum2` blocks.** Verified no
in-scope flow round-trips authored PSL through the printer (it runs only
in the schema-inference direction), so printing support is deferred to
the cutover, where the keyword is renamed anyway.
- **Known emitter gap (pre-existing, now tracked as
[TML-2885](https://linear.app/prisma-company/issue/TML-2885)):** the
emitted `contract.d.ts` narrows enum **column/field types** to the value
union, but does not type the domain `enum` block itself — so on the
emitted path, `db.enums.<ns>.<Name>.members` values are
`JsonValue`-typed at the type level (runtime values are correct). The
demo's literal-union type proofs therefore live on the column types
(SELECT/INSERT), which the emitter does narrow. Project spec R6 amended
to require emit parity; TML-2885 is now a cutover prerequisite.
- `pnpm lint` shows two pre-existing `no-bare-cast` info notices in
files this branch never touches; no new casts are added.

## How it fits together

1. **Grammar — no enum2-specific parsing**
([psl-parser/src/parser.ts](packages/1-framework/2-authoring/psl-parser/src/parser.ts)):
`enum2 Priority { … }` rides the existing generic extension-block
grammar (`<keyword> <Name> { key = value … }`); members are ordinary
parameter lines captured raw. The parser gains three **generic**
extension-block capabilities (each independently tested, usable by any
contributed block): `@@attr(...)` block-attribute lines,
duplicate-parameter diagnostics, and bare-identifier parameters behind a
descriptor opt-in flag.
2. **Interpreter**
([contract-psl/src/interpreter.ts](packages/2-sql/2-authoring/contract-psl/src/interpreter.ts)):
`processEnum2Declarations` consumes the `enum2`-keyword extension blocks
— validates `@@type` presence (required, never inferred), validates each
member's raw value with `JSON.parse` + `codec.decodeJson` (bare members
default to their name for string-accepting codecs), and enforces
well-formedness. Per enum it builds an `EnumTypeHandle` via the existing
`enumType()` and a `ColumnDescriptor` in the existing by-name map — so
field resolution (`priority Priority`) is unchanged and doesn't care
which block declared the name. Support requires no per-target
registration: a target that lacks the codec fails with the unknown-codec
diagnostic; the block descriptor lives at the SQL-family level, marked
`interpreterLowered` (the factory invariant now admits blocks lowered by
the interpreter rather than an entity-type factory).
3. **Lowering is 100% reuse:** the handles flow into the existing
`buildSqlContractFromDefinition` as `enums`, and the domain enum,
storage value-set, field/column `valueSet` refs, and the table check all
fall out of the already-merged build-contract code. Zero new lowering.
4. **Demo goes live**
([examples/prisma-next-demo](examples/prisma-next-demo)): `enum2
Priority` in the PSL schema, re-emitted `contract.json`/`contract.d.ts`,
migration `20260610T0000_add_priority_enum` (addColumn → setNotNull →
addCheckConstraint), and `enum-priority` / `enum-priority-filter`
subcommands consuming the enum through the emitted contract — including
filtering by a live member value via the emitted accessor; seeds and
integration fixtures source values from the emitted accessor too, never
raw literals.

## Behavior changes & evidence

- **The generic extension-block grammar gains `@@attr(...)` block
attributes, duplicate-parameter diagnostics, and opt-in bare-identifier
parameters** — and `enum2` blocks parse through it with zero
block-specific grammar. Implementation:
[parser.ts](packages/1-framework/2-authoring/psl-parser/src/parser.ts),
[psl-extension-block.ts](packages/1-framework/1-core/framework-components/src/shared/psl-extension-block.ts).
Evidence:
[parser-enum2.test.ts](packages/1-framework/2-authoring/psl-parser/test/parser-enum2.test.ts).
- **The interpreter lowers `enum2` to the new two-plane shape,
identically to the TS path** — plus ten validation diagnostics (missing
`@@type`, unknown codec, non-JSON / codec-rejected values, bare member
under non-string codec, duplicate names/values, native-name collision,
namespaced `enum2`, unsupported target). Implementation:
[interpreter.ts](packages/2-sql/2-authoring/contract-psl/src/interpreter.ts).
Evidence:
[interpreter.enum2.test.ts](packages/2-sql/2-authoring/contract-psl/test/interpreter.enum2.test.ts)
— parity incl. `storageHash` equality, all diagnostics, native+enum2
mixed document, non-string codec.
- **The demo proves the feature through the emitted contract** — typed
value-union reads, `db.enums.public.Priority`, declaration-order `ORDER
BY`, and the check-adding migration. Implementation:
[contract.prisma](examples/prisma-next-demo/src/prisma/contract.prisma),
[get-posts-by-priority.ts](examples/prisma-next-demo/src/queries/get-posts-by-priority.ts),
[main.ts](examples/prisma-next-demo/src/main.ts). Evidence:
[demo-dx.types.test.ts](examples/prisma-next-demo/test/demo-dx.types.test.ts)
(non-vacuous: paired `.not.toEqualTypeOf<string>()` + `@ts-expect-error`
on an out-of-union insert), integration suites.
- **Native enums are untouched** — the demo's `user_type` emits
byte-identically; no native fixture changes; the mixed-document test
asserts the native slice is unchanged.

## Testing performed

- `pnpm test:packages` — 799 files, 10,328 tests green on final HEAD
- `pnpm typecheck` — 138 tasks green
- `pnpm fixtures:check` — zero diff outside the demo's deliberately
re-emitted artifacts
- `pnpm lint:deps` — clean
- Demo: type tests + integration suites; `enum-priority` subcommand run
end-to-end (declaration-order sort observed: low, high, urgent).
Occasional PGlite portal flakes reproduced and ruled pre-existing.

## Skill update

n/a — the `enum2` spelling is deliberately transitional and is retired
at the cutover (TML-2853), when `enum` itself gains this meaning.
Documenting a keyword scheduled for deletion in user-facing skills would
teach syntax users should never adopt long-term; the skill update lands
with the cutover rename.

## Follow-ups

- [TML-2885](https://linear.app/prisma-company/issue/TML-2885) — emit
the typed domain `enum` block so `db.enums` is literal-typed through the
emitted contract (R6 emit parity; surfaced by this PR's review; cutover
prerequisite).
- TML-2855 — enum member defaults (`@default(Low)` on a real PSL enum
field).
- TML-2853 — cutover: rename `enum2` → `enum`, migrate remaining native
enums, delete the native machinery, add printer support for the final
keyword.
- Numeric-codec SQL rendering (CHECK / `ORDER BY` for non-text
value-sets) stays guarded — tracked separately.

## Alternatives considered

- **No new keyword — discriminate within `enum` on `@@type` presence.**
The new syntax is already distinguishable from native, so `enum` could
mean the new shape when `@@type` is present. Rejected: it re-overloads
one keyword with two meanings depending on an attribute — exactly the
dual-meaning ambiguity this project removes. An explicit second keyword
is unambiguous, and the cutover rename is trivial.
- **Just do the atomic cutover now.** Rejected: the cutover can't land
until full parity with native (member defaults still outstanding), and
it would be a single non-additive big-bang with no prior live
validation. The transitional keyword exercises the new mechanism in
production use before the irreversible flip.
- **A dedicated `parseEnum2Block` grammar production instead of the
generic extension-block path.** Built in the first round (on the premise
that the missing `@@`-attribute support justified a bespoke parse),
rejected in review: the right fix for the gap was generic
block-attribute support in the extension-block grammar, landed in the
rework.
- **A per-target `entityTypes.enum2` presence registration.** Built in
the first round mirroring native enum's Postgres entry, rejected in
review: native enums are genuinely Postgres-specific, the domain enum is
target-agnostic. Support now falls out of codec resolution; the factory
invariant admits interpreter-lowered blocks.
- **`@map(...)` for member values.** Rejected: `@map` everywhere else in
PSL means a physical storage mapping; the member value is a first-class
domain value, so it's assigned with `=`.
- **Keep the SQL-family tolerance patches instead of fixing the
`typeRef` leak.** Rejected: they masked a parity violation (PSL emit ≠
TS emit, divergent `storageHash`). Fixed at the source; the patches
reverted as dead code.

## Checklist

- [x] All commits are signed off (`git commit -s`) per the
[DCO](../CONTRIBUTING.md#developer-certificate-of-origin-dco). The DCO
status check will block merge if any commit is missing a
`Signed-off-by:` trailer.
- [x] I read [CONTRIBUTING.md](../CONTRIBUTING.md) and the change is
scoped to one logical concern.
- [x] Tests are updated (or `n/a` if the change is doc-only / refactor
with no behavioural delta).
- [x] The PR title is in `TML-NNNN: <sentence-case title>` form (Linear
ticket prefix + concise title naming the concrete deliverable). See
`.claude/skills/create-pr/SKILL.md` for the full convention.
- [x] The **Skill update** section above is filled in (or stated `n/a —
internal only`).


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
* Added Priority enum (Low, High, Urgent) for posts; demo supports
priority-aware listing and filtering.
  * Polymorphic Task types (Bug / Feature) exposed in demo.

* **Migrations**
* DB migration adds non-null post.priority and enforces allowed values.

* **CLI / Demo**
* New demo commands to list posts by priority and filter by priority
member; seed data updated with priorities.

* **Authoring**
* PSL authoring/parser extended to support enum2-style extension blocks.

* **Tests**
* Expanded tests covering enums, queries, seeding, and contract typings.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Signed-off-by: Will Madden <[email protected]>
Co-authored-by: Will Madden <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants