Repository navigation
TML-2852: enums become first-class in application code — typed I/O, db.enums, declaration-order ORDER BY - #769
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughParameterizes enum generics in contract authoring, widens enum member/value typing and encodes values during contract build, exposes typed enum accessors on the ORM client, adds enum-aware ORDER BY lowering in Postgres renderer, and adds type/runtime tests and demo integration across the stack. ChangesEnum Support Across the Stack
Sequence Diagram (high-level flow) sequenceDiagram
participant Authoring as ContractAuthoring
participant Builder as ContractBuilder
participant Runtime as ORMRuntime
participant Postgres as PostgresRenderer
ContractAuthoring->>ContractBuilder: defineContract/enums + enumType
ContractBuilder->>ContractBuilder: encodeEnumValue, merge scaffold+factory enums
ContractBuilder->>ORMRuntime: produce SqlContractResult (enumAccessors)
ORMRuntime->>ORMRuntime: buildEnumsMap/createEnumAccessor (lazy on db.enums)
ORMRuntime->>PostgresRenderer: query AST with enum-backed columns
PostgresRenderer->>PostgresRenderer: renderOrderByExpr -> array_position over valueSet
🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
🚥 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 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 📦
|
…ut types (TML-2852 Dispatch 1) FieldOutputType and FieldInputType in contract-types.ts now resolve to the literal value union (e.g. 'user' | 'admin') when the field was authored with field.namedType(enumHandle), instead of falling back to the codec's string output. The key fix was replacing the ModelStorageColumn conditional path (which TypeScript defers because it contains a type-variable extends check) with a direct ModelFieldState index access for the nullable and codec-id lookups. ExtractOutputType in query-builder/selection.ts now consults ExtractFieldOutputTypes via a FindModelForTable/FindFieldForColumn lookup before falling back to the codec type, so enum columns propagate the literal union through TableToSelection as well. Type-tests added in all four affected packages (contract-ts, sql-orm-client, sql-builder, query-builder) covering both read output and write input, plus a negative case that rejects out-of-union literals. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…ient Adds `db.enums.<Name>` to the sql-orm-client: a runtime accessor map built from the contract domain enum entity, plus the type-level connection so `db.enums.Role.values` resolves to the literal value tuple and `.members.User` to the value literal. - enum-accessor.ts: `createEnumAccessor` / `buildEnumsMap` (no bare casts; `Object.freeze` already yields `readonly`). - orm.ts: Proxy `enums` branch + `enums` typed off the contract`s `enumAccessors`. - contract-builder.ts: thread a `const Enums` generic through `defineContract` so authored enum handles keep their literal types. - contract-types.ts: `BuiltEnumAccessors` derives the accessor shape from the authored `EnumTypeHandle`; widened (enum-less) contracts stay empty. - Tests: runtime accessors + Proxy branch; a type-test asserting the literal `values` tuple (not `string[]`) and `.members.User === 'user'`. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
… BY (TML-2852 Dispatch 3) An ORDER BY on an enum-restricted column now renders array_position(ARRAY[v1, v2, …]::text[], <col>) over the value-set's ordered values, so rows sort by declaration order rather than lexically. The Postgres sql-renderer builds an alias→storage-coordinate map from the SELECT's FROM and JOIN table sources, resolves an ORDER BY column-ref to its storage column, and — when that column carries a valueSet — emits the array_position expression from the value-set's ordered values. Non-enum columns render unchanged. A PGlite integration test inserts rows out of declaration order and asserts the declaration-order result, plus a nullable-column case (array_position returns NULL for NULL rows, which sort last under the default ASC NULL handling). Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
d33e6a2 to
c011d3a
Compare
wmadden
left a comment
There was a problem hiding this comment.
Only a few small comments. Overall looks good.
…solution (TML-2852) D1 rewrote FieldOutputType/FieldInputType with an inline ResolveFieldDescriptor path that re-widened non-enum field result types to string (id, createdAt), regressing the query-builder ResultType inference covered by integration-tests contract-builder.test.ts and .types.test-d.ts. Restore mains codec-based resolution verbatim as FieldCodecOutputType and FieldCodecInputType, and layer the enum value-union narrowing on top via EnumNarrowedType, which only narrows when the field carries an enum typeRef. The non-enum widening came from EnumValueUnion structurally matching the default EnumTypeHandle and inferring Values as string[]. Guard it with a tuple-wrapped extends check plus a string[] extends Values bail-out so only fields with a concrete enum handle narrow; everything else falls through to mains codec output. In query-builder selection.ts, ExtractOutputType consults the field-output typemap only when it carries a concrete literal override, otherwise falling back to mains exact ExtractCodecTypes codec output expression. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…(TML-2852)
D2 added enums to OrmClient, so the loose () => ({ lane }) mocks no longer
overlap typeof orm and the as typeof ormMock cast failed with TS2352. Route the
mock implementations through unknown so the consumer stubs satisfy the richer
client type without weakening OrmClient.enums.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…rder sort (TML-2852) The Postgres ORDER BY enum hook only matched qualified column-ref order items. The sql-builders .orderBy(col) string and callback forms both emit an identifier-ref (bare column, no table qualifier), so a natural ORDER BY on an enum column fell through to a plain column reference and sorted lexically. Resolve identifier-ref order columns against the SELECTs FROM/JOIN sources and render array_position over the value-sets ordered values when exactly one source carries that enum column; an ambiguous name across joined tables falls through to the bare column. Adds a PGlite test for the identifier-ref form. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
… end to end (TML-2852) A focused example app authored with the TypeScript enumType API (not PSL enum) that demonstrates all three slice surfaces against PGlite: - Typed I/O: the enum field reads as the value union (not string) and a write only accepts the union; an out-of-union literal is a compile error (enum-demo.types.test-d.ts). - db.enums: the runtime accessor exposes values/names/members/has/ordinalOf in declaration order (enum-demo.integration.test.ts). - Declaration-order ORDER BY via array_position, plus the slice-2 CHECK constraint rejecting out-of-union values (enum-demo.integration.test.ts). The runtime passes the TypeScript-authored contract directly so the value-union types flow from the authored definition. The emitted contract.json / contract.d.ts are committed and kept current via emit:check. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[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/3-targets/6-adapters/postgres/src/core/sql-renderer.ts`:
- Around line 282-297: The current resolution loop over sourcesByRef only treats
ambiguity when multiple enum-backed columns match, allowing a rewrite to
array_position(...) when the same column name exists on multiple sources but
only one is enum; change the logic in sql-renderer.ts so that before setting
resolved (and before performing the array_position rewrite) you first count
matches of the identifier across all sources (use sourcesByRef and
contract.storage.namespaces lookups used in the existing loop), and only proceed
to set resolved/valueSet and perform the enum rewrite when the identifier
matches exactly one source column in total (not just one enum column); apply the
same uniqueness check to the other matching block that leads to the
array_position rewrite (the code around the existing resolved variable usage and
the 317-321 region) so ambiguous column names are not rewritten.
🪄 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: 7c1e650a-68d2-4642-b876-c4cedb51f2f4
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (19)
examples/enum-demo/README.mdexamples/enum-demo/biome.jsoncexamples/enum-demo/package.jsonexamples/enum-demo/prisma-next.config.tsexamples/enum-demo/src/contract.d.tsexamples/enum-demo/src/contract.jsonexamples/enum-demo/src/contract.tsexamples/enum-demo/src/db.tsexamples/enum-demo/test/enum-demo.integration.test.tsexamples/enum-demo/test/enum-demo.types.test-d.tsexamples/enum-demo/test/init-db.tsexamples/enum-demo/tsconfig.jsonexamples/enum-demo/vitest.config.tspackages/2-sql/2-authoring/contract-ts/src/contract-types.tspackages/2-sql/4-lanes/query-builder/src/selection.tspackages/3-extensions/postgres/test/postgres.test.tspackages/3-extensions/sqlite/test/transaction.test.tspackages/3-targets/6-adapters/postgres/src/core/sql-renderer.tspackages/3-targets/6-adapters/postgres/test/migrations/order-by-enum.integration.test.ts
✅ Files skipped from review due to trivial changes (8)
- examples/enum-demo/tsconfig.json
- examples/enum-demo/prisma-next.config.ts
- examples/enum-demo/src/contract.ts
- packages/3-extensions/sqlite/test/transaction.test.ts
- examples/enum-demo/src/contract.json
- examples/enum-demo/biome.jsonc
- examples/enum-demo/README.md
- examples/enum-demo/src/contract.d.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- packages/2-sql/4-lanes/query-builder/src/selection.ts
- packages/2-sql/2-authoring/contract-ts/src/contract-types.ts
…L-2852) Reduce the enum value-union narrowing to a shallow, single-pass form and fix a non-null enum column reading as `union | null`. Behavior spec (TDD, tests first): - A non-null enum field reads/writes as exactly its value union (no `| null`). - A nullable enum field reads/writes as `union | null`. - A non-text (int-backed) enum narrows to its int value union (e.g. `1 | 10`). - Non-enum fields keep their codec output unchanged. Implementation: - contract-types.ts: compute a field`s non-null base type once (enum value union when the field is enum-typed, else the codec channel), apply nullability once. Replaces the deeply nested FieldCodecOutputType / EnumNarrowedType pair (max conditional depth ~10 -> ~4). - contract-types.ts: resolve an enum-handle field`s storage descriptor and type-ref from the handle, so an enum column is a real StorageColumn with the correct `nullable: false` instead of collapsing to `never` (the `never extends true` vacuous-truth that injected the spurious `| null` in the select lane). - query-builder selection.ts: delete FindModelForTable / FindFieldForColumn / EnumOutputOverride / FieldOutputTypeFor; read the FieldOutputTypes override in one flat mapped-type pass (max depth ~7 -> ~3). - enum-type.ts + build-contract.ts: enum member values may be string or number literals (preserved in the handle for narrowing); encode to strings when lowering to the storage value-set / domain enum members. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…enum-demo (TML-2852)
Move the enum read-surface example out of a standalone `examples/enum-demo`
app and into the existing `prisma-next-demo`, and fix the Postgres value-set
materialization gap the move surfaced.
- Postgres value-set materialization: `postgresCreateNamespace` and the
Postgres contract serializer dropped the `entries.valueSet` slot, so an
`enumType`-authored enum built through the Postgres builder lost its
storage value-set. The CHECK constraint and the declaration-order ORDER BY
both reference that value-set, so `db init` failed ("value-set not found")
and ORDER BY fell through to a bare column. `PostgresSchema` now carries
`valueSet`, and the serializer round-trips it.
- postgres `defineContract`: thread an `enums` field through the wrapper so a
Postgres contract can declare `enumType` enums; re-export `enumType` /
`member` / `EnumTypeHandle` from `@prisma-next/postgres/contract-builder`.
- prisma-next-demo: add a TS-authored `enumType` enum (`Priority`) on a small
definition-form contract and demonstrate the three surfaces with tests —
typed read/write narrowing (`*.types.test-d.ts`), `db.enums` accessors, and
declaration-order ORDER BY against a dev database. PSL `enum` stays native.
- Delete `examples/enum-demo` entirely (workspace + lockfile).
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…any joined source shares the name (TML-2852) resolveEnumOrderValuesForIdentifier only fell through when two enum-backed columns matched. A join where the same column name exists on multiple sources but only one is enum-backed still rewrote to array_position over a bare identifier — ambiguous SQL. Now count every source column with that name (enum or not); rewrite only when exactly one source has it and it carries a value-set. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
There was a problem hiding this comment.
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/2-authoring/contract-ts/src/enum-type.ts (1)
188-203:⚠️ Potential issue | 🟠 Major | ⚡ Quick winValidate uniqueness on the lowered storage value.
seenValuesnow treats1and'1'as distinct, butbuild-contract.tslater normalizes both to"1". That meansenumType('E', ..., member('One', 1), member('TextOne', '1'))passes here and then emits duplicate enum/value-set entries downstream. Please compare uniqueness onString(m.value)(or otherwise on the lowered representation) so authored enums stay one-to-one after serialization.🛠️ Suggested fix
- const seenValues = new Set<string | number>(); + const seenLoweredValues = new Set<string>(); for (const m of members) { if (seenNames.has(m.name)) { throw new Error( `enumType("${name}"): duplicate member name "${m.name}". Member names must be unique.`, ); } seenNames.add(m.name); - if (seenValues.has(m.value)) { + const loweredValue = String(m.value); + if (seenLoweredValues.has(loweredValue)) { throw new Error( - `enumType("${name}"): duplicate member value "${m.value}". Member values must be unique.`, + `enumType("${name}"): duplicate member value "${loweredValue}" after storage encoding. Member values must be unique.`, ); } - seenValues.add(m.value); + seenLoweredValues.add(loweredValue); }🤖 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/2-authoring/contract-ts/src/enum-type.ts` around lines 188 - 203, The uniqueness check for enum member values in the members loop treats numeric 1 and string "1" as distinct; change the logic in enum-type.ts (inside the members iteration where seenValues is used) to compare and store the lowered/serialized representation (e.g., String(m.value)) so duplication is detected after serialization; update seenValues to be a Set<string>, perform seenValues.has(String(m.value)) for the duplicate check, and then seenValues.add(String(m.value)) when storing the value.packages/2-sql/2-authoring/contract-ts/src/contract-types.ts (1)
594-603:⚠️ Potential issue | 🟠 MajorFix
enumAccessorsaccessor method parameter types to use the authored enum value union
EnumHandleAccessorTypestill typeshas/nameOf/ordinalOfasv: string(even though enum handles arestring | numberat runtime and carry literal value tuples), so int-backed enums will incorrectly rejectdb.enums.<Enum>.has(1)/nameOf(10)/ordinalOf(1)at compile time.🛠️ Suggested fix
type EnumHandleAccessorType<Handle> = Handle extends EnumTypeHandle<infer _Name, infer Values, infer Names, infer MembersMap> ? { readonly values: Values; readonly names: Names; readonly members: MembersMap; - has(v: string): boolean; - nameOf(v: string): string | undefined; - ordinalOf(v: string): number; + has(v: Values[number]): boolean; + nameOf(v: Values[number]): string | undefined; + ordinalOf(v: Values[number]): number; } : never;🤖 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/2-authoring/contract-ts/src/contract-types.ts` around lines 594 - 603, EnumHandleAccessorType currently types the has/nameOf/ordinalOf parameters as v: string which prevents numeric enum values from compiling; update the parameter types for has, nameOf, and ordinalOf to accept the authored enum value union (use the inferred Values tuple to derive the value type, e.g. Values[number] or the equivalent union) in the EnumHandleAccessorType definition so these methods accept both string and numeric enum members.
🧹 Nitpick comments (1)
examples/prisma-next-demo/test/utils/enum-control-client.ts (1)
27-29: 💤 Low valueOptional: remove redundant
mkdirSyncaftermkdtempSync.
mkdtempSyncat line 27 already creates the directory atomically, so themkdirSynccall at line 29 is redundant. While therecursive: trueflag makes this a harmless no-op, removing it would simplify the code.♻️ Simplify by removing the redundant mkdir
const migrationsDir = mkdtempSync(join(tmpdir(), 'prisma-next-demo-enum-migrations-')); try { - mkdirSync(migrationsDir, { recursive: true }); const initResult = await client.dbInit({🤖 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 `@examples/prisma-next-demo/test/utils/enum-control-client.ts` around lines 27 - 29, Remove the redundant mkdirSync call: after creating migrationsDir with mkdtempSync (symbol migrationsDir), delete the subsequent mkdirSync(migrationsDir, { recursive: true }) invocation since mkdtempSync already creates the directory atomically; ensure any surrounding try/catch or error handling still makes sense after removing the mkdirSync line.
🤖 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/2-authoring/contract-ts/src/contract-types.ts`:
- Around line 594-603: EnumHandleAccessorType currently types the
has/nameOf/ordinalOf parameters as v: string which prevents numeric enum values
from compiling; update the parameter types for has, nameOf, and ordinalOf to
accept the authored enum value union (use the inferred Values tuple to derive
the value type, e.g. Values[number] or the equivalent union) in the
EnumHandleAccessorType definition so these methods accept both string and
numeric enum members.
In `@packages/2-sql/2-authoring/contract-ts/src/enum-type.ts`:
- Around line 188-203: The uniqueness check for enum member values in the
members loop treats numeric 1 and string "1" as distinct; change the logic in
enum-type.ts (inside the members iteration where seenValues is used) to compare
and store the lowered/serialized representation (e.g., String(m.value)) so
duplication is detected after serialization; update seenValues to be a
Set<string>, perform seenValues.has(String(m.value)) for the duplicate check,
and then seenValues.add(String(m.value)) when storing the value.
---
Nitpick comments:
In `@examples/prisma-next-demo/test/utils/enum-control-client.ts`:
- Around line 27-29: Remove the redundant mkdirSync call: after creating
migrationsDir with mkdtempSync (symbol migrationsDir), delete the subsequent
mkdirSync(migrationsDir, { recursive: true }) invocation since mkdtempSync
already creates the directory atomically; ensure any surrounding try/catch or
error handling still makes sense after removing the mkdirSync line.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: a209978a-97a7-42f7-9907-30108d7a8de5
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (15)
examples/prisma-next-demo/prisma/enum-contract.tsexamples/prisma-next-demo/prisma/enum-db.tsexamples/prisma-next-demo/test/enum-surface.integration.test.tsexamples/prisma-next-demo/test/enum-surface.types.test-d.tsexamples/prisma-next-demo/test/utils/enum-control-client.tspackages/2-sql/2-authoring/contract-ts/src/build-contract.tspackages/2-sql/2-authoring/contract-ts/src/contract-types.tspackages/2-sql/2-authoring/contract-ts/src/enum-type.tspackages/2-sql/2-authoring/contract-ts/test/enum-type.field-output.test.tspackages/2-sql/4-lanes/query-builder/src/selection.tspackages/3-extensions/postgres/src/contract/define-contract.tspackages/3-extensions/postgres/src/exports/contract-builder.tspackages/3-targets/3-targets/postgres/src/core/postgres-contract-serializer.tspackages/3-targets/3-targets/postgres/src/core/postgres-schema.tstest/integration/test/contract-builder.types.test-d.ts
✅ Files skipped from review due to trivial changes (1)
- packages/3-extensions/postgres/src/exports/contract-builder.ts
Collapse the enum read/write field-type helpers to the flattest shape the behavior tests require, without changing non-enum resolution: - Replace the `IsEnumTypeRef` boolean threaded through three descriptor resolvers with a single `EnumFieldHandle<FieldState>` that yields the handle (or never). `ResolveFieldDescriptor` and `ResolveFieldColumnTypeRef` now short-circuit on it; for non-enum fields both reduce to mains exact bodies. `ResolveFieldColumnTypeParams` reverts to byte-identical-to-main (it already produced undefined for enum fields via the column-type-ref). - Merge `FieldOutputType` + `FieldInputType` + `FieldNullable` + `FieldBaseType` into one channel-parameterised `FieldChannelType` and one `FieldChannelTypes` map; nullability is a flat union member, not an outer conditional. Net -27 lines; no behavior change (enum field-output type-tests and the full-lane ResultType spec stay green). Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…852) The factory form of defineContract dropped a top-level `enums` key returned from the factory callback: its `Built` generic carried only `types`/`models` and the impl spread only those, so an enum authored through the factory never reached `SqlContractResult` -> field narrowing / db.enums. Mirror the definition form. The factory `Built` type now carries `readonly enums?: Enums` captured with a `const Enums` generic, the impl spreads `built.enums`, and the public factory overload merges scaffold-declared and factory-returned enums into the narrowing `Enums` slot. A parity type-test asserts the factory form narrows field reads/writes to the value union and surfaces the same `enumAccessors` shape as the definition form. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…L-2852) Thread a factory-returned `enums` key through the Postgres `defineContract` wrapper so its factory form carries enum handles (previously only the scaffold arg did), mirroring the base builder. The demo contract (factory form) now declares a `Priority` enum (declaration order low -> high -> urgent, which differs from lexical) and references it on `Post.priority` via `field.namedType`. The no-emit app code consumes it for real: `getPostsByPriority` reads the narrowed value union and orders by declaration order, and `getPriorityEnum` surfaces `db.enums.Priority`. The rewritten enum-surface tests prove the read narrows to the union (not string), `db.enums` exposes the declaration-ordered runtime surface, declaration-order ORDER BY sorts low/low/high/urgent, and the CHECK constraint rejects out-of-union writes. Removes the side-contract (prisma/enum-contract.ts, prisma/enum-db.ts, test/utils/enum-control-client.ts) it replaces. The PSL schema is untouched (PSL enum repoint is a later slice). Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
packages/2-sql/2-authoring/contract-ts/src/contract-types.ts (1)
596-605:⚠️ Potential issue | 🟠 Major | ⚡ Quick winAccept numeric enum values in accessor lookups.
Lines 602-604 hard-code
stringlookup inputs, but this PR also introduces int-backed enums (Priorityin the new factory-form test is1 | 10). That meansenumAccessors.Priority.has(1),nameOf(1), andordinalOf(1)are rejected by the public types even though numeric enum values are now first-class elsewhere in the surface.Suggested fix
type EnumHandleAccessorType<Handle> = Handle extends EnumTypeHandle<infer _Name, infer Values, infer Names, infer MembersMap> ? { readonly values: Values; readonly names: Names; readonly members: MembersMap; - has(v: string): boolean; - nameOf(v: string): string | undefined; - ordinalOf(v: string): number; + has(v: string | number): boolean; + nameOf(v: string | number): Names[number] | undefined; + ordinalOf(v: string | number): number; } : never;🤖 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/2-authoring/contract-ts/src/contract-types.ts` around lines 596 - 605, The accessor type EnumHandleAccessorType currently restricts lookup inputs to string, which breaks int-backed enums; update the method signatures on EnumHandleAccessorType (the has, nameOf, and ordinalOf members) to accept both string and number (e.g., change parameter type from string to string | number) so numeric enum values like 1 or 10 are allowed in lookups while keeping return types the same.packages/2-sql/2-authoring/contract-ts/src/contract-builder.ts (1)
435-439:⚠️ Potential issue | 🟠 Major | ⚡ Quick winMerge scaffold and factory enums before building the contract.
Lines 435-439 currently overwrite
definition.enumswithbuilt.enums. That disagrees with the factory-form type on Lines 504-529, which advertisesMergeEnums<ScaffoldEnums, FactoryEnums>. In a mixed contract, any scaffold-authored enum disappears from the built contract as soon as the factory returns anenumsobject, so the runtime enum surface no longer matches the published type.Suggested fix
return buildContractFromDsl({ ...full, ...ifDefined('types', built.types), ...ifDefined('models', built.models), - ...ifDefined('enums', built.enums), + ...ifDefined( + 'enums', + built.enums === undefined + ? undefined + : { + ...(definition.enums ?? {}), + ...built.enums, + }, + ), });🤖 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/2-authoring/contract-ts/src/contract-builder.ts` around lines 435 - 439, The returned contract currently overwrites scaffold enums with factory enums; change the merge so scaffold and factory enums are combined before calling buildContractFromDsl by merging full.enums and built.enums into a single enums object (respecting scaffold keys and letting factory keys override where intended) instead of using ifDefined('enums', built.enums); update the return in the function that calls buildContractFromDsl to pass the merged enums (referencing buildContractFromDsl, ifDefined, definition.enums, built.enums and the MergeEnums<ScaffoldEnums, FactoryEnums> contract type) so runtime enums match the published MergeEnums type.packages/3-extensions/postgres/src/contract/define-contract.ts (1)
24-40:⚠️ Potential issue | 🟠 Major | ⚡ Quick winKeep the Postgres wrapper's enum generics split between scaffold and factory.
This wrapper collapses both enum sources into one
Enumsgeneric. Unlike the coredefineContractoverload inpackages/2-sql/2-authoring/contract-ts/src/contract-builder.ts(Lines 489-530), that meansdefineContract({ enums: { A } }, () => ({ enums: { B } }))cannot model the combined shape through the Postgres API. The extension surface ends up narrower than the builder it delegates to.Suggested fix
export function defineContract< const Types extends TypesConstraint = Record<never, never>, const Models extends ModelsConstraint = Record<never, never>, const ExtensionPacks extends | Record<string, ExtensionPackRef<'sql', string>> | undefined = undefined, - const Enums extends EnumsConstraint = Record<never, never>, + const ScaffoldEnums extends EnumsConstraint = Record<never, never>, + const FactoryEnums extends EnumsConstraint = Record<never, never>, >( - scaffold: PostgresScaffold<ExtensionPacks, Enums>, + scaffold: PostgresScaffold<ExtensionPacks, ScaffoldEnums>, factory: (helpers: ComposedAuthoringHelpers<SqlFamily, PostgresPack, ExtensionPacks>) => { readonly types?: Types; readonly models?: Models; - readonly enums?: Enums; + readonly enums?: FactoryEnums; }, -): PostgresResult<Types, Models, ExtensionPacks, Enums>; +): PostgresResult< + Types, + Models, + ExtensionPacks, + MergeEnums<ScaffoldEnums, FactoryEnums> +>;Also applies to: 84-98
🤖 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/3-extensions/postgres/src/contract/define-contract.ts` around lines 24 - 40, The Postgres wrapper collapses scaffold and factory enums into one Enums generic; update type PostgresResult to accept two enum generics (e.g. EnumsScaffold and EnumsFactory) and pass them through to buildBoundContract so both the scaffold-provided enums and the factory-provided enums are preserved. Concretely: replace the single Enums generic with separate EnumsScaffold and EnumsFactory generics, change the scaffold-side shape to use enums?: EnumsScaffold and ensure the factory-side shape (the buildBoundContract return/input) is typed to accept enums?: EnumsFactory so the wrapper delegates both enum sources to buildBoundContract (referencing the PostgresResult type and buildBoundContract, SqlFamily, and PostgresPack symbols).
🤖 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/2-authoring/contract-ts/src/contract-builder.ts`:
- Around line 435-439: The returned contract currently overwrites scaffold enums
with factory enums; change the merge so scaffold and factory enums are combined
before calling buildContractFromDsl by merging full.enums and built.enums into a
single enums object (respecting scaffold keys and letting factory keys override
where intended) instead of using ifDefined('enums', built.enums); update the
return in the function that calls buildContractFromDsl to pass the merged enums
(referencing buildContractFromDsl, ifDefined, definition.enums, built.enums and
the MergeEnums<ScaffoldEnums, FactoryEnums> contract type) so runtime enums
match the published MergeEnums type.
In `@packages/2-sql/2-authoring/contract-ts/src/contract-types.ts`:
- Around line 596-605: The accessor type EnumHandleAccessorType currently
restricts lookup inputs to string, which breaks int-backed enums; update the
method signatures on EnumHandleAccessorType (the has, nameOf, and ordinalOf
members) to accept both string and number (e.g., change parameter type from
string to string | number) so numeric enum values like 1 or 10 are allowed in
lookups while keeping return types the same.
In `@packages/3-extensions/postgres/src/contract/define-contract.ts`:
- Around line 24-40: The Postgres wrapper collapses scaffold and factory enums
into one Enums generic; update type PostgresResult to accept two enum generics
(e.g. EnumsScaffold and EnumsFactory) and pass them through to
buildBoundContract so both the scaffold-provided enums and the factory-provided
enums are preserved. Concretely: replace the single Enums generic with separate
EnumsScaffold and EnumsFactory generics, change the scaffold-side shape to use
enums?: EnumsScaffold and ensure the factory-side shape (the buildBoundContract
return/input) is typed to accept enums?: EnumsFactory so the wrapper delegates
both enum sources to buildBoundContract (referencing the PostgresResult type and
buildBoundContract, SqlFamily, and PostgresPack symbols).
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: 62792a6c-5926-4b5e-85c2-4e0ed53c2b8e
📒 Files selected for processing (10)
examples/prisma-next-demo/prisma/contract.tsexamples/prisma-next-demo/src/prisma-no-emit/priority-feed.tsexamples/prisma-next-demo/test/enum-surface.integration.test.tsexamples/prisma-next-demo/test/enum-surface.types.test-d.tspackages/2-sql/2-authoring/contract-ts/src/contract-builder.tspackages/2-sql/2-authoring/contract-ts/src/contract-types.tspackages/2-sql/2-authoring/contract-ts/test/enum-type.factory-form.test.tspackages/3-extensions/postgres/src/contract/define-contract.tspackages/3-targets/6-adapters/postgres/src/core/sql-renderer.tspackages/3-targets/6-adapters/postgres/test/migrations/order-by-enum.integration.test.ts
✅ Files skipped from review due to trivial changes (1)
- examples/prisma-next-demo/test/enum-surface.types.test-d.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/3-targets/6-adapters/postgres/src/core/sql-renderer.ts
…g|number (TML-2852) member<N, V> stays generic over any literal V; enumType constrains member values to the codec descriptors input type via CodecInput<C> (falls back to unknown when the descriptor carries no input phantom). EnumTypeHandle and the db.enums accessor (has/nameOf/ordinalOf) now accept the value union, so int-backed enums accept numeric values. Uniqueness now compares the lowered String(value) form so 1 and "1" collide as build-contract later normalizes them. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
buildBoundContract previously spread built.enums into the DSL input, overwriting any scaffold-authored definition.enums. The factory-form type advertises MergeEnums<ScaffoldEnums, FactoryEnums>, so a mixed contract silently lost the scaffold enums at runtime. Merge both sides instead. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…ntract (TML-2852)
The postgres wrapper collapsed scaffold + factory enums into one Enums generic,
so it could not model defineContract({ enums: { A } }, () => ({ enums: { B } }))
— narrower than the core defineContract it delegates to. Split into
ScaffoldEnums / FactoryEnums and return MergeEnums<ScaffoldEnums, FactoryEnums>,
mirroring the core overload. Exposes MergeEnums from the core builder for reuse.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
… demo test (TML-2852) Remove the redundant comment on contract.ts. The enum accessor probe with a non-member value now annotates the value union, since has() is typed to the codec value union after making member values codec-driven. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Sonnet 4.6 <[email protected]> Signed-off-by: Will Madden <[email protected]>
Mongo enums move from a non-goal to scope. The domain enum is framework-level and target-agnostic; Mongo realizes the value-set restriction as a $jsonSchema collection validator (validationLevel: strict) instead of a CHECK constraint, needing no value-set storage IR or migration-ops parallel. Mongo has no native enum and no prior PSL enum, so it skips the transitional keyword and the cutover entirely. Planned as one complete vertical slice (author -> enforce -> read, proven end-to-end against mongodb-memory-server) rather than split, since a non-vertical slice cannot be shown to work. Independent of the SQL track. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…aCodec encodeEnumValue and encodeDefaultLiteralValue both did the same codec-or-fallback dance. Merge them into one encodeViaCodec helper used for both the column-default and enum-lowering paths. Folds the former bare `as JsonValue` on the default path into the unified blindCast. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…ndation The enum-accessor builders and types are built purely from contract.domain.namespaces[ns].enum (framework ContractEnum), with nothing ORM-specific. Living in sql-orm-client forced the postgres and sqlite facade tests to wholesale-mock @prisma-next/sql-orm-client and pass buildNamespacedEnums through the mock to avoid a construction crash. Move the module to @prisma-next/contract (the 0-foundation layer both SQL facades and a future Mongo facade already depend on) under a new @prisma-next/contract/enum-accessor entrypoint, and relax the type constraint from Contract<SqlStorage> to Contract so it stays lane-neutral. Update the postgres/sqlite facades, the postgres read- surface type test, and the demo no-emit context to the new path; drop the now-unneeded buildNamespacedEnums pass-through from all four facade test mocks. The facade tests now run against the real, unmocked accessor. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
The no-emit context hand-wired stack/context/sql and hand-built the enums map with two blindCasts, behind a comment claiming "the no-emit path has no facade to hang db.enums on" — which is wrong: postgres() accepts a TypeScript-authored contract with deferred binding and exposes sql/enums/context/stack directly. Source those from the facade (db.sql.public, db.enums, db.context, db.stack), dropping both blindCasts, the misleading comment, and the custom rawCodecInferer stub (the facade uses the adapter inferer). createOrmClient still uses the orm() builder because the demo binds an externally-created runtime; everything else now comes from db. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
The merge pulled in three enum tests from main (PR #769) that construct runtimes through the deleted createRuntime / mocked-deserializer path. Port them to this branch's design: - postgres.test.ts: the two db.enums facade tests passed contractJson:{} with a mocked deserializeContract and asserted mocks.createRuntime. This branch's postgres.test.ts mocks only the pg boundary, so pass the real twoNamespaceDomain as contract and assert the pool never connects instead of inspecting a (deleted) createRuntime mock. - enum-surface.integration.test.ts: openRuntime built the runtime via instantiateExecutionStack + createRuntime; rebuild it through the postgres({ contract, url, extensions }).connect() facade, matching repositories.integration.test.ts. - runtime.ts: context.ts no longer exports validatedContract (took main's db-facade form), so pass the raw contract; the facade deserializes it. Signed-off-by: Will Madden <[email protected]> Co-Authored-By: Claude Opus 4.8 <[email protected]>
Mains enum work (#769) renders enum value unions into the field-type maps; our slice nests those maps by namespace id. Reconcile the enum type-tests to the nested shape: index ExtractFieldOutputTypes/InputTypes through the default namespace (public) or the fixtures __unbound__ coordinate, and pass the NsId coordinate to ContractToQC. Enum value unions still resolve per-namespace; no flat-map read reintroduced. Signed-off-by: Serhii Tatarintsev <[email protected]>
Mains enum work (#769) renders enum value unions into the field-type maps; our slice nests those maps by namespace id. Reconcile the enum type-tests to the nested shape: index ExtractFieldOutputTypes/InputTypes through the default namespace (public) or the fixtures __unbound__ coordinate, and pass the NsId coordinate to ContractToQC. Enum value unions still resolve per-namespace; no flat-map read reintroduced. Signed-off-by: Serhii Tatarintsev <[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]>
Mains enum work (#769) renders enum value unions into the field-type maps; our slice nests those maps by namespace id. Reconcile the enum type-tests to the nested shape: index ExtractFieldOutputTypes/InputTypes through the default namespace (public) or the fixtures __unbound__ coordinate, and pass the NsId coordinate to ContractToQC. Enum value unions still resolve per-namespace; no flat-map read reintroduced. Signed-off-by: Serhii Tatarintsev <[email protected]>
Mains enum work (#769) renders enum value unions into the field-type maps; our slice nests those maps by namespace id. Reconcile the enum type-tests to the nested shape: index ExtractFieldOutputTypes/InputTypes through the default namespace (public) or the fixtures __unbound__ coordinate, and pass the NsId coordinate to ContractToQC. Enum value unions still resolve per-namespace; no flat-map read reintroduced. Signed-off-by: Serhii Tatarintsev <[email protected]>
Mains enum work (#769) renders enum value unions into the field-type maps; our slice nests those maps by namespace id. Reconcile the enum type-tests to the nested shape: index ExtractFieldOutputTypes/InputTypes through the default namespace (public) or the fixtures __unbound__ coordinate, and pass the NsId coordinate to ContractToQC. Enum value unions still resolve per-namespace; no flat-map read reintroduced. Signed-off-by: Serhii Tatarintsev <[email protected]>
Mains enum work (#769) renders enum value unions into the field-type maps; our slice nests those maps by namespace id. Reconcile the enum type-tests to the nested shape: index ExtractFieldOutputTypes/InputTypes through the default namespace (public) or the fixtures __unbound__ coordinate, and pass the NsId coordinate to ContractToQC. Enum value unions still resolve per-namespace; no flat-map read reintroduced. Signed-off-by: Serhii Tatarintsev <[email protected]>
Mains enum work (#769) renders enum value unions into the field-type maps; our slice nests those maps by namespace id. Reconcile the enum type-tests to the nested shape: index ExtractFieldOutputTypes/InputTypes through the default namespace (public) or the fixtures __unbound__ coordinate, and pass the NsId coordinate to ContractToQC. Enum value unions still resolve per-namespace; no flat-map read reintroduced. Signed-off-by: Serhii Tatarintsev <[email protected]>
…havior; cover no-emit enum read F01: the TML-2886 entries in both 0.13-to-0.14/instructions.md files described the U3 behavior (enum field's FieldOutputTypes/FieldInputTypes entry "becomes its plain codec channel"), which U6 reverted. Rewrite both to describe what actually ships: the emitter renders the enum entry as a ref-following type expression that indexes the emitted domain enum block, which STILL resolves to the literal value union — FieldOutputTypes[ns][Model][enumField] stays 'low'|'high'|'urgent', not codec output. The source moved to the ref; the observable type is unchanged. The "no API/SPI change, observable types unchanged, no consumer action — incidental" conclusion is kept (correct, and why it stays an incidental declaration). F02: the no-emit baked-map fallback's reason-for-existing is already covered. examples/prisma-next-demo/test/enum-surface.types.test-d.ts (committed, from #769) asserts a no-emit (typeof contract) enum FIELD read through the query-builder select — sql.post.select('id','priority') yields Row['priority'] === 'low'|'high'|'urgent' and .not string — plus the no-emit write. That exercises the no-emit query lane (the tier the baked-map fallback backs), so no new test was added. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
## Linked issue n/a — umbrella tracker maintenance for the Supabase integration (`projects/supabase-integration/`). Adds the enums-as-domain-concept framework project to the tracked list. ## At a glance Enums are now a tracked part of the Supabase integration — they're central to it: Supabase's `auth.*` schema declares Postgres enum types and app schemas use enums heavily. New status-table row: ```md | enums-as-domain-concept | Enum as a domain-plane name→value valueSet restriction on the column's codec (not native CREATE TYPE); Postgres = value-set + check constraint, Mongo = $jsonSchema; typed reads + db.enums + declaration-order ORDER BY | 🚧 In progress (separate Terminal project) — substrate/enforcement/read-surface landed; PSL authoring, defaults, cutover, Mongo remain | ``` ## Decision Doc-only. Add `enums-as-domain-concept` to the umbrella tracker. It is **not** one of the original six constituents — it's a separate Terminal Linear project — so it gets the same treatment the README already gives the PSL-block substrate: a clearly-marked adopted framework project the integration depends on, with a note explaining the relevance rather than a claim that it was always in scope. Why it belongs in the list: faithfully modelling enum-typed columns in the Supabase contract (`auth.*` uses Postgres enums) and giving Supabase apps first-class enums both depend on it. It's not a hard blocker for the minimal walking skeleton, but it's required for the v0.1 enum story. ## What changed - **Status table** — new `enums-as-domain-concept` row: substrate (TML-2850) + Postgres enforcement (TML-2851) + read surface (TML-2852, prisma#769) landed; PSL authoring (TML-2882), member defaults (TML-2855), native-enum cutover (TML-2853), and the Mongo vertical (TML-2884) remain. - **Note below the table** — explains the Supabase relevance and flags the design choice that the Postgres realization is a text column + value-set + check constraint, **not** a native `CREATE TYPE … AS ENUM`. - **Dependency graph** — `enums` node added; `foundation --> enums` and a dashed `enums -.-> ext` ("enum-typed columns") edge. - Bumped the status-pass date to 2026-06-11. ## Reviewer notes - Pure docs; no source or behaviour change. - `enums-as-domain-concept` has its own Linear project and its own spec/plan under `projects/enums-as-domain-concept/` — this PR only references it from the umbrella, it doesn't move or change it. - The dashed graph edge mirrors the "adopted, not a hard blocker for the minimal skeleton" framing in the prose. ## Testing performed n/a — documentation only. ## Skill update n/a — internal planning docs only; no user-facing surface change. ## Checklist - [x] All commits are signed off (`git commit -s`). - [x] I read CONTRIBUTING.md and the change is scoped to one logical concern. - [x] Tests are updated (n/a — doc-only). - [ ] The PR title is in `TML-NNNN: <title>` form — n/a: umbrella tracker maintenance with no single Linear ticket. - [x] The **Skill update** section is filled in (n/a — internal only). Signed-off-by: Will Madden <[email protected]> Co-authored-by: Will Madden <[email protected]> Co-authored-by: Claude Opus 4.8 <[email protected]>
At a glance
In the demo's own contract,
Postcarries aPriorityenum — and the column is typed as its value union everywhere you touch it:This runs end-to-end against PGlite in
examples/prisma-next-demo— typed read,db.enums.<ns>, declaration-orderORDER BY, and the slice-2CHECKrejecting out-of-union writes.What this decides
An enum becomes a first-class application concept: its value union flows into the static read/write types of both query lanes,
db.enums.<ns>.<Name>exposes it at runtime, andORDER BYon an enum column sorts by declaration order. It works for text and int-backed enums and in both authoring forms (definition and factorydefineContract). Built on the merged substrate (slice 1) and check-constraint enforcement (slice 2), and lands additively — PSLenumstays native until the cutover, so onlyenumType-authored contracts exercise it.How it builds up
valueSetto the value union, on both paths: the authoredDefinition(no-emit) and the emittedcontract.d.ts— the emitter resolves a field'svalueSetref to the enum's member-value union, codec-agnostically (text and int). Both lanes inherit it through the field-output typemap; non-enum fields are unchanged.db.enums.<ns>.<Name>(R6) — a runtime, literal-typed accessor (.values/.members.X/.has/.nameOf/.ordinalOf) built from that namespace's domain enums. Enums are lane-agnostic contract metadata, sodb.enumslives on thedbfacade alongsidetransaction/prepare/raw/context(decided with the query team) — a namespace-keyed map projected per target exactly likedb.sql/db.orm. It matches the IR (domain.namespaces[ns].enum) and lets the same enum name in two namespaces resolve independently. Unbound-namespace targets (sqlite/mongo) getdb.enums.<Name>via the existing per-facade projection. Because enums sit on the facade rather than adjacent to models, no reserved-name guard is needed — a model namedenumsno longer collides.ORDER BY(R8, Postgres) — rendersarray_position(ARRAY[…]::text[], col)over the value-set's ordered values.enumskey threaded through the factory overload, mirroring the definition form), not only the definition form.Scope
Additive / dark. PSL
enumkeeps lowering to native (the repoint is the cutover, TML-2853); member defaults are TML-2855; non-PostgresORDER BY(MySQLFIELD(...)/ SQLiteCASE) is future. Existing fixtures are byte-identical apart from the demo.CI note
The repo-wide
pnpm typecheckis red on inheritedCannot find modulesubpath errors (/contract-builder,/migration,/adapter,/aggregate,/constants) that reproduce on cleanorigin/main— a separate main-health issue, not introduced here.Alternatives considered
Definition— rejected: emission widens the value-set tostring[], erasing the literals.valueSetrestriction layered on top.orderByDeclarationOrder()API — rejected: ordering an enum column by declaration order should just work; the renderer handles it implicitly.🤖 Generated with Claude Code
Summary by CodeRabbit
Release Notes
'user' | 'admin'instead of genericstring) in both read and write operations, with compile-time type checking.db.enums.<namespace>.<EnumName>(lane-agnostic namespace-keyed map).