Repository navigation
TML-2965: author native Postgres enums in TypeScript - #935
Conversation
Slice spec + plan entry for the native-enum TypeScript authoring mirror: - a generic pack-entity attachment through the defineContract chain (following the enums wiring) so an author-declared pack entity lands in entries.<kind> + derives its value-set; - a bespoke nativeEnum(...) handle + a deferred pg.enum(handle) descriptor (follows the enumType() precedent; the generic type.pg.enum path is bypassed → follow-up TML-2983); - type-name qualification relocated out of the codec (columnFromEntity returns the bare name) into a generic build-stage step shared by PSL and TS, so a named schema like auth is authorable in TS with no eager, wrongly-timed qualification — emitted output byte-identical to PSL. Proven by a PSL+TS byte-identical parity test covering the default and a named schema. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…ML-2965) TS authoring only admitted the closed models/valueObjects/enums set; a pack-contributed entity kind (native_enum, and later RLS role/policy) had no way into a namespace`s entries. Add a generic, namespace-scoped `packEntities` field (namespace → kind → name → entity) threaded through the defineContract chain the same way `enums` is — reachable from both the plain-definition and scaffold+factory forms (with a 3-level deep merge so factory-declared siblings do not drop scaffold-declared ones). At assembly each entity lands in entries.<kind>, and its value-set is derived via the same `deriveValueSetFromEntity` hook the PSL interpreter uses and folded into entries.valueSet. The framework/contract-ts names no specific kind; the managed table/valueSet kinds are rejected if an author supplies them. typecheck 143/143; contract-ts 387/387; target-postgres 686/686; fixtures:check zero drift; lint:casts flat (1031); lint:deps clean. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…odec (TML-2965) `PgEnumDescriptor.columnFromEntity` schema-qualified the enum type name eagerly (auth.aal_level), which is the wrong home twice over: qualifying a type name by schema is a generic concern, and the namespace is not known at a TS builder call site (a column is built before its model associates a namespace). So the codec now returns the bare type name, and a generic `qualifyTypeName(name, namespaceId, defaultNamespaceId)` helper (in @prisma-next/sql-contract, reachable by both SQL authoring paths, target-agnostic — the default namespace id is a parameter since Postgres`s `public` is target-local) applies the prefix. The PSL path qualifies at resolution, gated on the codec result carrying `typeParams.typeName`, so only named-type codecs (pg/enum) qualify and the generic entity-ref path is untouched. Pure relocation — emitted output byte-identical (fixtures:check zero drift). Sets up the coming TS path to qualify at builder→IR assembly, where the namespace is known. typecheck 143/143; sql-contract 259/259; sql-contract-psl 346/346; target-postgres 686/686; fixtures:check zero drift; lint:casts flat (1031); lint:deps clean. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…num (TML-2965)
Add the TS authoring surface for native Postgres enums, mirroring the PSL
`native_enum` block + `pg.enum(Ref)` column byte-for-byte:
- `nativeEnum(name, ...values).map(typeName)` (Postgres extension TS surface) —
a bespoke handle constructor (following the enumType() precedent): validates
non-empty/unique values, builds a PostgresNativeEnum, derives its value-set at
build time. `name` is the entity name (the entries/valueSet key); `.map()`
overrides the Postgres type name (PSL`s `@@map`), default type name = name.
- `pg.enum(handle)` — a deferred column descriptor carrying a generic,
family-blind `entityRef` ({ entityKind, entityName, entity }) on the framework
ColumnTypeDescriptor. It computes no namespace-dependent value at builder-call
time (the column is built before its model has a namespace).
- build-contract resolves each deferred column against the field`s now-known
model namespace: schema-qualifies the type name (via qualifyTypeName), harvests
the entity into the namespace`s packEntities so it lands in entries.<kind> +
derives its value-set (reusing the D1 attachment), and wires the column`s
valueSet ref — all generically, naming no entity kind.
Proven for public and named (`auth`) schemas incl. an emit-then-consume test
typing the column as the member value union.
typecheck 143/143; contract-ts 387/387; target-postgres 686/686; postgres 101/101;
fixtures:check zero drift; lint:casts 1031; lint:framework-vocabulary 906; lint:deps clean.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…(TML-2965) Prove a native_enum + pg.enum column authored in TypeScript produces a contract identical to the PSL equivalent, in the default schema and a named schema (auth, the @@map-distinct case): - extend ts-psl-parity.real-packs.test.ts with in-memory `Contract` toEqual cases (default + auth), building the TS side via nativeEnum(...).map(...) + pg.enum(handle) and the PSL side via the equivalent native_enum block + pg.enum(Ref) (the shared helper now threads codecLookup, which pg.enum resolution needs); - add a parity/native-enum/ fixture (schema.prisma + contract.ts + packs.ts + expected.contract.json) asserting the emitted contract.json is byte-identical between the TS and PSL authorings. No PSL<->TS difference surfaced. Also records the additive TML-2965 postgres-extension exports in the 0.14->0.15 upgrade instructions (net-new; no extension-author action). Full gate green: build; typecheck --force 143/143; lint incl lint:casts (1031), lint:framework-vocabulary (906), lint:deps; fixtures:check zero drift; test:packages, test:integration (1138), test:e2e (109). Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…ML-2965) Review finding: the harvest of deferred entity-ref columns was last-write-wins, so two different nativeEnum handles sharing a name in one namespace silently collided — a column kept its own type/cast but the emitted entries.valueSet came from the last harvested entity, an internally inconsistent column. PSL hard-errors on the equivalent (PSL_DUPLICATE_DECLARATION), and byte-parity with PSL is the slice`s bar, so the TS path now rejects it too. Guard both `harvestPackEntity` (across columns) and `mergeHarvestedPackEntities` (harvested vs author-declared) by entity identity — the same handle reused by many columns is normal and records once; two different entities under one name+kind in a namespace throws a path-aware error. Also documents two by-design asymmetries of the harvest-from-usage model (a handle used in N namespaces materialises N types; an unused nativeEnum is absent — the latter a noted follow-up). typecheck 143/143; contract-ts 387/387; postgres 103/103 (+2 collision cases); ts-psl-parity 4/4; fixtures:check zero drift; lint:casts 1031; lint:framework-vocabulary 906. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (6)
✅ Files skipped from review due to trivial changes (1)
🚧 Files skipped from review as they are similar to previous changes (3)
📝 WalkthroughWalkthroughThis PR adds late-resolved entity references to column descriptors, threads ChangesNative Enum Authoring
Estimated code review effort: 4 (Complex) | ~60 minutes Sequence Diagram(s)sequenceDiagram
participant ContractAuthor
participant NativeEnumAPI
participant BuildContract
participant PostgresTarget
participant StorageNamespace
ContractAuthor->>NativeEnumAPI: nativeEnum(name, ...members)
ContractAuthor->>NativeEnumAPI: pg.enum(handle)
NativeEnumAPI->>BuildContract: ColumnTypeDescriptor with entityRef
BuildContract->>BuildContract: collect pack entities and qualify column
BuildContract->>PostgresTarget: qualifyColumnType(enum descriptor, namespaceId)
PostgresTarget-->>BuildContract: qualified nativeType and typeParams.typeName
BuildContract->>StorageNamespace: emit entries.native_enum and entries.valueSet
Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
size-limit report 📦
|
@prisma-next/extension-author-tools
@prisma-next/mongo-runtime
@prisma-next/family-mongo
@prisma-next/sql-runtime
@prisma-next/family-sql
@prisma-next/extension-arktype-json
@prisma-next/middleware-cache
@prisma-next/mongo
@prisma-next/extension-paradedb
@prisma-next/extension-pgvector
@prisma-next/extension-postgis
@prisma-next/postgres
@prisma-next/sql-orm-client
@prisma-next/sqlite
@prisma-next/extension-supabase
@prisma-next/target-mongo
@prisma-next/adapter-mongo
@prisma-next/driver-mongo
@prisma-next/contract
@prisma-next/utils
@prisma-next/config
@prisma-next/errors
@prisma-next/framework-components
@prisma-next/operations
@prisma-next/ts-render
@prisma-next/contract-authoring
@prisma-next/ids
@prisma-next/psl-parser
@prisma-next/psl-printer
@prisma-next/cli
@prisma-next/cli-telemetry
@prisma-next/config-loader
@prisma-next/emitter
@prisma-next/language-server
@prisma-next/migration-tools
prisma-next
@prisma-next/vite-plugin-contract-emit
@prisma-next/mongo-codec
@prisma-next/mongo-contract
@prisma-next/mongo-value
@prisma-next/mongo-contract-psl
@prisma-next/mongo-contract-ts
@prisma-next/mongo-emitter
@prisma-next/mongo-schema-ir
@prisma-next/mongo-query-ast
@prisma-next/mongo-orm
@prisma-next/mongo-query-builder
@prisma-next/mongo-lowering
@prisma-next/mongo-wire
@prisma-next/sql-contract
@prisma-next/sql-errors
@prisma-next/sql-operations
@prisma-next/sql-schema-ir
@prisma-next/sql-contract-psl
@prisma-next/sql-contract-ts
@prisma-next/sql-contract-emitter
@prisma-next/sql-lane-query-builder
@prisma-next/sql-relational-core
@prisma-next/sql-builder
@prisma-next/target-postgres
@prisma-next/target-sqlite
@prisma-next/adapter-postgres
@prisma-next/adapter-sqlite
@prisma-next/driver-postgres
@prisma-next/driver-sqlite
commit: |
| /** | ||
| * Late-resolved pack-entity reference: `entityKind`/`entityName` identify a | ||
| * pack entity whose final placement depends on data not yet known when the | ||
| * descriptor carrying this reference is built — e.g. an owning namespace | ||
| * resolved only once the surrounding structure is assembled. | ||
| */ | ||
| export type EntityRef = { | ||
| readonly entityKind: string; | ||
| readonly entityName: string; | ||
| readonly entity: unknown; | ||
| }; |
There was a problem hiding this comment.
Why is this in a file called "column spec"
There was a problem hiding this comment.
Repositioned so it no longer orphans the ColumnTypeDescriptor doc, and kept the generic EntityRef name — a column-scoped name (ColumnEntityRef) adds forbidden "column" framework vocab and bumps the lint:framework-vocabulary ratchet (906→909), which cuts against the family-blindness that ratchet enforces. It stays in this file because it is a field on ColumnTypeDescriptor; the doc now frames it as "a field on the descriptor it is declared on". (826c88b)
There was a problem hiding this comment.
Does this belong in SQL at all? Only Postgres has a namespace. Can we move this to the target?
We should otherwise be delegating to the namespace schemaIR node to tell us its ID, which for the unbound namespace should be empty
There was a problem hiding this comment.
Agreed — moved out of the SQL family entirely. Qualification is now a Postgres-target concern: the target contributes an authoring.qualifyColumnType hook, with the rule owned by the pg/enum codec (bare for the default/unbound schema, ${ns}.${name} otherwise). build-contract reads it off definition.target duck-typed (like columnFromEntity) and applies it at column construction, so the storage column and the domain field are both built qualified in one pass — no more build-then-patch. qualifyTypeName is deleted from @prisma-next/sql-contract. (826c88b)
| /** | ||
| * The target's default namespace id (e.g. Postgres's `'public'`) — consulted | ||
| * only when a type constructor's descriptor declares an `entityRefArg`, to | ||
| * decide whether the resolved entity's type name needs schema-qualifying | ||
| * against `namespaceId` (see `qualifyEntityRefColumnResult`). | ||
| */ | ||
| readonly defaultNamespaceId?: string; |
There was a problem hiding this comment.
I'm a bit suspicious of this being present in the sql family
There was a problem hiding this comment.
Right — the defaultNamespaceId threading is gone and the PSL resolver no longer qualifies; it returns the codec bare name and the target hook qualifies at construction. Nothing about schema-qualification remains in the SQL family. (826c88b)
| * of them, silently mismatching the other column's type/cast. PSL hard-errors | ||
| * on the equivalent (`PSL_DUPLICATE_DECLARATION`); the TS path rejects it too. | ||
| */ | ||
| function harvestPackEntity( |
There was a problem hiding this comment.
Renamed to plain English: collectPackEntityFromColumn / CollectedPackEntities / mergeCollectedPackEntities. (826c88b)
| * author-declared pack entity claiming one of these would silently clobber | ||
| * or be clobbered by the managed slot, so it is rejected outright. | ||
| */ | ||
| const MANAGED_ENTRY_KINDS = new Set(['table', 'valueSet']); |
There was a problem hiding this comment.
Sourced from the canonical constants — tableEntityKind.kind / valueSetEntityKind.kind from @prisma-next/sql-contract — instead of the string literals. (826c88b)
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/2-sql/2-authoring/contract-ts/src/build-contract.ts (1)
973-1005: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick winAdd a collision check before merging namespace
valueSetentries atpackages/2-sql/2-authoring/contract-ts/src/build-contract.ts:983-990
{ ...enumValueSetEntries, ...packValueSetEntries }lets a pack-entity-derivedvalueSetoverwrite a same-namedenumType()value set in the same namespace. That can make a domain enum CHECK resolve to the wrong values viaentries.valueSet[entityName]. Reject same-name collisions here instead of letting the spread win.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/2-sql/2-authoring/contract-ts/src/build-contract.ts` around lines 973 - 1005, The namespace valueSet merge in build-contract.ts currently lets pack-entity-derived entries overwrite enumType()-derived entries with the same name. Add an explicit collision check before constructing valueSetEntries in the namespace assembly logic so any duplicate key between storageValueSetsByNs and derivePackEntityValueSets is rejected with a clear error. Use the existing collect/merge flow around mergeHarvestedPackEntities, derivePackEntityValueSets, and createNamespace to locate the fix.
🧹 Nitpick comments (2)
packages/3-extensions/postgres/src/contract/native-enum.ts (1)
77-96: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winValidate the entity
nameargument, not justmembers.
nativeEnumrejects empty/duplicate members but doesn't validatename(or the.map()-provided type name). PSL'snative_enum <Name>is grammar-constrained to a valid identifier; this TS surface accepts any string, including'', which would later produce an invalidCREATE TYPEstatement.🛡️ Proposed guard
export function nativeEnum< const Name extends string, const Members extends readonly [string, ...string[]], >(name: Name, ...members: Members): NativeEnumHandle<Name, Name, Members> { + if (name.length === 0) { + throw new Error('nativeEnum(): name must be a non-empty string.'); + } if (members.length === 0) { throw new Error(`nativeEnum("${name}"): must have at least one member.`); }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/3-extensions/postgres/src/contract/native-enum.ts` around lines 77 - 96, The nativeEnum validation currently checks only member values; add validation for the enum name/type name passed as name in nativeEnum and the derived type name used by buildNativeEnumHandle. Ensure the name is constrained to a valid PSL identifier before returning the NativeEnumHandle, and throw a clear error for empty or otherwise invalid names. Keep the existing member uniqueness checks intact, and update nativeEnum/buildNativeEnumHandle so invalid .map()-produced names cannot flow through to CREATE TYPE generation.packages/2-sql/2-authoring/contract-ts/src/contract-builder.ts (1)
353-389: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winScaffold-vs-factory pack-entity merge silently overwrites on name collision, unlike the identity-checked harvest merge in
build-contract.ts.
mergePackEntityNamesdoes{ ...(a ?? {}), ...(b ?? {}) }with no identity check, so a factory-returned pack entity silently clobbers a scaffold-declared one of the same namespace/kind/name with a different entity, with no error — while the equivalent collision between "declared" and "harvested-via-column" pack entities inbuild-contract.ts'smergeHarvestedPackEntitiesthrows. This mirrors the existingenumsmerge precedent at Line 475, so it may be an intentional/consistent choice, but it's worth confirming this is deliberate given the PR's broader emphasis on rejecting duplicate name collisions.♻️ Optional: add identity check consistent with the build-stage merge
function mergePackEntityNames( a: Readonly<Record<string, unknown>> | undefined, b: Readonly<Record<string, unknown>> | undefined, ): Readonly<Record<string, unknown>> { - return { ...(a ?? {}), ...(b ?? {}) }; + for (const [name, entity] of Object.entries(b ?? {})) { + const existing = a?.[name]; + if (existing !== undefined && existing !== entity) { + throw new Error(`mergePackEntities: conflicting entity declared for "${name}".`); + } + } + return { ...(a ?? {}), ...(b ?? {}) }; }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/2-sql/2-authoring/contract-ts/src/contract-builder.ts` around lines 353 - 389, The pack-entity merge at mergePackEntityNames currently shallow-merges scaffold and factory entries, so a same namespace/kind/name collision can silently overwrite a different entity. Update the merge logic in mergePackEntities/mergePackEntityKinds/mergePackEntityNames to mirror the identity-checked behavior used by mergeHarvestedPackEntities in build-contract.ts: when both sides define the same pack entity key, verify they refer to the same entity and throw on conflicting definitions instead of overwriting. Keep the merge shape the same for non-conflicting namespace/kind/name entries.
🤖 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
`@skills/extension-author/prisma-next-extension-upgrade/upgrades/0.14-to-0.15/instructions.md`:
- Around line 262-271: The note describing the new native enum API uses the
wrong shape for `nativeEnum`; update the instructions to reflect that mapping
happens on the returned handle, not as a constructor argument. In the references
to `nativeEnum`, `NativeEnumHandle`, and `pg.enum`, describe the flow as
creating the handle with the enum name and values, then applying the type
mapping on that handle, so the guidance matches the actual contract-builder API.
---
Outside diff comments:
In `@packages/2-sql/2-authoring/contract-ts/src/build-contract.ts`:
- Around line 973-1005: The namespace valueSet merge in build-contract.ts
currently lets pack-entity-derived entries overwrite enumType()-derived entries
with the same name. Add an explicit collision check before constructing
valueSetEntries in the namespace assembly logic so any duplicate key between
storageValueSetsByNs and derivePackEntityValueSets is rejected with a clear
error. Use the existing collect/merge flow around mergeHarvestedPackEntities,
derivePackEntityValueSets, and createNamespace to locate the fix.
---
Nitpick comments:
In `@packages/2-sql/2-authoring/contract-ts/src/contract-builder.ts`:
- Around line 353-389: The pack-entity merge at mergePackEntityNames currently
shallow-merges scaffold and factory entries, so a same namespace/kind/name
collision can silently overwrite a different entity. Update the merge logic in
mergePackEntities/mergePackEntityKinds/mergePackEntityNames to mirror the
identity-checked behavior used by mergeHarvestedPackEntities in
build-contract.ts: when both sides define the same pack entity key, verify they
refer to the same entity and throw on conflicting definitions instead of
overwriting. Keep the merge shape the same for non-conflicting
namespace/kind/name entries.
In `@packages/3-extensions/postgres/src/contract/native-enum.ts`:
- Around line 77-96: The nativeEnum validation currently checks only member
values; add validation for the enum name/type name passed as name in nativeEnum
and the derived type name used by buildNativeEnumHandle. Ensure the name is
constrained to a valid PSL identifier before returning the NativeEnumHandle, and
throw a clear error for empty or otherwise invalid names. Keep the existing
member uniqueness checks intact, and update nativeEnum/buildNativeEnumHandle so
invalid .map()-produced names cannot flow through to CREATE TYPE generation.
🪄 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: 0198edbf-90a9-4e6f-a1fb-7bf61c5ab52b
⛔ Files ignored due to path filters (3)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yamlprojects/native-postgres-enums/plan.mdis excluded by!projects/**projects/native-postgres-enums/slices/native-enum-ts-authoring/spec.mdis excluded by!projects/**
📒 Files selected for processing (28)
packages/1-framework/1-core/framework-components/src/shared/column-spec.tspackages/2-sql/1-core/contract/package.jsonpackages/2-sql/1-core/contract/src/exports/qualify-type-name.tspackages/2-sql/1-core/contract/src/qualify-type-name.tspackages/2-sql/1-core/contract/test/qualify-type-name.test.tspackages/2-sql/1-core/contract/tsdown.config.tspackages/2-sql/2-authoring/contract-psl/src/interpreter.tspackages/2-sql/2-authoring/contract-psl/src/psl-column-resolution.tspackages/2-sql/2-authoring/contract-psl/src/psl-field-resolution.tspackages/2-sql/2-authoring/contract-ts/src/build-contract.tspackages/2-sql/2-authoring/contract-ts/src/contract-builder.tspackages/2-sql/2-authoring/contract-ts/src/contract-definition.tspackages/2-sql/2-authoring/contract-ts/src/contract-dsl.tspackages/2-sql/2-authoring/contract-ts/src/contract-lowering.tspackages/2-sql/2-authoring/contract-ts/test/pack-entity-attachment.test.tspackages/3-extensions/postgres/package.jsonpackages/3-extensions/postgres/src/contract/native-enum.tspackages/3-extensions/postgres/src/exports/contract-builder.tspackages/3-extensions/postgres/test/contract-builder/native-enum.test.tspackages/3-targets/3-targets/postgres/src/core/codecs.tspackages/3-targets/3-targets/postgres/src/exports/codecs.tspackages/3-targets/3-targets/postgres/src/exports/types.tsskills/extension-author/prisma-next-extension-upgrade/upgrades/0.14-to-0.15/instructions.mdtest/integration/test/authoring/parity/native-enum/contract.tstest/integration/test/authoring/parity/native-enum/expected.contract.jsontest/integration/test/authoring/parity/native-enum/packs.tstest/integration/test/authoring/parity/native-enum/schema.prismatest/integration/test/authoring/parity/ts-psl-parity.real-packs.test.ts
… at construction (TML-2965) Address the #935 review. Schema-qualifying a native-enum type name (auth.aal_level) is a Postgres concern — only Postgres has schemas — so it must not live in the SQL family. Move it to the target, and apply it where the storage column and the domain field are both first constructed so neither is built bare-then-patched: - The Postgres target contributes `authoring.qualifyColumnType`; the rule lives on the `pg/enum` codec (`qualifyNativeType`: bare for the default/unbound schema, `${ns}.${name}` otherwise). `buildSqlContractFromDefinition` reads the hook off `definition.target` duck-typed (like `columnFromEntity`) and applies it to each scalar column at construction — so the storage column is built from the qualified descriptor and the domain field derives from it, both correct in one pass. Both the PSL `pg.enum(Ref)` and TS `pg.enum(handle)` paths route through this loop; the dispatch keys off the codec id, catching both. - Delete `qualifyTypeName` from `@prisma-next/sql-contract` and its `defaultNamespaceId` threading through the PSL resolver — the family no longer knows about qualification, it only calls a target hook (like `createNamespace`). - Delete the two fix-up passes the earlier build-then-patch approach needed: the `createNamespace` column-walk (+ probe schema + `PostgresSchema.qualifyType`) and `syncDomainFieldTypeParams`. Also from the review: rename `harvest*` → `collect*` (build-contract); source the managed entry kinds from `tableEntityKind.kind`/`valueSetEntityKind.kind` instead of literals; reposition `EntityRef` so it no longer orphans the `ColumnTypeDescriptor` doc. Emitted output byte-identical (fixtures:check zero drift). typecheck 143/143; target-postgres 686/686; postgres 103/103; PSL<->TS parity 4/4 + 22/22; lint:casts 1031; lint:framework-vocabulary 906. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
- Guard the namespace value-set merge: a pack-entity-derived value-set could silently overwrite a same-named `enumType()`-derived one in a namespace (`entries.valueSet[name]` drives typing / the domain-enum CHECK), corrupting a column. `mergeNamespaceValueSets` now throws on a name present in both, like the harvest guard. - `nativeEnum` validates the entity name and the `.map()` type name (reject empty/whitespace), not just members — an empty name flowed into an invalid CREATE TYPE. - Make the scaffold-vs-factory pack-entity merge identity-checked (throws on a same-name different-instance collision), consistent with the build-stage `mergeCollectedPackEntities`. - Fix the 0.14→0.15 upgrade note to the shipped `nativeEnum(name, …).map(typeName)` shape. typecheck 143/143; contract-ts 389/389; postgres 106/106; target-postgres 686/686; PSL<->TS parity 26/26; fixtures:check zero drift; lint:casts 1031; lint:framework-vocabulary 906. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
At a glance
Native Postgres enums were PSL-only. Now they're authorable in the TypeScript DSL too:
produces the same contract as the PSL equivalent:
native_enum AalLevel { aal1 = "aal1" aal2 = "aal2" aal3 = "aal3" @@map("aal_level") } // in schema `auth` model Session { aal pg.enum(AalLevel)? }— the same
entries.valueSet.AalLevel, the same column{ codecId: pg/enum@1, nativeType: "auth.aal_level", typeParams, valueSet }, and the same'aal1' | 'aal2' | 'aal3'value-union typing — inpublicand named schemas alike.The decision
Three moves, in layered order:
models/valueObjects/enumsset, so a pack-contributed entity kind had no way into a namespace'sentries. A new genericpackEntitiesfield threads through thedefineContractchain — the same wiringenumsalready uses — and lands any author-declared entity inentries.<kind>, deriving its value-set via the same hook the PSL interpreter uses. The framework andcontract-tsname no specific kind, so RLSrole/policyride this same seam later.nativeEnum(…)+pg.enum(handle)on the Postgres TS surface, following the existingenumType()precedent — rather than repairing the generic auto-composedtype.pg.enumpath, which is a larger change shared with RLS (TML-2983).columnFromEntityused to bakeauth.aal_leveleagerly; that's the wrong home twice over — qualifying a type name is a generic concern, and afield.column(pg.enum(handle))builder call can't know its model's namespace yet (thefieldsobject is built beforemodel(…, { namespace })associates one). So the codec returns the bare name and a genericqualifyTypeNameapplies the prefix once the namespace is known — for both the PSL and TS paths, at the same stage (the PSL resolver moved onto it too, with zero fixture drift). This is what lets non-publicschemas work without a fence.How it works
The author declares an enum as a
constand references it viapg.enum(handle)in a column — there is no separate registration step; the entity is collected from that usage at build time (harvest-from-usage), which is also how it picks up the field's namespace.nativeEnum(name, …values).map(typeName)builds a handle:nameis the entity name (theentries.native_enum/entries.valueSetkey),.map()overrides the Postgres type name (PSL's@@map), defaulting toname.pg.enum(handle)returns a deferred column descriptor carrying a generic, family-blindentityRef({ entityKind, entityName, entity }) on the frameworkColumnTypeDescriptor— it computes nothing namespace-dependent at builder-call time.build-contractvisits each field with its model's now-known namespace and, for a deferred column, generically: schema-qualifies the type name, harvests the entity into that namespace'sentries.<kind>(+ derives its value-set, reusing move 1), and wires the column'svalueSetref. It names no entity kind — it readsentityRefoff the descriptor. Two different enums sharing a name in one namespace are rejected, matching PSL'sPSL_DUPLICATE_DECLARATION.Proof
PSL↔TS parity, both directions: an in-memory
ContracttoEqual(ts-psl-parity.real-packs) and an emittedcontract.jsonbyte-equality fixture (parity/native-enum/), each covering the default schema and a named schema (auth, the@@map-distinct case). Full gate green — typecheck 143/143,fixtures:checkzero drift,lint:casts1031,lint:framework-vocabulary906 (the framework stays family-blind), all three test suites.Follow-ups / known asymmetries
type.pg.enumpath so reference-taking type-constructors work for every pack (would fold the bespokepg.enum(handle)back onto the generic path).nativeEnumdeclared but never used is absent from the contract, whereas an unused PSL block still lowers a value-set (minor, inert-only — a noted follow-up).Shaping + dispatch plan:
projects/native-postgres-enums/slices/native-enum-ts-authoring/spec.md.🤖 Generated with Claude Code
Summary by CodeRabbit
nativeEnum(...),NativeEnumHandle, andpg.enum(...)columns.