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

TML-2850: introduce domain enums + storage value-sets (additive groundwork) - #750

Merged
wmadden merged 14 commits into
mainfrom
tml-2850-enum-contract-substrate
Jun 7, 2026
Merged

wmadden merged 14 commits into
mainfrom
tml-2850-enum-contract-substrate

Conversation

@wmadden-electric

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

Copy link
Copy Markdown
Contributor

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:

const Role = enumType('Role', text, member('User', 'user'), member('Admin', 'admin'));

model('User', {
  fields: { role: field.namedType(Role) },
});

Role carries its values as a precise type — Role.values is readonly ['user', 'admin'], not string[] — and lowers into the contract on both planes:

// domain plane — the application concept
"enum": { "Role": { "codecId": "pg/text@1", "members": [
  { "name": "User", "value": "user" }, { "name": "Admin", "value": "admin" }
] } }
"models": { "User": { "fields": {
  "role": { "nullable": false, "codecId": "pg/text@1",
            "valueSet": { "kind": "enum", "namespaceId": "public", "name": "Role" } } } } }

// storage plane — the physical permitted-value set
"valueSet": { "Role": { "values": ["user", "admin"] } }
"tables": { "users": { "columns": {
  "role": { "nativeType": "text", "codecId": "pg/text@1",
            "valueSet": { "kind": "value-set", "namespaceId": "public", "name": "Role" } } } } }

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 valueSet reference when it is enum-restricted. Storage realizes the restriction as a named value-set (and, in a later slice, a check constraint) — never a native CREATE TYPE ... AS ENUM.

Full rationale: projects/enums-as-domain-concept/{spec,design-notes}.md.

How the shape is built, piece by piece

  • One reference type. Both valueSet pointers above are the same coordinate — { kind, namespaceId, name, spaceId? } — matching the existing ForeignKeyReference carrier (presence of spaceId is the cross-space discriminator; no tag field). It lives in the foundation package so both planes can use it; kind says which plane the referent is in ('enum' in domain, 'value-set' in storage).
  • Two new entities. ContractEnum (domain: a codec + ordered name→value members) and StorageValueSet (storage: the ordered permitted values, a frozen IR node). The value-set becomes a first-class entity automatically — the coordinate walker iterates a namespace's entries structurally, so it picks up the new slot with zero walker change.
  • The authoring API. enumType / member build an ordered name→value map whose literal value tuple survives end to end (the type-test expectTypeOf(Role.values).toEqualTypeOf<readonly ['user','admin']>() is the guarantee). field.namedType(Role) lowers to the domain enum entry, the storage value-set entry, and the valueSet refs on the field and column — pointing at the value-set, not reusing the native typeRef mechanism (pinned by a test).
  • Persistence. The value-set hydrates from JSON in the SQL-family serializer (coexisting with the untouched native-enum hydration); arktype validators accept the new shape and reject malformed input; a round-trip test exercises the real serializer on both planes.

Landed dark — and why

enum is 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: PSL enum, the existing authoring, and the native Postgres enum path are all untouched, and the new shape is reachable only through the enumType API above. The cutover — repointing enum to 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:check regenerates the entire repo's fixtures byte-identically (zero diff, zero migration drift), and pnpm lint:casts is net-negative. This PR changes no emitted output.

Scope — deliberately out (later slices)

  • Server-side enforcement (the check constraint), member defaults, migration/verification → TML-2851.
  • Typed reads/writes, db.enums, declaration-order ORDER BY → TML-2852.
  • The cutover: repoint PSL enum + delete the native machinery → TML-2853.

Alternatives considered

  • Keep the enum a native Postgres type. Postgres-only; you cannot remove a value without a full type rebuild; ALTER TYPE ... ADD VALUE cannot run in a transaction; text-only. A value-set + check constraint makes add/remove/rename ordinary ALTER TABLEs on every SQL target. (Native can return later as an alternate storage realization under the same domain enum.)
  • Model the field type as 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.
  • A named enum entity in the storage plane. Rejected: with native types gone there is no physical object to name; the bare value-set states permitted physical values and nothing else, which is a legitimately-storage concept.
  • Cut over directly instead of landing dark. Rejected: flipping enum to 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

    • Added first-class enum support across contracts: authoring, domain namespace enums, and corresponding storage value-sets; contract builder and serialization now carry enum/value-set metadata end-to-end.
    • Fields and storage columns can reference value-sets for constrained values.
  • Tests

    • Added extensive tests for enum authoring, lowering, serialization round-trips, validators, and value-set behavior.

