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

TML-2855: enum field defaults by member — @default(Low) renders DEFAULT 'low' - #808

Merged
wmadden-electric merged 7 commits into
mainfrom
tml-2855-slice-enum-member-defaults-defaultadmin-renders-default
Jun 11, 2026
Merged

wmadden-electric merged 7 commits into
mainfrom
tml-2855-slice-enum-member-defaults-defaultadmin-renders-default

Conversation

@wmadden-electric

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

Copy link
Copy Markdown
Contributor

Linked issue

Refs TML-2855.
Was stacked on #805 (TML-2882) — now merged; this PR targets main directly (rebased, four commits).
With TML-2885, the last parity prerequisite before the cutover (TML-2853).

At a glance

An enum field declares its default by naming a member, on both authoring surfaces, and it lands as an ordinary literal:

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

model Post {
  priority Priority @default(Low)   // names a member — not the raw string "low"
}
field.namedType(Priority).default(Priority.members.Low)   // members only — .default('lwo') is a compile error
priority text NOT NULL DEFAULT 'low'

Before this PR, .default() on an enum-typed field accepted any literal, and PSL @default had no member awareness.

Decision

Member-to-literal resolution happens at lowering, per authoring surface — there is no new ColumnDefault variant and no machinery below the lowering. The storage column carries the resolved literal ({ "kind": "literal", "value": "low" }), so the storage plane stays plannable in isolation per the directional invariant settled on #805 (domain may reference storage; storage may never reference domain). The enumMember variant the original ticket described predates that correction and was never shipped; this PR supersedes it (see the ticket's 2026-06-10 respec comment and project spec §9).

Reviewer notes

  • The negative type-tests are the heart of the TS surface: EnumScalarFieldBuilder.default() narrows to the handle's member value union (Handle['values'][number]); the package typecheck passes with the @ts-expect-error directives present, so each rejected literal genuinely errors. defaultSql is a type error (and runtime throw) on enum builders.
  • A latent stale artifact from the base branch is re-emitted here: commit fe9ce0f53 on the base branch canonicalized empty typeParams out of emitted contracts, but the demo's copied pgvector space was never re-emitted and still carried the old shape + hash. Running the migration tooling surfaced it; this PR re-emits it (byte-identical to the pgvector package's own contract). Tree-wide there are zero "typeParams":{} survivors now.
  • Known follow-up (not exercised by any current usage): the member-only .default() narrowing is lost if .nullable()/.id() is chained before it (base builder methods return the base type). Recorded in the review ledger; closes when nullable-with-default enum fields are needed.
  • The spec's "At a glance" shows "default": "low" as shorthand; the persisted shape is the existing object form ({"kind":"literal","value":"low"}), identical to every other literal default on the wire (e.g. task.status).

How it fits together

  1. TS DSL (contract-dsl.ts): the EnumTypeHandle overload of namedTypeField returns an EnumScalarFieldBuilder whose .default() accepts only the member value union and lowers to the existing literal default.
  2. PSL (psl-field-resolution.ts): when a field's type resolves to an enum2, @default(<identifier>) resolves the member name to its value (literal default); non-member identifiers, quoted raw values, and function defaults are span-accurate diagnostics. Non-enum and native-enum @default lowering is untouched.
  3. Nothing below the lowering changes — validator, planner, buildColumnDefaultSql, verification all see an ordinary literal default.
  4. Demo (examples/prisma-next-demo): @default(Low) in the PSL schema (mirrored in the TS no-emit contract), re-emitted artifacts, migration 20260610T2216_set_priority_default (a single setDefault op), and an integration test inserting a post without priority and reading back 'low' — including the type-level proof that the insert payload's priority became optional.

Behavior changes & evidence

Testing performed

  • pnpm test:packages — 800 files / 10,352 tests green on final HEAD
  • Full pnpm typecheck green for all packages this diff can reach (recurring stale-dist environment artifacts in unrelated packages adjudicated in review, same shape as on the base branch)
  • pnpm fixtures:check — clean outside the demo's deliberate changes
  • pnpm lint:deps — clean

Skill update

