Repository navigation
TML-2850: introduce domain enums + storage value-sets (additive groundwork) - #750
Conversation
Adopt additive-then-cutover sequencing: the new enum representation lands dark in slice 1 (native stays the default; PSL `enum` not repointed), and the single atomic cutover (flip `enum` + delete native) becomes slice 4. `enum` is one keyword and cannot mean both shapes at once, so every intermediate merge stays green. Amends plan.md sequencing; adds the enum-contract-substrate slice spec. Refs TML-2850, TML-2853. Signed-off-by: Will Madden <[email protected]> Co-Authored-By: Claude Opus 4.8 <[email protected]>
Four additive dispatches: domain enum IR + ValueSetRef → storage value-set IR → enumType/member authoring + lowering → serializer/validators/round-trip (with the fixtures:check-clean regression guard). Refs TML-2850. Signed-off-by: Will Madden <[email protected]> Co-Authored-By: Claude Opus 4.8 <[email protected]>
Dispatch 1 of the enum-contract-substrate slice. Purely additive —
no existing behavior changes.
- `ValueSetRef` interface in foundation contract: `{ kind: 'enum' |
'value-set'; namespaceId; name; spaceId? }`. Presence-based
cross-space discrimination, mirrors the ForeignKeyReference carrier
convention. Placed in foundation (not framework-components) because
domain-types lives in the foundation layer which cannot import core.
- `ContractEnum` type: `{ codecId; members: readonly { name; value }[] }`.
Members array is ordered (declaration order preserved).
- `ContractField.valueSet?: ValueSetRef` — additive optional sibling to
the existing scalar `type`; does not replace the codec.
- `ApplicationDomainNamespace.enum?: Record<string, ContractEnum>` —
parallel to existing `models` / `valueObjects` slots.
- All types exported through `@prisma-next/contract/types`.
- Two new test files covering all four shapes and the order invariant.
Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Dispatch 2 of the enum-contract-substrate slice. Purely additive —
no existing behavior changes, zero fixture diff.
- `StorageValueSet` frozen IR node: `{ kind: 'value-set'; values:
readonly string[] }` (ordered, codec-encoded values). Extends
`SqlNode`; `kind` is enumerable and overrides the base non-enumerable
`'sql'` discriminator so the JSON envelope carries the discriminator
for hydration dispatch.
- `SqlNamespace.entries.valueSet?: Record<string, StorageValueSet>` —
optional slot alongside the existing `table` slot in both the
`SqlNamespace` type and `SqlNamespaceTablesInput`. `buildSqlNamespace`
normalises input-shape `StorageValueSetInput` into `StorageValueSet`
instances when the slot is present; the unbound-singleton fast path
still returns `SqlUnboundNamespace.instance` for empty, valueset-free
unbound namespaces.
- `StorageColumn.valueSet?: ValueSetRef` — additive optional restriction
reference imported from `@prisma-next/contract` (foundation). Follows
the existing `declare readonly …` + `if (input.x) this.x = input.x`
pattern for optional fields.
- All new shapes exported via `@prisma-next/sql-contract/types`.
- Unit tests: `StorageValueSet` construction + freeze; namespace with
valueSet entry; `StorageColumn` with cross-space and local `ValueSetRef`.
Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Add `enumType()` / `member()` standalone authoring API for domain-concept enums. An `EnumTypeHandle` carries the literal value tuple via const generics and lowers to both a domain `enum` entry and a storage `valueSet` entry in the contract's default namespace. `field.namedType(handle)` gains a new overload that threads the handle through `FieldNode.enumTypeHandle` so both domain field `valueSet` refs and storage column `valueSet` refs are set during `buildSqlContractFromDefinition`. All changes are additive; the existing postgres native-enum path (`pg/enum@1` codec, `processEnumDeclarations`, `PostgresEnumType`) is untouched. Signed-off-by: Will Madden <[email protected]> Co-Authored-By: Claude Opus 4.8 <[email protected]>
Orchestrator artifacts from the dispatch loop: review scoreboard/findings, project learnings (lint:casts is the real cast gate; build→pnpm i before fixtures:check), and slice-plan updates (ValueSetRef foundation placement, fixtures gate sequence). Refs TML-2850. Signed-off-by: Will Madden <[email protected]> Co-Authored-By: Claude Opus 4.8 <[email protected]>
…-absence test (TML-2850) Convert bare `as` casts introduced in this dispatch to `blindCast` / `Reflect.get` to pass the lint:casts ratchet (delta -1). Add a test pinning the absence of `typeRef` on enum-typed storage columns to guard the invariant that `field.namedType(enumType(...))` emits a `valueSet` ref and not a `typeRef`. Signed-off-by: Will Madden <[email protected]> Co-Authored-By: Claude Opus 4.8 <[email protected]>
…nd-trip (TML-2850)
Dispatch 4 of 4 for the enum-contract-substrate slice. Additive / dark.
- Extend `hydrateSqlNamespaceEntry` in `SqlContractSerializerBase` to walk the
new `valueSet` slot alongside `table`, constructing `StorageValueSet` instances
from the JSON envelope by dispatching on the enumerable `kind:'value-set'`
discriminator. Uses `blindCast` per repo rules — no bare `as` casts.
- Add `StorageValueSetSchema` (kind:'value-set', values:string[]) and
`ContractEnumSchema` ({codecId, members:[{name,value}]}) arktype validator
fragments to `@prisma-next/sql-contract/validators`.
- Wire `StorageValueSetSchema` into `createNamespaceEntrySchema` as a new
`valueSet?` slot on `entries`; wire `ContractEnumSchema` into
`createSqlContractSchema` as a new `enum?` slot on domain namespaces.
- Add `ValueSetRefSchema` and extend `ModelFieldSchema`/`StorageColumnSchema`
to accept the optional `valueSet?` field without rejecting it.
- Round-trip test in `@prisma-next/family-sql`: authored → JSON → hydrate
back produces identical `StorageValueSet` instances; validator accepts valid
contracts and rejects malformed enum/value-set shapes (missing values, bad
member).
- `lint:casts` delta: −1 (net negative vs merge-base).
- `pnpm fixtures:check` diff: zero (slice is dark; no emission changes).
Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 4.8 <[email protected]>
All four dispatches SATISFIED; slice-closing review verified additivity end-to-end (full build → pnpm i → fixtures:check byte-identical). Refs TML-2850. Signed-off-by: Will Madden <[email protected]> Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (4)
✅ Files skipped from review due to trivial changes (1)
🚧 Files skipped from review as they are similar to previous changes (3)
📝 WalkthroughWalkthroughAdds end-to-end enum/value-set support: foundation types (ValueSetRef, ContractEnum), SQL IR node (StorageValueSet) and column/namespace wiring, validators, authoring DSL and enum handles, contract-building lowering changes, serializer hydration, and tests. ChangesEnum Type Support
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
@prisma-next/extension-author-tools
@prisma-next/mongo-runtime
@prisma-next/family-mongo
@prisma-next/sql-runtime
@prisma-next/family-sql
@prisma-next/extension-arktype-json
@prisma-next/middleware-cache
@prisma-next/mongo
@prisma-next/extension-paradedb
@prisma-next/extension-pgvector
@prisma-next/extension-postgis
@prisma-next/postgres
@prisma-next/sql-orm-client
@prisma-next/sqlite
@prisma-next/extension-supabase
@prisma-next/target-mongo
@prisma-next/adapter-mongo
@prisma-next/driver-mongo
@prisma-next/contract
@prisma-next/utils
@prisma-next/config
@prisma-next/errors
@prisma-next/framework-components
@prisma-next/operations
@prisma-next/ts-render
@prisma-next/contract-authoring
@prisma-next/ids
@prisma-next/psl-parser
@prisma-next/psl-printer
@prisma-next/cli
@prisma-next/cli-telemetry
@prisma-next/emitter
@prisma-next/migration-tools
prisma-next
@prisma-next/vite-plugin-contract-emit
@prisma-next/mongo-codec
@prisma-next/mongo-contract
@prisma-next/mongo-value
@prisma-next/mongo-contract-psl
@prisma-next/mongo-contract-ts
@prisma-next/mongo-emitter
@prisma-next/mongo-schema-ir
@prisma-next/mongo-query-ast
@prisma-next/mongo-orm
@prisma-next/mongo-query-builder
@prisma-next/mongo-lowering
@prisma-next/mongo-wire
@prisma-next/sql-contract
@prisma-next/sql-errors
@prisma-next/sql-operations
@prisma-next/sql-schema-ir
@prisma-next/sql-contract-psl
@prisma-next/sql-contract-ts
@prisma-next/sql-contract-emitter
@prisma-next/sql-lane-query-builder
@prisma-next/sql-relational-core
@prisma-next/sql-builder
@prisma-next/target-postgres
@prisma-next/target-sqlite
@prisma-next/adapter-postgres
@prisma-next/adapter-sqlite
@prisma-next/driver-postgres
@prisma-next/driver-sqlite
commit: |
size-limit report 📦
|
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
packages/2-sql/1-core/contract/src/validators.ts (1)
89-94: ⚡ Quick winConsider extracting the duplicated ValueSetRef schema.
The
valueSetschema is inlined at lines 89-94 withinStorageColumnSchemaand then defined separately asValueSetRefSchemaat lines 389-394. This duplication means changes to the ValueSetRef shape must be applied in two places.♻️ Refactor to eliminate duplication
Define
ValueSetRefSchemabeforeStorageColumnSchemaand reference it:+const ValueSetRefSchema = type({ + kind: "'enum' | 'value-set'", + namespaceId: 'string', + name: 'string', + 'spaceId?': 'string', +}); + const StorageColumnSchema = type({ '+': 'reject', nativeType: 'string', codecId: 'string', nullable: 'boolean', 'typeParams?': 'Record<string, unknown>', 'typeRef?': 'string', 'default?': ColumnDefaultSchema, 'control?': ControlPolicySchema, - 'valueSet?': type({ - kind: "'enum' | 'value-set'", - namespaceId: 'string', - name: 'string', - 'spaceId?': 'string', - }), + 'valueSet?': ValueSetRefSchema, }).narrow((col, ctx) => {Then remove the duplicate definition at lines 389-394.
Also applies to: 389-394
🤖 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 89 - 94, The StorageColumnSchema currently inlines the valueSet shape for the 'valueSet?' property which duplicates the separately defined ValueSetRefSchema (lines 389-394); refactor by defining ValueSetRefSchema once (place it before StorageColumnSchema) and change StorageColumnSchema's 'valueSet?' field to reference ValueSetRefSchema instead, then remove the duplicate inline definition so only ValueSetRefSchema remains.
🤖 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/2-authoring/contract-ts/src/build-contract.ts`:
- Around line 379-387: The field value-set refs
(storageValueSetRef/domainValueSetRef built around enumHandle in buildField) use
the model's namespaceId and enumHandle.enumName, but enum registration later
uses defaultNamespaceId and the definition.enums object key, causing dangling
refs for non-default namespaces and alias mismatches; change the enum
registration (the code that registers authored enums from definition.enums) to
register each enum under the model's namespaceId (not defaultNamespaceId) and
use the enum handle's canonical name (enumHandle.enumName) as the registration
key (or resolve aliases so the registered key matches enumHandle.enumName) so
that storageValueSetRef/domainValueSetRef and the authored-enum registry
reference the same namespace and name pair consistently (refer to enumHandle,
isValueObjectField, storageValueSetRef, domainValueSetRef, defaultNamespaceId,
and definition.enums).
---
Nitpick comments:
In `@packages/2-sql/1-core/contract/src/validators.ts`:
- Around line 89-94: The StorageColumnSchema currently inlines the valueSet
shape for the 'valueSet?' property which duplicates the separately defined
ValueSetRefSchema (lines 389-394); refactor by defining ValueSetRefSchema once
(place it before StorageColumnSchema) and change StorageColumnSchema's
'valueSet?' field to reference ValueSetRefSchema instead, then remove the
duplicate inline definition so only ValueSetRefSchema remains.
🪄 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: 466eb35e-e930-4dc5-b972-619969dd59e8
⛔ Files ignored due to path filters (5)
projects/enums-as-domain-concept/learnings.mdis excluded by!projects/**projects/enums-as-domain-concept/plan.mdis excluded by!projects/**projects/enums-as-domain-concept/reviews/code-review.mdis excluded by!projects/**projects/enums-as-domain-concept/slices/enum-contract-substrate/plan.mdis excluded by!projects/**projects/enums-as-domain-concept/slices/enum-contract-substrate/spec.mdis excluded by!projects/**
📒 Files selected for processing (24)
packages/1-framework/0-foundation/contract/src/domain-envelope.tspackages/1-framework/0-foundation/contract/src/domain-types.tspackages/1-framework/0-foundation/contract/src/exports/types.tspackages/1-framework/0-foundation/contract/src/value-set-ref.tspackages/1-framework/0-foundation/contract/test/domain-enum-slot.test.tspackages/1-framework/0-foundation/contract/test/value-set-ref.test.tspackages/2-sql/1-core/contract/src/exports/types.tspackages/2-sql/1-core/contract/src/ir/build-sql-namespace.tspackages/2-sql/1-core/contract/src/ir/sql-storage.tspackages/2-sql/1-core/contract/src/ir/storage-column.tspackages/2-sql/1-core/contract/src/ir/storage-value-set.tspackages/2-sql/1-core/contract/src/types.tspackages/2-sql/1-core/contract/src/validators.tspackages/2-sql/1-core/contract/test/storage-value-set.test.tspackages/2-sql/2-authoring/contract-ts/src/build-contract.tspackages/2-sql/2-authoring/contract-ts/src/contract-builder.tspackages/2-sql/2-authoring/contract-ts/src/contract-definition.tspackages/2-sql/2-authoring/contract-ts/src/contract-dsl.tspackages/2-sql/2-authoring/contract-ts/src/contract-lowering.tspackages/2-sql/2-authoring/contract-ts/src/enum-type.tspackages/2-sql/2-authoring/contract-ts/src/exports/contract-builder.tspackages/2-sql/2-authoring/contract-ts/test/enum-type.authoring.test.tspackages/2-sql/9-family/src/core/ir/sql-contract-serializer-base.tspackages/2-sql/9-family/test/value-set-roundtrip.test.ts
…nceof; prune data-only tests (TML-2850) Replace the single `kind: 'enum' | 'value-set'` field on ValueSetRef with two orthogonal axes: `plane: 'domain' | 'storage'` and `entityKind: 'enum' | 'value-set'`. Update all construction sites in build-contract.ts, consolidate the duplicated ValueSetRefSchema in validators.ts (one definition, reused in both StorageColumnSchema and ModelFieldSchema), and update all test assertions to match the new shape. Remove two data-only construction tests (domain-enum-slot.test.ts and value-set-ref.test.ts) whose coverage is fully superseded by the authoring → structure tests in enum-type.authoring.test.ts and the serializer round-trip tests in value-set-roundtrip.test.ts. Replace the two instanceof + blindCast guard pairs in SqlBoundNamespace constructor with unconditional `new StorageTable(v)` / `new StorageValueSet(v)` — both classes accept their own instances as input (idempotent construction), so the instanceof check was unnecessary. Removes two blindCast calls (lint:casts delta = -1 vs merge-base). Signed-off-by: Will Madden <[email protected]> Co-Authored-By: Claude Opus 4.8 <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 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/1-framework/0-foundation/contract/src/value-set-ref.ts`:
- Around line 20-26: Replace the broad ValueSetRef interface with a
discriminated union that enforces the valid plane/entityKind pairs: one variant
for plane: 'domain' with entityKind: 'enum' and another for plane: 'storage'
with entityKind: 'value-set', while preserving the common fields (namespaceId,
name, optional spaceId) so existing consumers and filters can still access those
properties; update any references to ValueSetRef to accept the union type (the
symbol ValueSetRef and its fields plane and entityKind are the points to
change).
🪄 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: 9cb064c6-c8d2-4134-88fb-78c59fa287ff
📒 Files selected for processing (6)
packages/1-framework/0-foundation/contract/src/value-set-ref.tspackages/2-sql/1-core/contract/src/ir/build-sql-namespace.tspackages/2-sql/1-core/contract/src/validators.tspackages/2-sql/2-authoring/contract-ts/src/build-contract.tspackages/2-sql/2-authoring/contract-ts/test/enum-type.authoring.test.tspackages/2-sql/9-family/test/value-set-roundtrip.test.ts
✅ Files skipped from review due to trivial changes (1)
- packages/2-sql/9-family/test/value-set-roundtrip.test.ts
🚧 Files skipped from review as they are similar to previous changes (3)
- packages/2-sql/1-core/contract/src/ir/build-sql-namespace.ts
- packages/2-sql/1-core/contract/src/validators.ts
- packages/2-sql/2-authoring/contract-ts/src/build-contract.ts
…ration key == enum name (TML-2850)
Field/column valueSet refs were using the consuming model's namespaceId,
but authored enums always register under the contract's defaultNamespaceId.
A model in a non-default namespace therefore produced refs pointing at a
namespace where the enum was never registered. Fix: use defaultNamespaceId
in both valueSet ref constructions.
Also throw early when the enums object key differs from the enumType name.
With the old code, { MyAlias: enumType('Role', …) } would register under
'MyAlias' but build refs pointing at 'Role'. Aliases are not a supported
feature; a clear error is better than a silent dangling ref.
Two new tests cover these cases:
- A model in a non-default namespace uses an enum; asserts the emitted
field/column valueSet ref carries defaultNamespaceId, not the model's ns.
- An enums key that doesn't match the enumType name throws the key-check
error.
Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Delete the committed review scoreboard and learnings ledger — these are transient working state from the dispatch loop, not PR content; they migrate to durable docs at project close-out. Gitignore projects/*/reviews/ and projects/*/learnings.md so they are never committed into slice PRs again. Refs TML-2850. Signed-off-by: Will Madden <[email protected]> Co-Authored-By: Claude Opus 4.8 <[email protected]>
wmadden
left a comment
There was a problem hiding this comment.
I'm satisfied. Address the CodeRabbit comments and merge
Add JSDoc docstring to `EnumMember` interface — the only new public exported symbol in the slice that was missing one. All other new exports (member, enumType, EnumTypeHandle, isEnumTypeHandle, ENUM_TYPE_HANDLE_BRAND, ValueSetRef, StorageValueSetInput, StorageValueSet, ContractEnum, StorageValueSetSchema, ContractEnumSchema) already had docstrings. Signed-off-by: Will Madden <[email protected]> Co-Authored-By: Claude Opus 4.8 <[email protected]>
…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]>
At a glance
Today, declaring an enum means declaring a Postgres-specific storage type. This PR adds a new way to model the same idea as an application concept, authored like this:
Rolecarries its values as a precise type —Role.valuesisreadonly ['user', 'admin'], notstring[]— and lowers into the contract on both planes:That is the whole shape this PR introduces. Nothing emits it by default yet — see "Landed dark" below.
The decision
An enum is a domain-plane concept, not a storage type. The model: a codec is the type (the set of values a column may hold); an enum is a named restriction narrowing that set to specific values. So a field keeps its codec, always, and additionally carries a
valueSetreference when it is enum-restricted. Storage realizes the restriction as a named value-set (and, in a later slice, a check constraint) — never a nativeCREATE TYPE ... AS ENUM.Full rationale:
projects/enums-as-domain-concept/{spec,design-notes}.md.How the shape is built, piece by piece
valueSetpointers above are the same coordinate —{ kind, namespaceId, name, spaceId? }— matching the existingForeignKeyReferencecarrier (presence ofspaceIdis the cross-space discriminator; no tag field). It lives in the foundation package so both planes can use it;kindsays which plane the referent is in ('enum'in domain,'value-set'in storage).ContractEnum(domain: a codec + ordered name→value members) andStorageValueSet(storage: the ordered permitted values, a frozen IR node). The value-set becomes a first-class entity automatically — the coordinate walker iterates a namespace'sentriesstructurally, so it picks up the new slot with zero walker change.enumType/memberbuild an ordered name→value map whose literal value tuple survives end to end (the type-testexpectTypeOf(Role.values).toEqualTypeOf<readonly ['user','admin']>()is the guarantee).field.namedType(Role)lowers to the domain enum entry, the storage value-set entry, and thevalueSetrefs on the field and column — pointing at the value-set, not reusing the nativetypeRefmechanism (pinned by a test).Landed dark — and why
enumis one keyword; it cannot mean both the native type and this new shape at once. So this PR lands the new representation without making it the default: PSLenum, the existing authoring, and the native Postgres enum path are all untouched, and the new shape is reachable only through theenumTypeAPI above. The cutover — repointingenumto the new shape and deleting the native machinery — is a single atomic later slice (TML-2853), which keeps every merge in between green.The payoff of landing dark is a clean additivity guarantee, and it is verified rather than asserted:
pnpm build→pnpm i→pnpm fixtures:checkregenerates the entire repo's fixtures byte-identically (zero diff, zero migration drift), andpnpm lint:castsis net-negative. This PR changes no emitted output.Scope — deliberately out (later slices)
db.enums, declaration-orderORDER BY→ TML-2852.enum+ delete the native machinery → TML-2853.Alternatives considered
ALTER TYPE ... ADD VALUEcannot run in a transaction; text-only. A value-set + check constraint makes add/remove/rename ordinaryALTER TABLEs on every SQL target. (Native can return later as an alternate storage realization under the same domain enum.)codec | enum. Rejected: it breaks the invariant that every field/column has a codec — a foundational change that ripples everywhere. A codec is the type; an enum is an additive restriction on top of it.enumto the new shape before its realization (enforcement + migration, TML-2851) exists would leave enum-using contracts unmigratable in between. Dark, plus a single atomic cutover, keeps every intermediate state shippable.Refs TML-2850.
🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Tests