wmadden and others added 9 commits June 7, 2026 12:06
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]>
@wmadden-electric
wmadden-electric requested a review from a team as a code owner June 7, 2026 11:32
@coderabbitai

coderabbitai Bot commented Jun 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: 2a0ad5c5-bf6a-44b4-8855-1a2554e2e2af

📥 Commits

Reviewing files that changed from the base of the PR and between f90d5a8 and 76dc7f3.

📒 Files selected for processing (4)
  • .gitignore
  • packages/2-sql/2-authoring/contract-ts/src/build-contract.ts
  • packages/2-sql/2-authoring/contract-ts/src/enum-type.ts
  • packages/2-sql/2-authoring/contract-ts/test/enum-type.authoring.test.ts
✅ Files skipped from review due to trivial changes (1)
  • .gitignore
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/2-sql/2-authoring/contract-ts/test/enum-type.authoring.test.ts
  • packages/2-sql/2-authoring/contract-ts/src/enum-type.ts
  • packages/2-sql/2-authoring/contract-ts/src/build-contract.ts

📝 Walkthrough

Walkthrough

Adds 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.

Changes

Enum Type Support

Layer / File(s) Summary
Foundation domain types and ValueSetRef interface
packages/1-framework/0-foundation/contract/src/value-set-ref.ts, packages/1-framework/0-foundation/contract/src/domain-types.ts, packages/1-framework/0-foundation/contract/src/domain-envelope.ts, packages/1-framework/0-foundation/contract/src/exports/types.ts
Introduces ValueSetRef to reference domain enums or storage value-sets; adds ContractEnum; extends ContractField and ApplicationDomainNamespace to carry enum/value-set information and re-exports new types.
SQL IR StorageValueSet and column/namespace slots
packages/2-sql/1-core/contract/src/ir/storage-value-set.ts, packages/2-sql/1-core/contract/src/ir/storage-column.ts, packages/2-sql/1-core/contract/src/ir/sql-storage.ts, packages/2-sql/1-core/contract/src/types.ts, packages/2-sql/1-core/contract/src/exports/types.ts
Adds StorageValueSet IR node and input shape; extends StorageColumn to optionally reference a ValueSetRef; extends SqlNamespaceTablesInput/SqlNamespace types to include valueSet maps and re-exports storage value-set types.
SQL namespace hydration and validation
packages/2-sql/1-core/contract/src/ir/build-sql-namespace.ts, packages/2-sql/1-core/contract/src/validators.ts, packages/2-sql/9-family/src/core/ir/sql-contract-serializer-base.ts
Detect unbound/bound namespaces considering valueSet presence; convert namespace valueSet entries into StorageValueSet instances during construction/serialization; add ValueSetRefSchema, StorageValueSetSchema, and ContractEnumSchema and wire them into per-namespace and model-field validation.
Authoring enum system
packages/2-sql/2-authoring/contract-ts/src/enum-type.ts, packages/2-sql/2-authoring/contract-ts/src/exports/contract-builder.ts
Introduce EnumMember, member() helper, branded EnumTypeHandle, and enumType() factory preserving literal typing, validating uniqueness, and exposing runtime helpers; export helpers and types for consumers.
Authoring type contracts and DSL
packages/2-sql/2-authoring/contract-ts/src/contract-builder.ts, packages/2-sql/2-authoring/contract-ts/src/contract-definition.ts, packages/2-sql/2-authoring/contract-ts/src/contract-dsl.ts, packages/2-sql/2-authoring/contract-ts/src/exports/contract-builder.ts
Extend contract input/definition/scaffold types with optional enums map; add enumTypeHandle to FieldNode; update namedTypeField to accept EnumTypeHandle and route it through scalar field lowering; re-export enum helpers.
Enum wiring in contract building and lowering
packages/2-sql/2-authoring/contract-ts/src/build-contract.ts, packages/2-sql/2-authoring/contract-ts/src/contract-lowering.ts
When lowering authored fields, derive enum handles and build ValueSetRef for storage and domain, pass refs into storage/domain builders to emit valueSet constraints, build per-namespace enum/value-set registries, and include enum slices in domain namespaces; lowering recognizes enum handles and attaches metadata to field nodes.
Family serialization and comprehensive testing
packages/2-sql/9-family/src/core/ir/sql-contract-serializer-base.ts, packages/2-sql/1-core/contract/test/storage-value-set.test.ts, packages/2-sql/2-authoring/contract-ts/test/enum-type.authoring.test.ts, packages/2-sql/9-family/test/value-set-roundtrip.test.ts
Serializer hydrates optional namespace valueSet slots into StorageValueSet instances. Tests added/expanded for StorageValueSet immutability, enum-type authoring behavior and typing, contract authoring integration, and JSON round-trip + validation for enums/value-sets.
Misc: re-exports and workspace ignore
packages/2-sql/1-core/contract/src/exports/types.ts, packages/2-sql/1-core/contract/src/types.ts, .gitignore
Add small re-exports for StorageValueSet types and update .gitignore for workspace artifacts.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • prisma/prisma-next#552: Overlaps in serializer/namespace hydration changes; both touch namespace-slot processing in serializer.
  • prisma/prisma-next#630: Related changes to SQL namespace materialization and SqlBoundNamespace construction.