n/a — the @default(member) surface rides the transitional enum2 keyword, which is retired at the cutover; user-facing docs land with the cutover rename (same policy as #805).

Follow-ups

  • Builder-chaining: preserve member-only .default() narrowing through .nullable()/.id() chains when nullable-with-default enum fields land.
  • TML-2885 — emit-typed db.enums (the other cutover prerequisite).

Alternatives considered

  • An enumMember ColumnDefault variant recording the member in storage (the original ticket design). Rejected by the 2026-06-10 directional-invariant settlement: it is a storage → domain reference, and storage must be plannable in isolation. The resolved literal carries everything DDL needs; the authored source names the member, so intent is recoverable by re-emit.
  • Default by raw value (@default("low")). Rejected (per the ticket): severs the domain link, can't be membership-checked at authoring time; it is an explicit diagnostic now.
  • Recording member intent on the domain field in this slice. Deferred — additive later if introspection/diffing wants it; no observable behavior needs it today.

Checklist

  • All commits are signed off (git commit -s) per the DCO. The DCO status check will block merge if any commit is missing a Signed-off-by: trailer.
  • I read CONTRIBUTING.md and the change is scoped to one logical concern.
  • Tests are updated (or n/a if the change is doc-only / refactor with no behavioural delta).
  • 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.
  • The Skill update section above is filled in (or stated n/a — internal only).

Summary by CodeRabbit

  • New Features

    • Enum field defaults: You can now specify default values for enum-typed fields using @default(EnumMember) syntax. This allows enum fields to be optional on insert operations, with the database automatically applying the specified default value when omitted.
  • Chores

    • Added upgrade guidance and migration path for enum field defaults support in v0.14.

@wmadden-electric
wmadden-electric requested a review from a team as a code owner June 10, 2026 22:32
@coderabbitai

coderabbitai Bot commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR implements enum member default lowering across PSL and TypeScript contract authoring, demonstrates the feature with a Priority enum default migration in the demo app, and updates contract artifacts, runtime code, and tests to support enum-backed field defaults.

Changes

Enum2 Member Defaults and Priority Demo

Layer / File(s) Summary
Priority default migration structure and generated contracts
examples/prisma-next-demo/migrations/app/20260610T2216_set_priority_default/*
Defines the migration schema (contract.prisma with Post, Task, User, and Priority enum), migration class (migration.ts) that sets post.priority to 'low', operation spec (ops.json) with SQL ALTER TABLE steps, and fully generated start/end contract artifacts in JSON and TypeScript declaration formats encoding the Postgres schema, domain models, and enum defaults.
Demo runtime implementation, CLI, and tests
examples/prisma-next-demo/src/main*.ts, examples/prisma-next-demo/src/queries/enum-default-demo*.ts, examples/prisma-next-demo/test/enum-surface.integration.test.ts, examples/prisma-next-demo/src/prisma/contract.*, examples/prisma-next-demo/prisma/contract.ts
Updates the demo app's contract.ts to include Post.priority with default Low, adds runtime query handlers that insert/read/verify enum defaults, wires enum-default-demo CLI command in both main and no-emit entrypoints, updates generated contract typing/JSON with the priority column default, and adds integration test asserting post.priority reads as 'low' when omitted on insert.
PSL enum2 field default lowering and interpreter
packages/2-sql/2-authoring/contract-psl/src/interpreter.ts, packages/2-sql/2-authoring/contract-psl/src/psl-field-resolution.ts, packages/2-sql/2-authoring/contract-psl/test/interpreter.enum2.test.ts
Threads enum2 handles through the interpreter into field resolution, implements new enum2-specific default lowering that validates enum member names (rejecting quoted literals and function calls), emits member-unknown and syntax diagnostics, and produces literal column defaults; adds PSL↔TS parity test and comprehensive diagnostic/lowering test cases for both string and int enum backings.
TypeScript contract DSL enum defaults
packages/2-sql/2-authoring/contract-ts/src/contract-dsl.ts, packages/2-sql/2-authoring/contract-ts/test/enum-type.member-defaults.test.ts
Introduces EnumScalarFieldBuilder subclass that overrides .default(memberValue) to accept only enum member values, disallows .defaultSql() with a runtime throw, updates field.namedType(enumHandle) to return the enum builder instead of a generic scalar builder, and adds tests validating compile-time member-only type constraints and runtime literal default output shape.
Upgrade documentation
skills/upgrade/prisma-next-upgrade/upgrades/0.13-to-0.14/instructions.md
Documents TML-2855 enum member default feature as additive, noting that PSL @default(EnumMember) and TS .default(memberValue) now lower to literal defaults, the demo priority field gains the default, and the migration fixture is emitted; states no consumer action required until cutover docs.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • prisma/prisma-next#805: Introduces the Priority enum and post.priority field mapping in the demo; this PR's migration adds the default value of Low to that field.

Suggested reviewers

  • aqrln

Poem

🐰 Enums now remember what they meant to be—
A Priority.Low whispers its default decree,
From schema to storage, the whole journey flows,
Member values settle where the column grows,
Type-safe defaults that the compiler knows! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 22.22% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically describes the main change: implementing enum field defaults that render to DEFAULT literals in SQL, exemplified by @default(Low) rendering to DEFAULT 'low'.
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-2855-slice-enum-member-defaults-defaultadmin-renders-default

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 10, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@prisma-next/extension-author-tools

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

@prisma-next/mongo-runtime

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

@prisma-next/family-mongo

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

@prisma-next/sql-runtime

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

@prisma-next/family-sql

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

@prisma-next/extension-arktype-json

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

@prisma-next/middleware-cache

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

@prisma-next/mongo

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

@prisma-next/extension-paradedb

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

@prisma-next/extension-pgvector

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

@prisma-next/extension-postgis

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

@prisma-next/postgres

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

@prisma-next/sql-orm-client

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

@prisma-next/sqlite

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

@prisma-next/extension-supabase

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

@prisma-next/target-mongo

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

@prisma-next/adapter-mongo

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

@prisma-next/driver-mongo

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

@prisma-next/contract

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

@prisma-next/utils

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

@prisma-next/config

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

@prisma-next/errors

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

@prisma-next/framework-components

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

@prisma-next/operations

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

@prisma-next/ts-render

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

@prisma-next/contract-authoring

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

@prisma-next/ids

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

@prisma-next/psl-parser

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

@prisma-next/psl-printer

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

@prisma-next/cli

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

@prisma-next/cli-telemetry

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

@prisma-next/emitter

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

@prisma-next/migration-tools

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

prisma-next

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

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

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

@prisma-next/mongo-codec

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

@prisma-next/mongo-contract

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

@prisma-next/mongo-value

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

@prisma-next/mongo-contract-psl

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

@prisma-next/mongo-contract-ts

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

@prisma-next/mongo-emitter

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

@prisma-next/mongo-schema-ir

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

@prisma-next/mongo-query-ast

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

@prisma-next/mongo-orm

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

@prisma-next/mongo-query-builder

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

@prisma-next/mongo-lowering

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

@prisma-next/mongo-wire

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

@prisma-next/sql-contract

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

@prisma-next/sql-errors

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

@prisma-next/sql-operations

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

@prisma-next/sql-schema-ir

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

@prisma-next/sql-contract-psl

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

@prisma-next/sql-contract-ts

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

@prisma-next/sql-contract-emitter

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

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

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

@prisma-next/sql-relational-core

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

@prisma-next/sql-builder

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

@prisma-next/target-postgres

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

@prisma-next/target-sqlite

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

@prisma-next/adapter-postgres

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

@prisma-next/adapter-sqlite

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

@prisma-next/driver-postgres

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

@prisma-next/driver-sqlite

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

commit: fa11672

@github-actions

github-actions Bot commented Jun 10, 2026 •

Copy link
Copy Markdown

size-limit report 📦

Path Size
postgres / no-emit 153.92 KB (+0.06% 🔺)
postgres / emit 121.27 KB (0%)
mongo / no-emit 76.8 KB (0%)
mongo / emit 70.96 KB (0%)
cf-worker / no-emit 182.91 KB (+0.07% 🔺)
cf-worker / emit 147.02 KB (0%)

@wmadden-electric
wmadden-electric force-pushed the tml-2855-slice-enum-member-defaults-defaultadmin-renders-default branch from fc93a32 to 47e9d9c Compare June 10, 2026 22:59
Base automatically changed from tml-2882-slice-transitional-psl-enum2-block-author-the-new-enum to main June 11, 2026 09:14
@wmadden-electric
wmadden-electric force-pushed the tml-2855-slice-enum-member-defaults-defaultadmin-renders-default branch from 4f4fcb3 to 105e548 Compare June 11, 2026 09:15
wmadden and others added 4 commits June 11, 2026 11:17
TS DSL: `field.namedType(EnumHandle)` now returns `EnumScalarFieldBuilder`
whose `.default()` accepts only the handle's member value union
(`Values[number]`). A non-member literal is a compile-time error.
`defaultSql` is overridden to `never` on the enum builder (function defaults
on enum2 fields are not allowed). Lowering emits `{ kind: 'literal', value }`.

PSL: `@default(MemberName)` on an enum2 field resolves the bare identifier
against the enum's member names and lowers to the member's value as a literal
default. Non-member identifiers, quoted raw values, and function defaults each
emit a dedicated diagnostic (`PSL_ENUM2_UNKNOWN_DEFAULT_MEMBER` /
`PSL_ENUM2_DEFAULT_MUST_BE_MEMBER_NAME`). `enum2Handles` is threaded from
`buildModelNodeFromPsl` into `collectResolvedFields` via a new optional field
on `CollectResolvedFieldsInput`. Non-enum and native-enum `@default` lowering
is unchanged. The PSL↔TS parity test is extended with a defaulted field;
storageHash equality is asserted on both authoring paths.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Add @default(Low) to the demo's priority Priority field in both PSL and
TS no-emit contracts; re-emit contract.json / contract.d.ts (storage diff:
priority column gains "default":{"kind":"literal","value":"low"}, storageHash
recomputes to 372f890); create migration 20260610T2216_set_priority_default
with a single setDefault op (ALTER TABLE post ALTER COLUMN priority SET
DEFAULT 'low'); fix pre-existing pgvector contract-space hash drift (3b5e09f
→ 8ac1bfb, metadata-only change from tml-2882 emissions); add integration
test proving an insert omitting priority reads back 'low'.

Sweep: test:packages green (800 files / 10352 tests); demo typecheck clean;
fixtures:check zero-diff outside deliberate demo changes; lint:deps clean;
no new bare casts.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Member defaults via `@default(EnumType.Member)` are additive and opt-in.
Demo regeneration only. No consumer migration path needed; the cutover
carries user-facing docs.

Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
@wmadden-electric
wmadden-electric force-pushed the tml-2855-slice-enum-member-defaults-defaultadmin-renders-default branch from 105e548 to f469ed1 Compare June 11, 2026 09:17

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

Ensure this feature is demonstrated in example app code in both the emit and no-emit paths. Not just in tests. Otherwise looks good

wmadden added 2 commits June 11, 2026 11:56
Co-Authored-By: Will Madden <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Adds `enum-default-demo` to both main.ts (emitted contract) and
main-no-emit.ts (inline TS contract). Each command inserts a Post
without supplying `priority` — typed-optional because the contract
records @default(Low) / .default(Priority.members.Low) — reads the
row back, and confirms the database supplied 'low'. Cleanup runs at
the end of each demo.

Also updates the emitted contract.d.ts artifacts (src/prisma and
migrations) to include the typed enum block now generated by the
current emitter.

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

Copy link
Copy Markdown
Contributor Author

Done (03df382). Added enum-default-demo to both main.ts (emitted contract, @default(Low)) and main-no-emit.ts (inline TS contract, .default(Priority.members.Low)). Each command inserts a Post without priority, reads it back, and confirms the DB supplied 'low'. Demo tests in enum-surface.integration.test.ts exercise the same insert-without-priority path against a real PGlite DB (53/53 passing). pnpm fixtures:check clean.

The previous regeneration ran against a stale dist carrying the TML-2885
emitter, injecting the typed domain enum block this branch cannot produce.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
@wmadden-electric
wmadden-electric added this pull request to the merge queue Jun 11, 2026

@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: 3

🤖 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 `@examples/prisma-next-demo/src/queries/enum-default-demo-no-emit.ts`:
- Around line 12-48: Wrap the main demo flow in enumDefaultDemoNoEmit in a try {
... } finally { ... } so cleanup always runs: perform the inserts, select and
assertions inside the try block and move both delete calls (the
sql.post.delete() for demoPostId and sql.user.delete() for demoUserId) into the
finally block so runtime.execute(...) is invoked to remove demoPostId and
demoUserId even if an error occurs; keep existing checks (e.g., the row/null
check) inside the try.

In `@packages/2-sql/2-authoring/contract-psl/src/psl-field-resolution.ts`:
- Around line 417-438: The current lowering uses
enum2Handles?.get(field.typeName) which misses named-type aliases; update the
resolution so if enum2Handles.get(field.typeName) is undefined you resolve the
named type descriptor (namedTypeDescriptors?.get(field.typeName) or similar) to
find the underlying enum2 name/descriptor and then look up enum2Handles by that
underlying name before deciding between lowerEnum2DefaultForField and
lowerDefaultForField; keep the same call sites (lowerEnum2DefaultForField,
lowerDefaultForField) and pass the same parameters once you have the resolved
enumHandle so alias-typed fields like PriorityAlias will correctly use the enum2
path.

In `@skills/upgrade/prisma-next-upgrade/upgrades/0.13-to-0.14/instructions.md`:
- Around line 178-186: Update the PSL examples and prose to use the bare enum
member form for defaults: replace usages of `@default`(EnumType.Member) and
`@default`(Priority.Low) with `@default`(Low) (and any other member examples) and
change the generic placeholder `@default`(<EnumType>.<Member>) to
`@default`(<Member>); ensure the text clarifies that PSL enum defaults use only
the member identifier (not the enum name) so examples and placeholder match the
actual authoring surface referenced by the doc.
🪄 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: 0a5002ae-17bc-4bfc-9b2a-dc06d4bb4daf

📥 Commits

Reviewing files that changed from the base of the PR and between 1c13f26 and fa11672.

⛔ Files ignored due to path filters (2)
  • projects/enums-as-domain-concept/slices/enum-member-defaults/plan.md is excluded by !projects/**
  • projects/enums-as-domain-concept/slices/enum-member-defaults/spec.md is excluded by !projects/**
📒 Files selected for processing (26)
  • examples/prisma-next-demo/migrations/app/20260610T2216_set_priority_default/contract.prisma
  • examples/prisma-next-demo/migrations/app/20260610T2216_set_priority_default/end-contract.d.ts
  • examples/prisma-next-demo/migrations/app/20260610T2216_set_priority_default/end-contract.json
  • examples/prisma-next-demo/migrations/app/20260610T2216_set_priority_default/migration.json
  • examples/prisma-next-demo/migrations/app/20260610T2216_set_priority_default/migration.ts
  • examples/prisma-next-demo/migrations/app/20260610T2216_set_priority_default/ops.json
  • examples/prisma-next-demo/migrations/app/20260610T2216_set_priority_default/start-contract.d.ts
  • examples/prisma-next-demo/migrations/app/20260610T2216_set_priority_default/start-contract.json
  • examples/prisma-next-demo/migrations/pgvector/20260601T0000_install_vector_extension/migration.json
  • examples/prisma-next-demo/migrations/pgvector/contract.json
  • examples/prisma-next-demo/migrations/pgvector/refs/head.json
  • examples/prisma-next-demo/prisma/contract.ts
  • examples/prisma-next-demo/src/main-no-emit.ts
  • examples/prisma-next-demo/src/main.ts
  • examples/prisma-next-demo/src/prisma/contract.d.ts
  • examples/prisma-next-demo/src/prisma/contract.json
  • examples/prisma-next-demo/src/prisma/contract.prisma
  • examples/prisma-next-demo/src/queries/enum-default-demo-no-emit.ts
  • examples/prisma-next-demo/src/queries/enum-default-demo.ts
  • examples/prisma-next-demo/test/enum-surface.integration.test.ts
  • packages/2-sql/2-authoring/contract-psl/src/interpreter.ts
  • packages/2-sql/2-authoring/contract-psl/src/psl-field-resolution.ts
  • packages/2-sql/2-authoring/contract-psl/test/interpreter.enum2.test.ts
  • packages/2-sql/2-authoring/contract-ts/src/contract-dsl.ts
  • packages/2-sql/2-authoring/contract-ts/test/enum-type.member-defaults.test.ts
  • skills/upgrade/prisma-next-upgrade/upgrades/0.13-to-0.14/instructions.md

Comment on lines +12 to +48
export async function enumDefaultDemoNoEmit(runtime: Runtime): Promise<void> {
await runtime.execute(
sql.user.insert([{ id: demoUserId, email: '[email protected]', kind: 'user' }]).build(),
);

// `priority` is intentionally omitted — the field is typed-optional here
// because the TS contract declares `.default(Priority.members.Low)`.
await runtime.execute(
sql.post.insert([{ id: demoPostId, title: 'Enum-default demo', userId: demoUserId }]).build(),
);

const rows = await runtime.execute(
sql.post
.select('id', 'priority')
.where((f, fns) => fns.eq(f.id, demoPostId))
.build(),
);
const row = rows[0];
if (!row) throw new Error('Demo post not found after insert');

console.log(`priority read back from DB: ${row.priority}`);
console.log(
`Expected 'low' (the .default(Priority.members.Low) value): ${row.priority === 'low'}`,
);

await runtime.execute(
sql.post
.delete()
.where((f, fns) => fns.eq(f.id, demoPostId))
.build(),
);
await runtime.execute(
sql.user
.delete()
.where((f, fns) => fns.eq(f.id, demoUserId))
.build(),
);

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Root cause: cleanup is not guaranteed when using fixed demo IDs.

Both demo implementations only delete inserted rows on the happy path. Any mid-flow error can leave records behind and make reruns fail with ID collisions. Consolidate both to the same try { ... } finally { cleanup } structure.

🤖 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/src/queries/enum-default-demo-no-emit.ts` around
lines 12 - 48, Wrap the main demo flow in enumDefaultDemoNoEmit in a try { ... }
finally { ... } so cleanup always runs: perform the inserts, select and
assertions inside the try block and move both delete calls (the
sql.post.delete() for demoPostId and sql.user.delete() for demoUserId) into the
finally block so runtime.execute(...) is invoked to remove demoPostId and
demoUserId even if an error occurs; keep existing checks (e.g., the row/null
check) inside the try.

Comment on lines +417 to 438
const enum2Handle = enum2Handles?.get(field.typeName);
const loweredDefault: LoweredFieldDefault = defaultAttribute
? enum2Handle
? lowerEnum2DefaultForField({
modelName: model.name,
fieldName: field.name,
defaultAttribute,
enumHandle: enum2Handle,
sourceId,
diagnostics,
})
: lowerDefaultForField({
modelName: model.name,
fieldName: field.name,
defaultAttribute,
columnDescriptor: descriptor,
generatorDescriptorById,
sourceId,
defaultFunctionRegistry,
diagnostics,
})
: {};

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.

⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Handle enum2 aliases when lowering member defaults.

enum2Handles?.get(field.typeName) only matches fields typed with the enum2’s original name. Named types already resolve enum2-backed descriptors through namedTypeDescriptors, so a schema like type PriorityAlias = Priority plus priority PriorityAlias @default(Low) will fall back to the generic scalar-default path and reject a valid enum member default. Resolve the underlying enum2 handle through named-type aliases too.

🤖 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-psl/src/psl-field-resolution.ts` around
lines 417 - 438, The current lowering uses enum2Handles?.get(field.typeName)
which misses named-type aliases; update the resolution so if
enum2Handles.get(field.typeName) is undefined you resolve the named type
descriptor (namedTypeDescriptors?.get(field.typeName) or similar) to find the
underlying enum2 name/descriptor and then look up enum2Handles by that
underlying name before deciding between lowerEnum2DefaultForField and
lowerDefaultForField; keep the same call sites (lowerEnum2DefaultForField,
lowerDefaultForField) and pass the same parameters once you have the resolved
enumHandle so alias-typed fields like PriorityAlias will correctly use the enum2
path.

Comment on lines +178 to +186
<!--
TML-2855: member defaults via `@default(member)` (PR #808). The PSL interpreter and
contract-ts authoring surface now resolve `@default(EnumType.Member)` to a
`{ kind: 'literal', value: '<dbValue>' }` default. The demo `priority` field gains
`@default(Priority.Low)` and a new migration (`20260610T2216_set_priority_default`)
is emitted. Additive and opt-in: only fields that declare `@default(<EnumType>.<Member>)`
are affected; no existing contract changes shape. No consumer action required; the
cutover (TML-2853) will carry the user-facing docs.
-->

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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Correct the PSL syntax examples to match the actual authoring surface.

The documentation uses @default(EnumType.Member) and @default(Priority.Low) notation, but the actual PSL syntax for enum member defaults is a bare member identifier: @default(Low), not @default(Priority.Low). The enum name prefix is not part of the PSL surface.

📝 Suggested correction
 <!--
 TML-2855: member defaults via `@default(member)` (PR `#808`). The PSL interpreter and
-contract-ts authoring surface now resolve `@default(EnumType.Member)` to a
+contract-ts authoring surface now resolve `@default(Member)` (bare member identifier in PSL) to a
 `{ kind: 'literal', value: '<dbValue>' }` default. The demo `priority` field gains
-`@default(Priority.Low)` and a new migration (`20260610T2216_set_priority_default`)
+`@default(Low)` and a new migration (`20260610T2216_set_priority_default`)
 is emitted. Additive and opt-in: only fields that declare `@default(<EnumType>.<Member>)`
 are affected; no existing contract changes shape. No consumer action required; the
 cutover (TML-2853) will carry the user-facing docs.
 -->

Note: Line 183's generic placeholder @default(<EnumType>.<Member>) should also be @default(<Member>) to match PSL syntax, though as a placeholder in prose it may be acceptable if clarified that it refers to member name only.

🤖 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 `@skills/upgrade/prisma-next-upgrade/upgrades/0.13-to-0.14/instructions.md`
around lines 178 - 186, Update the PSL examples and prose to use the bare enum
member form for defaults: replace usages of `@default`(EnumType.Member) and
`@default`(Priority.Low) with `@default`(Low) (and any other member examples) and
change the generic placeholder `@default`(<EnumType>.<Member>) to
`@default`(<Member>); ensure the text clarifies that PSL enum defaults use only
the member identifier (not the enum name) so examples and placeholder match the
actual authoring surface referenced by the doc.

Merged via the queue into main with commit dcc2613 Jun 11, 2026
20 checks passed
@wmadden-electric
wmadden-electric deleted the tml-2855-slice-enum-member-defaults-defaultadmin-renders-default branch June 11, 2026 10:39
paulwer pushed a commit to paulwer/prisma-next that referenced this pull request Jun 11, 2026
…gh emit (prisma#809)

## Linked issue

Refs [TML-2885](https://linear.app/prisma-company/issue/TML-2885).
**Was stacked on prisma#808 → prisma#805** — both now merged; this PR targets `main`
directly (rebased, four commits).
With TML-2855, completes the cutover's (TML-2853) parity prerequisites.

## At a glance

The emitted `contract.d.ts` now types the domain `enum` block, so
`db.enums` is literal-typed **through the emitted contract** — closing
the R6 emit-parity gap found in prisma#805's review:

```ts
// before (emitted path): runtime correct, types collapsed
db.enums.public.Priority.values        // JsonValue[]
db.enums.public.Priority.members.High  // JsonValue

// after
db.enums.public.Priority.values        // readonly ['low', 'high', 'urgent']
db.enums.public.Priority.members.High  // 'high'
```

```ts
// emitted contract.d.ts — the public namespace gains:
readonly enum: {
  readonly Priority: {
    readonly codecId: 'pg/text@1';
    readonly members: readonly [
      { readonly name: 'Low'; readonly value: 'low' },
      { readonly name: 'High'; readonly value: 'high' },
      { readonly name: 'Urgent'; readonly value: 'urgent' }
    ];
  };
};
```

## Decision

One change site: the emitter renders the per-namespace domain `enum`
block with literal member tuples (order preserved — it's semantic). The
**existing** accessor type chain (`NamespaceEnumAccessors` /
`NamespacedEnums` in `enum-accessor.ts`) already extracts literal
`values`/`members` from exactly this shape, so it is untouched — as are
the runtime and the TML-2852 field narrowing. `contract.json` and every
hash are byte-identical: this is a types-only emission change.

The acceptance evidence is deletion: the demo's
`getPriorityEnumFromEmit()` workaround and its `blindCast`s — whose
reason strings documented exactly this gap — are gone; every consumer
reads `db.enums.public.Priority` directly, cast-free (net −4 `blindCast`
sites).

## Reviewer notes

- **Non-vacuity is compile-level:** without the emitted enum block,
`db.enums.public.Priority` does not exist at the type level, so the demo
type tests fail to compile (verified by deleting the block and watching
six files fail; restored cleanly). Stronger than a runtime assert.
- **One genuinely new `blindCast`** in
[generate-contract-dts.ts](packages/1-framework/3-tooling/emitter/src/generate-contract-dts.ts)
(`ns.enum`), byte-identical in idiom to the two pre-existing sibling
casts (`ns.models`, `ns.valueObjects`) it sits beside.
- **A real stack regression was caught and fixed during this slice:**
TML-2882's `aad4e15b3` made `blockAttributes` required on
`PslExtensionBlock`; a cli test fixture predated it. Earlier "full
typecheck green" runs were stale-dist false greens. Fixed on the base
branch (`53680da2e` on prisma#805) and the stack rebased.
- The JSON→TS literal rendering reuses the TML-2852 D4 helpers
(`serializeValue`/`serializeObjectKey`) — no duplication.

## Behavior changes & evidence

- **The emitter renders the domain enum block** —
[generate-contract-dts.ts](packages/1-framework/3-tooling/emitter/src/generate-contract-dts.ts);
evidence:
[emitter.integration.test.ts](packages/1-framework/3-tooling/emitter/test/emitter.integration.test.ts)
(string codec, int-codec bare-number literals, quoted non-identifier
member keys, enum-less namespaces emit no block; unbound-namespace
coverage folded in).
- **`db.enums` is literal-typed through emit, cast-free in the demo** —
[get-posts-by-priority.ts](examples/prisma-next-demo/src/queries/get-posts-by-priority.ts)
(workaround deleted),
[demo-dx.types.test.ts](examples/prisma-next-demo/test/demo-dx.types.test.ts)
(literal `members.High` / `values` through the emitted artifacts).
- **Types-only:** no `.json` file changes; four `.d.ts` files regenerate
with only the additive enum block.

## Testing performed

- `pnpm test:packages` — green on final HEAD (one adapter-postgres
DB-infra timeout, diff-unreachable)
- `pnpm typecheck` — green incl. `@prisma-next/cli` against fresh dist
(see reviewer note on the fixed stack regression)
- `pnpm fixtures:check` — clean (full re-emit against fresh dist, no
drift)
- `pnpm lint:deps` — clean

## Skill update

n/a — types-only emission change; the user-facing `db.enums` surface was
documented with TML-2852, and the transitional-keyword docs policy
(skill lands at cutover) carries the rest.

## Follow-ups

- TML-2853 (cutover) — parity prerequisites now complete once this stack
merges.

## Alternatives considered

- **Narrowing at the accessor instead of emitting the block**
(parameterize `EnumAccessor` per call site). Rejected: the accessor
chain was already built to extract from the typed contract shape;
emitting the shape fixes every consumer at once and keeps "the `.d.ts`
is the contract" honest.
- **Emitting only the value tuples (not full member pairs).** Rejected:
`members.<Name>` needs the name→value literal pairs; the full tuple is
what `EnumEntryMembers` consumes, and it matches the runtime JSON
one-for-one.

## 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`).

---------

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