Suggested reviewers

  • aqrln

Poem

🐰 A rabbit hops with enum delight,
Names and values stored just right,
From authoring fields to SQL sets,
Frozen values and tests—no frets,
Hooray for enums, snug and bright!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 23.08% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the main change: introduction of domain enums and storage value-sets as additive groundwork, matching the PR's comprehensive scope across domain, storage, authoring, and serialization layers.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch tml-2850-enum-contract-substrate

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

❤️ Share

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

@pkg-pr-new

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

Copy link
Copy Markdown

Open in StackBlitz

@prisma-next/extension-author-tools

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

@prisma-next/mongo-runtime

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

@prisma-next/family-mongo

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

@prisma-next/sql-runtime

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

@prisma-next/family-sql

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

@prisma-next/extension-arktype-json

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

@prisma-next/middleware-cache

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

@prisma-next/mongo

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

@prisma-next/extension-paradedb

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

@prisma-next/extension-pgvector

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

@prisma-next/extension-postgis

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

@prisma-next/postgres

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

@prisma-next/sql-orm-client

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

@prisma-next/sqlite

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

@prisma-next/extension-supabase

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

@prisma-next/target-mongo

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

@prisma-next/adapter-mongo

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

@prisma-next/driver-mongo

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

@prisma-next/contract

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

@prisma-next/utils

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

@prisma-next/config

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

@prisma-next/errors

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

@prisma-next/framework-components

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

@prisma-next/operations

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

@prisma-next/ts-render

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

@prisma-next/contract-authoring

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

@prisma-next/ids

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

@prisma-next/psl-parser

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

@prisma-next/psl-printer

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

@prisma-next/cli

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

@prisma-next/cli-telemetry

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

@prisma-next/emitter

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

@prisma-next/migration-tools

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

prisma-next

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

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

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

@prisma-next/mongo-codec

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

@prisma-next/mongo-contract

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

@prisma-next/mongo-value

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

@prisma-next/mongo-contract-psl

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

@prisma-next/mongo-contract-ts

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

@prisma-next/mongo-emitter

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

@prisma-next/mongo-schema-ir

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

@prisma-next/mongo-query-ast

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

@prisma-next/mongo-orm

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

@prisma-next/mongo-query-builder

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

@prisma-next/mongo-lowering

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

@prisma-next/mongo-wire

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

@prisma-next/sql-contract

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

@prisma-next/sql-errors

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

@prisma-next/sql-operations

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

@prisma-next/sql-schema-ir

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

@prisma-next/sql-contract-psl

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

@prisma-next/sql-contract-ts

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

@prisma-next/sql-contract-emitter

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

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

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

@prisma-next/sql-relational-core

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

@prisma-next/sql-builder

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

@prisma-next/target-postgres

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

@prisma-next/target-sqlite

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

@prisma-next/adapter-postgres

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

@prisma-next/adapter-sqlite

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

@prisma-next/driver-postgres

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

@prisma-next/driver-sqlite

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

commit: c89717a

@github-actions

github-actions Bot commented Jun 7, 2026 •

Copy link
Copy Markdown

size-limit report 📦

Path Size
postgres / no-emit 146.13 KB (+0.48% 🔺)
postgres / emit 117.32 KB (+0.18% 🔺)
mongo / no-emit 76.09 KB (0%)
mongo / emit 70.95 KB (0%)
cf-worker / no-emit 175.91 KB (+0.37% 🔺)
cf-worker / emit 143.91 KB (+0.16% 🔺)

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
packages/2-sql/1-core/contract/src/validators.ts (1)

89-94: ⚡ Quick win

Consider extracting the duplicated ValueSetRef schema.

The valueSet schema is inlined at lines 89-94 within StorageColumnSchema and then defined separately as ValueSetRefSchema at lines 389-394. This duplication means changes to the ValueSetRef shape must be applied in two places.

♻️ Refactor to eliminate duplication

Define ValueSetRefSchema before StorageColumnSchema and 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

📥 Commits

Reviewing files that changed from the base of the PR and between 90574dc and 75ed70e.

⛔ Files ignored due to path filters (5)
  • projects/enums-as-domain-concept/learnings.md is excluded by !projects/**
  • projects/enums-as-domain-concept/plan.md is excluded by !projects/**
  • projects/enums-as-domain-concept/reviews/code-review.md is excluded by !projects/**
  • projects/enums-as-domain-concept/slices/enum-contract-substrate/plan.md is excluded by !projects/**
  • projects/enums-as-domain-concept/slices/enum-contract-substrate/spec.md is excluded by !projects/**
📒 Files selected for processing (24)
  • packages/1-framework/0-foundation/contract/src/domain-envelope.ts
  • packages/1-framework/0-foundation/contract/src/domain-types.ts
  • packages/1-framework/0-foundation/contract/src/exports/types.ts
  • packages/1-framework/0-foundation/contract/src/value-set-ref.ts
  • packages/1-framework/0-foundation/contract/test/domain-enum-slot.test.ts
  • packages/1-framework/0-foundation/contract/test/value-set-ref.test.ts
  • packages/2-sql/1-core/contract/src/exports/types.ts
  • packages/2-sql/1-core/contract/src/ir/build-sql-namespace.ts
  • packages/2-sql/1-core/contract/src/ir/sql-storage.ts
  • packages/2-sql/1-core/contract/src/ir/storage-column.ts
  • packages/2-sql/1-core/contract/src/ir/storage-value-set.ts
  • packages/2-sql/1-core/contract/src/types.ts
  • packages/2-sql/1-core/contract/src/validators.ts
  • packages/2-sql/1-core/contract/test/storage-value-set.test.ts
  • packages/2-sql/2-authoring/contract-ts/src/build-contract.ts
  • packages/2-sql/2-authoring/contract-ts/src/contract-builder.ts
  • packages/2-sql/2-authoring/contract-ts/src/contract-definition.ts
  • packages/2-sql/2-authoring/contract-ts/src/contract-dsl.ts
  • packages/2-sql/2-authoring/contract-ts/src/contract-lowering.ts
  • packages/2-sql/2-authoring/contract-ts/src/enum-type.ts
  • packages/2-sql/2-authoring/contract-ts/src/exports/contract-builder.ts
  • packages/2-sql/2-authoring/contract-ts/test/enum-type.authoring.test.ts
  • packages/2-sql/9-family/src/core/ir/sql-contract-serializer-base.ts
  • packages/2-sql/9-family/test/value-set-roundtrip.test.ts

@wmadden-electric wmadden-electric changed the title TML-2850: enum contract substrate — domain enums + storage value-sets (additive) TML-2850: introduce domain enums + storage value-sets (additive groundwork) Jun 7, 2026
…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]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 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

📥 Commits

Reviewing files that changed from the base of the PR and between 75ed70e and f90d5a8.

📒 Files selected for processing (6)
  • packages/1-framework/0-foundation/contract/src/value-set-ref.ts
  • 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
  • packages/2-sql/2-authoring/contract-ts/test/enum-type.authoring.test.ts
  • packages/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

wmadden and others added 2 commits June 7, 2026 14:48
…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 wmadden left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I'm satisfied. Address the CodeRabbit comments and merge

wmadden and others added 2 commits June 7, 2026 15:14
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]>
@wmadden
wmadden merged commit b661ee1 into main Jun 7, 2026
20 checks passed
@wmadden
wmadden deleted the tml-2850-enum-contract-substrate branch June 7, 2026 14:25
paulwer pushed a commit to paulwer/prisma-next that referenced this pull request Jun 11, 2026
…risma#805)

## Linked issue

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

## At a glance

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

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

model Post {
  priority Priority
}
```

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

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

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

## Decision

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

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

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

## Reviewer notes

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

## How it fits together

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

## Behavior changes & evidence

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

## Testing performed

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

## Skill update

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

## Follow-ups

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

## Alternatives considered

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

## Checklist

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


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

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

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

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

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

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

---------

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants