Repository navigation
Native Postgres enums: external Supabase types as typed value unions - #906
Conversation
End-to-end rewrite reflecting the settled design: - native_enum entity is the authoring source of permitted values AND the managed CREATE TYPE lifecycle (RLS DiffableNode template). - It derives the standalone value-set (the TML-2952/2953 canonical structure); native does not fork the typing/enforcement machinery, it reuses it. - Column: nativeType + the native_enum codec (gives the ::type cast) + a valueSet ref for typing (the shared machinery). No CHECK; the type enforces. - Authoring via field.namedType(handle); the handle carries the native realization; lowering branches check vs native. - Parallel-safe with TML-2952/2953 (reuses machinery that exists today; enum codecs are identity, so no hard dependency — file-level rebase coordination). - Settled the prior open decisions (slot name native_enum; column→value-set coordinate ref, not the legacy typeRef/storage.types codec-alias seam). Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
Correct the inverted thesis. A native Postgres enum is a distinct database type (persistence plane), not a domain enum. Two directions: - externally-managed / adopted (primary): the type is the source; PN derives the value-set (typing) and a db.enums accessor (members where name=value) from it. No authored domain enum. - authored (phase 2): a user may realize a domain enum as a native type (domain -> storage); only here is native a persistence strategy for a domain enum. Ripples fixed: db.enums derived from the type (external) / domain enum (authored); the #5 spine and R2/R4 no longer assume a domain enum always exists. Technical model unchanged. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
Add specs/authoring-design.md as the design of record: native enum is a distinct Postgres type (pack-contributed native_enum entity, RLS template) consumed via a pg.enum(ref) codec whose dynamic per-instance nativeType drives the ::type cast. The entity's members derive the value-set; typing, db.enums, and enforcement reuse the shared value-set machinery. No CHECK. Reconcile spec.md to that design throughout: pg.enum@1 + typeParams.ref on the column, PostgresNativeEnum DiffableNode, db.enums always sourced from the native_enum members (external and authored alike), and the two enum kinds (check-realized via enumType, native via native_enum) sharing one downstream value-set path. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…rect read model Add specs/querying-design.md and specs/migration-design.md as the designs of record for the read/query and migration paths, each grounded in the real implementation (every cited file:line verified). Querying: SQL/ORM value-union typing already lands via StorageColumnTypes (TML-2886) reading the storage value-set — no new typing code; the domain FieldOutputTypes path is not involved. Runtime member access is a NEW Postgres-only db.native_enums facade root (sibling of db.enums, reusing EnumAccessor); db.enums stays domain-only and is untouched. The one hard new piece is the per-column ::type cast — renderTypedParam reads a static per-codecId nativeType today, so the resolved type name must ride the lowered parameter. Migration: native_enum is a PostgresNativeEnum DiffableNode on the RLS role/policy template — projected into PostgresSchemaIR, diffed by the generic differ, planned into CREATE TYPE / DROP TYPE / ADD VALUE / RENAME VALUE; remove and reorder are refused. external grade drops Supabase enums from the planner input before the diff (no DDL). No custom seams; the dead TML-2853 residue (postgres-enum-type-schema.ts, dead ISSUE_KIND_ORDER keys) is deleted, not reclaimed. Reconcile spec.md + authoring-design.md to the corrected read model (db.native_enums, not db.enums; correct TML-2886/2952 attribution; delete-don't-reclaim). Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
… claim Delete the one dead fragment of the removed TML-2853 native enum: postgres-enum-type-schema.ts (the PostgresEnumTypeSchema arktype validator). It is unimported and has no registration site — confirmed via repo-wide grep; verified green with typecheck + build + lint:deps. Also drop the stale comment in namespace-entity-kinds.test.ts that pointed at the now-deleted file (no test behavior change). The ISSUE_KIND_ORDER keys (type_missing / type_values_mismatch / enum_values_changed) turned out to be LIVE generic infrastructure — used by mapIssueToCall, the isMissing predicate, and the SQL-family verifier's EnumValuesChangedIssue — not residue. Correct spec.md and migration-design.md, which had wrongly listed them as deletable; they are kept and reused. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
… settled decisions Rewrite plan.md from scratch via the Drive process: the MVP is external Supabase native enums (represented, typed, surfaced via db.native_enums), with ZERO migration machinery — three vertical slices. PN-managed create/delete/add- value becomes a separate, deferred effort (may never be built). Reconcile all four specs to the decisions settled this session, several of which are grounded in fresh code verification: - Variadic PSL blocks already ship (variadicParameters; the SQL enum block is a live instance) — the native_enum block reuses them verbatim, NOT new. - The ::type cast is the adapter's existing nativeType mechanism; the only gap is that codecRefForStorageColumn drops the per-column nativeType today — stamp it on the CodecRef, renderTypedParam prefers it. Small, local; no longer framed as a hard/new piece. - All inference is `managed` (no external-adopted grade, no promote concept). - Migration diffing is order-aware: only a pure suffix-append -> ADD VALUE is accepted; rename/remove/reorder refused. RENAME VALUE dropped (three ops). - Members are always authored key = value (no shorthand). - db.native_enums accessor types from BOTH emitted and no-emit paths. - Supabase enters via the extension declaring its enums in contract.prisma. All open questions across the four docs are now closed. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…lapse to 2 slices Correct the native-enum model to what it actually is: pg.enum is a parameterized codec exactly like vector(N). Its typeParams carry the enum's values (baked from the native_enum block at authoring time); typing is parameterized-codec typing (the codec's renderOutputType is the value union) for both emitted and no-emit. There is NO value-set on the native path (that is the check-enum path), and no dependency on the enum-typing refactor (TML-2952/2953). Strip the value-set from spec.md throughout (the model, components, at-a-glance, requirements, the storage-invariant section, and one "Alternatives" entry that was actually the chosen design). Reframe "why the value-set lives in storage" as "why the native_enum entity lives in storage." Plan: collapse to 2 slices — db.native_enums folded into slice 1 (no value in deferring the runtime accessor). Add the slice-1 spec (native-enum-representation-typing-and-access). Linear skipped per operator. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…no value-set)
Reconcile the three design-of-record docs to what spec.md/plan.md now say: the
native path is the pg.enum parameterized codec (the vector(N) mechanism), not a
value-set.
authoring-design: §2.5 "derived value-set" → "No value-set"; §3 the codec's
params carry the enum's values (baked from the block at authoring) rather than an
entity ref; §3.3 resolution is postgres-specific field lowering, not the generic
scalar-only type-constructor template; §5 typing is renderOutputType (the
value-union), emit + no-emit; example JSON drops the valueSet entry + column
valueSet ref (typeParams: { values }); §8 pipeline updated.
querying-design: §2 rewritten to parameterized-codec typing (codec-refined
StorageColumnTypes branch for emit; CodecChannelType for no-emit), dropping the
value-set/StorageValueSet path and the TML-2952 dependency framing.
migration-design: fix the storageHash section's stale link to the renamed
spec.md section.
No value-set on the native path anywhere; no dependency on TML-2952/2953.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Now that TML-2952 is merged (this branch is rebased onto main), native-enum
typing is the value-set → codec path — the SAME machinery check enums use, made
enum-agnostic by 2952 ("the domain enum is no longer a typing input"). A native
column carries a valueSet ref (to the value-set derived from the native_enum
entity) and types as the literal union via computeColumnType → renderValueSetType
→ renderValueLiteral, with ZERO new typing code. This supersedes the
parameterized-codec (renderOutputType) framing across all the docs.
- spec.md, authoring-design.md, querying-design.md, plan.md: value-set drives
typing; column = { codecId, valueSet ref, nativeType } (no typeParams:{values},
no CHECK); the native_enum entity derives a StorageValueSet; the pg.enum codec
is a param-free text codec (encode/decode + renderValueLiteral + per-column
nativeType). Alternatives re-flipped (parameterized-codec is the rejected one).
- No-emit column typing is the one gap — deferred to TML-2960 (filed, assigned).
- slice-1 spec: rewritten to value-set + a 5-dispatch test-first plan
(D1 entity+value-set → D2 column+emit-typing → D3 cast → D4 db.native_enums
→ D5 e2e).
migration-design.md unchanged (deferred managed path, already value-set-neutral).
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
The native_enum PSL block lowers to a storage native_enum entity (kind postgres-enum: typeName, ordered members, optional control) and derives a StorageValueSet, both round-tripping through the Postgres serializer + validator. Reuses the RLS policy/role entity template — no custom seams. Value-set derivation rides a new GENERIC hook: AuthoringEntityTypeFactoryOutput gains an optional deriveValueSet(entity); the family interpreter's generic extension-block pass folds any hook-derived value-set into entries.valueSet, naming no target discriminator. The Postgres native_enum descriptor supplies deriveValueSet typed against PostgresNativeEnum — no cast, no duck-type. Members are authored key = "value" (bare rejected); duplicate member values and domain-enum name collisions are diagnosed. Also fixes two latent bugs surfaced here: the extension-entity diagnostics sink was silently dropped, and a co-namespace valueSet could be clobbered on merge. Gates: lint:casts delta 0; typecheck, build, lint:deps, fixtures:check green; postgres, contract-psl, framework-components package tests green. TS authoring mirror (helpers.nativeEnum) deferred to a later increment — it needs new ContractDefinition machinery; this lands the PSL declaration path. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
Correct querying-design §2.2 and authoring-design §5: post-TML-2952, FieldOutputTypes is NOT "not involved" — it resolves the native union from the storage column's value-set via sqlEmission.resolveFieldValueSet, and the ORM (db.model.findOne) reads FieldOutputTypes first. So both emitted maps — StorageColumnTypes (raw SQL builder) and FieldOutputTypes (ORM) — get the union from the same value-set; what's gone is only the old domain-enum override (domainEnumLookup, deleted by 2952). No field-typing code is added either way. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
… (Postgres)
A PSL field `foo pg.enum(SomeNativeEnum)` lowers to a column carrying
{ codecId: 'pg/enum@1', valueSet ref -> the enum's derived value-set, nativeType },
no CHECK — and types as the value union in the query builder, ORM, and emitted
contract via the existing post-2952 value-set -> codec machinery (zero new
emitter typing code).
- pg/enum@1: a text codec (passthrough + renderValueLiteral); distinct from
pg/text@1 for identifiability + the future managed phase.
- pg.enum(Ref) resolves via a NEW generic entityRefTypeConstructor mechanism
(framework-components): a field-type registry for calls that resolve an arg
against another document-local entity. Postgres contributes resolvePgEnumRef;
the family layer names no target. The field is optional on AuthoringContributions
(no external break).
- interpreter: the extension-block-lowering pass now runs before model/field
resolution so pg.enum(Ref) can resolve against an already-lowered native_enum
entity. Behaviour-preserving move (no backward dependency; RLS policy/role
unaffected; ok/notOk outcomes unchanged).
- two latent bug fixes: buildStorageColumn now reads a field-descriptor value-set
(was dropped for non-domain-enum fields); CHECK auto-generation skips columns
whose value-set is native-type-enforced (valueSetEnforcement, defaulting to
'check' so existing check-enums keep their CHECK).
Gates: lint:casts delta 0; typecheck, build, lint, lint:deps, fixtures green;
postgres/contract-psl/contract-ts/framework-components/emitter/sql-builder/
query-builder/sql-orm-client package tests green; integration + e2e green
(only the pre-existing config-loader macOS path flake red).
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
… (Postgres)
A bound parameter for a native-enum column (pg.enum(Ref), codec pg/enum@1) must
be cast to the enum's Postgres type — $N::aal_level — but the per-column native
type was dropped before rendering, so the renderer fell back to the codec's
static meta ('text', which is inferrable) and emitted a bare $N.
Carry the column's own native type through to the cast:
- CodecRef gains an optional nativeType (additive; absent for columns with no
independent native type, where renderers keep using the codec's static meta).
- codecRefForStorageColumn stamps columnDef.nativeType onto every returned ref;
frozenCodecRef preserves it when freezing the ref into the AST (it reconstructs
the ref field-by-field and would otherwise strip it back out).
- renderTypedParam prefers the ref-carried nativeType over the static per-codec
meta; both ParamRef render sites pass it.
Existing columns are unaffected: fixtures:check regenerates identically — a
column whose native type matches its codec's static meta renders the same cast
as before.
Gates: typecheck 143/143; framework-components build; sql-relational-core and
adapter-postgres tests green; fixtures:check clean; lint:casts delta 0; 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]>
A new Postgres-only client root db.native_enums exposes native Postgres enum members at runtime — a sibling of db.enums. db.native_enums.<ns>.<Name> gives .values/.names/.members/.has/.nameOf/.ordinalOf, resolved per namespace. - buildNamespacedNativeEnums(storage) walks storage.namespaces[ns].entries .native_enum and builds one EnumAccessor per entity (name === value for native enums). Zero framework change: the createEnumAccessor primitive is reused unmodified. - Attached in the Postgres client facade only (PostgresClient and PostgresTransactionContext, built once, spread into the client and each tx). db.enums, and the sqlite/mongo runtimes, are untouched. - NamespacedNativeEnums<TContract> is intentionally non-literal (an open Record<string, EnumAccessor> per namespace): the storage plane isn't type-emitted per-entity, so per-name literal accessor typing is deferred and composes with the emitted/no-emit value-set typing boundary. Runtime is correct for both emitted and no-emit contracts; the column value-union typing (the primary type surface) is already literal. Gates: postgres 81/81; typecheck 143/143; lint:casts delta 0; lint:deps clean; fixtures:check clean (runtime-only). sqlite/mongo/db.enums confirmed untouched. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…he PSL vertical The TS authoring mirror needs generic ContractDefinition pack-entity attachment (route author-declared, namespace-scoped pack entities into entries.<kind>) — shared with RLS role/policy, and unbuilt. It's unused by the MVP's PSL/Supabase path, so it moves out of the representation slice into its own deferred slice, tracked as TML-2965. Also record the shipped db.native_enums accessor typing: an open Record<string, EnumAccessor> per namespace (runtime-correct for emit + no-emit); per-name literal accessor typing composes with the TML-2960 value-set boundary. plan.md: representation slice scoped to PSL; new deferred TS-authoring slice; tracker + sequencing updated. slice spec: scope, done-conditions, and dispatch plan aligned to PSL, with the delivered dispatches marked done by commit hash. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
Record the concrete slice-2 shape: aal_level (aal1/aal2/aal3) on a new AuthSession model in the Supabase extension, demonstrated in the supabase example. A real executed example is a stronger emit-then-consume proof than a synthetic fixture, so it subsumes the planned D5 fixture. Notes the external-type seed requirement (CREATE TYPE in bootstrapSupabaseShim, since PN emits no DDL) and the schema-qualified-cast check for a non-public enum type. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…n nativeType The nativeType-forwarding change (fbb9609) made codecRefForStorageColumn carry the column's nativeType on every CodecRef, but only the relational-core tests were updated at the time. These ~29 whole-shape assertions in sql-builder, sql-orm-client, and sql-runtime still expected the old ref shape and failed once test:packages was run. Where a test builds the ref from a fixture column, the helper now reads nativeType off that same column (via ifDefined); inline refs get the field directly. Assertions stay toEqual (no weakening to toMatchObject). test:packages: the ~29 nativeType mismatches are gone; remaining reds are the pre-existing config-loader macOS-path flakes and a cli control-api ordering flake (28/28 in isolation) — none from this change. typecheck 143/143; lint:casts delta 0; 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]>
…lic schemas A pg.enum(Ref) column took the bare @@Map type name as its nativeType (e.g. aal_level). For a native enum in a non-public Postgres schema — the primary case, Supabase's auth schema — the reference must be schema-qualified (auth.aal_level), or two things break: the $N::type cast fails (`type "aal_level" does not exist` under the default search_path) and db verify reports a spurious type_mismatch (contract aal_level vs Postgres format_type() auth.aal_level). Qualify the column's nativeType by its namespace. namespaceId is the schema name (PostgresSchema.qualifyTable renders "auth"."sessions"), and the default is public. The one generic chokepoint holding both the resolution and the namespace is resolveEntityRefTypeConstructorCall; it now forwards namespaceId to the ref resolver (an additive optional param on the framework resolve signature), and the Postgres resolvePgEnumRef qualifies typeName unless the namespace is the default (public) or the unbound/late-bound sentinel — mirroring the qualify vs don't-qualify split PostgresSchema already uses for tables. The public-default id moves to a leaf constant so the family layer never hardcodes it. Qualifying the single nativeType field fixes both consumers at once: renderTypedParam splices it verbatim (-> $N::auth.aal_level) and db verify compares it to format_type()'s output (-> match). public/default stays bare. Gates: psl-pg-enum-column + sql-renderer cast tests (qualified for auth, bare for public); typecheck 143/143; lint:casts delta 0; 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]>
…ive_enums on the Supabase client Declares the first real external native enum: the Supabase extension contract gets native_enum AalLevel (Postgres type auth.aal_level, members aal1/aal2/aal3) and an AuthSession model (auth.sessions) with aal pg.enum(AalLevel)?. Both are external — PN emits no DDL — so bootstrapSupabaseShim seeds CREATE TYPE auth.aal_level + auth.sessions directly, mirroring the auth.users seed. The supabase example proves the capability end-to-end against real Postgres: - reads auth.sessions.aal as the value union 'aal1'|'aal2'|'aal3'|null, typed off the emitted extension contract (not a hand-built type); - reaches the members at runtime via db.asServiceRole().supabase.native_enums .auth.AalLevel; - runs a where aal = $1 query that binds the $N::auth.aal_level cast and executes. Supporting wiring: - db.native_enums on the Supabase client's .supabase root, reusing buildNamespacedNativeEnums (now re-exported from @prisma-next/postgres/runtime) over the extension contract's storage. - pg/enum@1 added to the postgres codec-type-map so an enum value resolves as a typed bound parameter in where()/insert. Gates: example-supabase + extension-supabase green (real Postgres via @prisma/dev); fixtures:check clean; typecheck 143/143; lint:casts delta 0; lint:deps clean; test:packages green (only pre-existing config-loader macOS-path flakes). Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…fix it exposed The real Supabase example demonstration exposed that slice 1 was incomplete for non-public schemas (the cast + db verify used the bare type name). Records the fix (qualify nativeType by namespace) and the db.native_enums-on-Supabase wiring as the delivered content of slice 2. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThis PR adds Postgres native enum ( ChangesPostgres Native Enum Feature
Estimated code review effort: 4 (Complex) | ~75 minutes Sequence Diagram(s)sequenceDiagram
participant Test as native-enum-session.integration.test
participant Queries as session-queries.ts
participant Db as SupabaseInternalDb
participant Renderer as sql-renderer.ts
participant Postgres as Postgres
Test->>Queries: findSessionsByAal(db, 'aal2')
Queries->>Db: db.sql.auth.sessions query
Db->>Renderer: renderParamRef(typeParams)
Renderer->>Renderer: nativeTypeFor('pg/enum@1', typeParams)
Renderer->>Postgres: SELECT ... WHERE aal = $1::auth.aal_level
Postgres-->>Db: rows
Db-->>Queries: rows
Queries-->>Test: matching sessions
Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
packages/3-targets/3-targets/postgres/src/core/postgres-contract-serializer.ts (1)
149-172: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConsider consolidating the repeated per-entity-kind serialize loops.
tablesOut/valueSetOut/roleOut/policyOut/nativeEnumOutare now five copies of the same "iterate + serializeJsonObject" pattern. A small helper (e.g.serializeEntries(ns.table)) would remove the duplication and make adding future entity kinds a one-liner.♻️ Proposed consolidation
+ private serializeEntries<T>(entries: Record<string, T>): Record<string, JsonObject> { + const out: Record<string, JsonObject> = {}; + for (const [name, value] of Object.entries(entries)) { + out[name] = this.serializeJsonObject(value); + } + return out; + } + private serializePostgresNamespace(ns: PostgresSchema, isUnboundSlot: boolean): JsonObject { - const tablesOut: Record<string, JsonObject> = {}; - for (const [tableName, table] of Object.entries(ns.table)) { - tablesOut[tableName] = this.serializeJsonObject(table); - } - const valueSetEntries = ns.valueSet; - const valueSetOut: Record<string, JsonObject> = {}; - if (valueSetEntries !== undefined) { - for (const [valueSetName, valueSet] of Object.entries(valueSetEntries)) { - valueSetOut[valueSetName] = this.serializeJsonObject(valueSet); - } - } - const roleOut: Record<string, JsonObject> = {}; - for (const [roleName, role] of Object.entries(ns.role)) { - roleOut[roleName] = this.serializeJsonObject(role); - } - const policyOut: Record<string, JsonObject> = {}; - for (const [policyName, policy] of Object.entries(ns.policy)) { - policyOut[policyName] = this.serializeJsonObject(policy); - } - const nativeEnumOut: Record<string, JsonObject> = {}; - for (const [nativeEnumName, nativeEnum] of Object.entries(ns.nativeEnum)) { - nativeEnumOut[nativeEnumName] = this.serializeJsonObject(nativeEnum); - } + const tablesOut = this.serializeEntries(ns.table); + const valueSetOut = ns.valueSet !== undefined ? this.serializeEntries(ns.valueSet) : {}; + const roleOut = this.serializeEntries(ns.role); + const policyOut = this.serializeEntries(ns.policy); + const nativeEnumOut = this.serializeEntries(ns.nativeEnum);🤖 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-targets/3-targets/postgres/src/core/postgres-contract-serializer.ts` around lines 149 - 172, The serializePostgresNamespace method repeats the same iterate-and-serialize pattern for tables, value sets, roles, policies, and native enums. Refactor this into a shared helper in PostgresContractSerializer (for example, a serializeEntries-style method) that takes a record and returns the serialized JsonObject map, then use it for each entity kind to remove duplication and make future additions a one-liner.
🤖 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/4-lanes/relational-core/src/codec-ref-for-column.ts`:
- Around line 41-47: Replace the bare `instanceParams as JsonValue` cast in
`codec-ref-for-column` with the same `blindCast` pattern used in the sibling
branch, using the existing cast helper from `@prisma-next/utils/casts`. Update
the `hasParamKeys` return path in `codec-ref-for-column` so both branches use
consistent, guideline-compliant casting and keep the `codecId`, `typeParams`,
and `nativeType` shape unchanged.
In `@packages/3-targets/3-targets/postgres/src/core/authoring.ts`:
- Around line 136-145: The local snakeCase helper in authoring.ts is duplicating
behavior that already exists in applyNaming(..., 'snake_case') and can diverge
on acronym runs. Replace this second implementation by reusing the canonical
snake_case logic from the shared naming path, or extract a single shared helper
used by both the PSL and TS mirror code so typeName generation stays
byte-identical.
---
Nitpick comments:
In
`@packages/3-targets/3-targets/postgres/src/core/postgres-contract-serializer.ts`:
- Around line 149-172: The serializePostgresNamespace method repeats the same
iterate-and-serialize pattern for tables, value sets, roles, policies, and
native enums. Refactor this into a shared helper in PostgresContractSerializer
(for example, a serializeEntries-style method) that takes a record and returns
the serialized JsonObject map, then use it for each entity kind to remove
duplication and make future additions a one-liner.
🪄 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: 82a2634a-a6c8-49f9-86d9-c32d0541d58b
⛔ Files ignored due to path filters (6)
projects/native-postgres-enums/plan.mdis excluded by!projects/**projects/native-postgres-enums/slices/native-enum-representation-typing-and-access/spec.mdis excluded by!projects/**projects/native-postgres-enums/spec.mdis excluded by!projects/**projects/native-postgres-enums/specs/authoring-design.mdis excluded by!projects/**projects/native-postgres-enums/specs/migration-design.mdis excluded by!projects/**projects/native-postgres-enums/specs/querying-design.mdis excluded by!projects/**
📒 Files selected for processing (64)
examples/supabase/src/session-queries.tsexamples/supabase/test/native-enum-session.integration.test.tspackages/1-framework/1-core/framework-components/src/control/control-stack.tspackages/1-framework/1-core/framework-components/src/exports/authoring.tspackages/1-framework/1-core/framework-components/src/shared/codec-types.tspackages/1-framework/1-core/framework-components/src/shared/column-spec.tspackages/1-framework/1-core/framework-components/src/shared/framework-authoring.tspackages/1-framework/1-core/framework-components/test/control-stack.test.tspackages/1-framework/3-tooling/cli/test/config-types.test.tspackages/2-mongo-family/2-authoring/contract-psl/test/provider.test.tspackages/2-mongo-family/2-authoring/contract-ts/test/config-types.test.tspackages/2-sql/1-core/contract/test/namespace-entity-kinds.test.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-psl/test/fixtures.tspackages/2-sql/2-authoring/contract-ts/src/build-contract.tspackages/2-sql/2-authoring/contract-ts/test/config-types.test.tspackages/2-sql/3-tooling/emitter/test/emitter-hook.storage-column-types.test.tspackages/2-sql/4-lanes/relational-core/src/ast/types.tspackages/2-sql/4-lanes/relational-core/src/codec-ref-for-column.tspackages/2-sql/4-lanes/relational-core/test/codec-descriptor-registry.test.tspackages/2-sql/4-lanes/relational-core/test/codec-ref-for-column.test.tspackages/2-sql/4-lanes/sql-builder/test/native-enum-column.field-output.test-d.tspackages/2-sql/4-lanes/sql-builder/test/runtime/field-proxy.test.tspackages/2-sql/5-runtime/test/same-bare-table-name.test.tspackages/3-extensions/postgres/src/exports/runtime.tspackages/3-extensions/postgres/src/runtime/native-enums.tspackages/3-extensions/postgres/src/runtime/postgres.tspackages/3-extensions/postgres/test/postgres.test.tspackages/3-extensions/sql-orm-client/test/filters.test.tspackages/3-extensions/sql-orm-client/test/model-accessor.test.tspackages/3-extensions/sql-orm-client/test/mutation-include-read-back-namespace.test.tspackages/3-extensions/sql-orm-client/test/native-enum.field-output.test-d.tspackages/3-extensions/sql-orm-client/test/query-plan-mutations.test.tspackages/3-extensions/sql-orm-client/test/query-plan-select.test.tspackages/3-extensions/sql-orm-client/test/repository.test.tspackages/3-extensions/sql-orm-client/test/where-binding-nested-namespace.test.tspackages/3-extensions/supabase/src/contract/contract.d.tspackages/3-extensions/supabase/src/contract/contract.jsonpackages/3-extensions/supabase/src/contract/contract.prismapackages/3-extensions/supabase/src/runtime/supabase.tspackages/3-extensions/supabase/test/supabase-bootstrap.tspackages/3-extensions/supabase/test/supabase-facade.test.tspackages/3-targets/3-targets/postgres/src/core/authoring.tspackages/3-targets/3-targets/postgres/src/core/codec-ids.tspackages/3-targets/3-targets/postgres/src/core/codec-type-map.tspackages/3-targets/3-targets/postgres/src/core/codecs.tspackages/3-targets/3-targets/postgres/src/core/descriptor-meta.tspackages/3-targets/3-targets/postgres/src/core/entity-kinds.tspackages/3-targets/3-targets/postgres/src/core/namespace-ids.tspackages/3-targets/3-targets/postgres/src/core/postgres-contract-serializer.tspackages/3-targets/3-targets/postgres/src/core/postgres-enum-type-schema.tspackages/3-targets/3-targets/postgres/src/core/postgres-schema.tspackages/3-targets/3-targets/postgres/src/core/postgres-validators.tspackages/3-targets/3-targets/postgres/src/core/schema-ir/postgres-native-enum.tspackages/3-targets/3-targets/postgres/test/codec-render-value-literal.test.tspackages/3-targets/3-targets/postgres/test/codec-type-map.pg-enum.test-d.tspackages/3-targets/3-targets/postgres/test/postgres-contract-serializer.test.tspackages/3-targets/3-targets/postgres/test/postgres-native-enum.test.tspackages/3-targets/3-targets/postgres/test/psl-native-enum-authoring.test.tspackages/3-targets/3-targets/postgres/test/psl-pg-enum-column.test.tspackages/3-targets/6-adapters/postgres/src/core/sql-renderer.tspackages/3-targets/6-adapters/postgres/test/sql-renderer.cast-policy.test.ts
💤 Files with no reviewable changes (1)
- packages/3-targets/3-targets/postgres/src/core/postgres-enum-type-schema.ts
| return hasParamKeys | ||
| ? { codecId: instance.codecId, typeParams: instanceParams as JsonValue } | ||
| : { codecId: instance.codecId }; | ||
| ? { | ||
| codecId: instance.codecId, | ||
| typeParams: instanceParams as JsonValue, | ||
| nativeType: columnDef.nativeType, | ||
| } | ||
| : { codecId: instance.codecId, nativeType: columnDef.nativeType }; |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win
Bare as cast — use blindCast for consistency.
instanceParams as JsonValue is a bare cast; the sibling branch just below (line 52-55) already uses blindCast<JsonValue, '...'>(...) for the identical cast. As per coding guidelines, "No bare as in production code. Use blindCast<T, "Reason"> or castAs<T> from @prisma-next/utils/casts".
🛠️ Proposed fix
return hasParamKeys
? {
codecId: instance.codecId,
- typeParams: instanceParams as JsonValue,
+ typeParams: blindCast<
+ JsonValue,
+ 'instance typeParams is a validated contract record; its values are JSON-serialisable'
+ >(instanceParams),
nativeType: columnDef.nativeType,
}
: { codecId: instance.codecId, nativeType: columnDef.nativeType };📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| return hasParamKeys | |
| ? { codecId: instance.codecId, typeParams: instanceParams as JsonValue } | |
| : { codecId: instance.codecId }; | |
| ? { | |
| codecId: instance.codecId, | |
| typeParams: instanceParams as JsonValue, | |
| nativeType: columnDef.nativeType, | |
| } | |
| : { codecId: instance.codecId, nativeType: columnDef.nativeType }; | |
| return hasParamKeys | |
| ? { | |
| codecId: instance.codecId, | |
| typeParams: blindCast< | |
| JsonValue, | |
| 'instance typeParams is a validated contract record; its values are JSON-serialisable' | |
| >(instanceParams), | |
| nativeType: columnDef.nativeType, | |
| } | |
| : { codecId: instance.codecId, nativeType: columnDef.nativeType }; |
🤖 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/4-lanes/relational-core/src/codec-ref-for-column.ts` around
lines 41 - 47, Replace the bare `instanceParams as JsonValue` cast in
`codec-ref-for-column` with the same `blindCast` pattern used in the sibling
branch, using the existing cast helper from `@prisma-next/utils/casts`. Update
the `hasParamKeys` return path in `codec-ref-for-column` so both branches use
consistent, guideline-compliant casting and keep the `codecId`, `typeParams`,
and `nativeType` shape unchanged.
Source: Coding guidelines
| // TODO(TS-mirror parity): this diverges from `applyNaming(..., 'snake_case')` | ||
| // on acronym runs. The TS mirror (`field.column(pg.enum(handle))`) must reuse ONE | ||
| // canonical snake_case so PSL and TS lower to a byte-identical contract — pick | ||
| // the single source of truth then, don't leave two implementations. | ||
| function snakeCase(name: string): string { | ||
| return name | ||
| .replace(/([a-z0-9])([A-Z])/g, '$1_$2') | ||
| .replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2') | ||
| .toLowerCase(); | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Reuse the canonical snake_case implementation instead of a second, diverging one.
The TODO already documents that this diverges from applyNaming(..., 'snake_case') on acronym runs, risking PSL vs. TS-authored contracts lowering to different typeNames for the same identifier.
Do you want me to consolidate this on the existing applyNaming snake_case implementation (or extract a single shared helper) so PSL and the TS mirror stay byte-identical?
🤖 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-targets/3-targets/postgres/src/core/authoring.ts` around lines 136
- 145, The local snakeCase helper in authoring.ts is duplicating behavior that
already exists in applyNaming(..., 'snake_case') and can diverge on acronym
runs. Replace this second implementation by reusing the canonical snake_case
logic from the shared naming path, or extract a single shared helper used by
both the PSL and TS mirror code so typeName generation stays byte-identical.
…, requirements named Rewrite both for an implementer reading cold. State the concrete design up front (the native_enum entity, derived value-set, pg.enum column, db.native_enums) instead of leading with philosophy; name the requirement each design element satisfies inline rather than leaving R1-R10 as a divorced list to reverse-engineer. Draw a hard line between shipped Phase 1 (external enums, PR #906) and the forward Phase 2 design (managed enums), and state Phase 2 concretely — the SchemaIR node, projection, order-aware diff, and three ops — rather than "follow RLS". Cut the ~6x repetition of the column shape and the settled-decisions dump; keep a compact requirements→design→proof table; alternatives last. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
| return rows[0]; | ||
| } | ||
|
|
||
| export function findSessionsByAal(db: SupabaseInternalDb, aal: 'aal1' | 'aal2' | 'aal3') { |
There was a problem hiding this comment.
This should use the actual native_enum type, not a string union. Same as for regular enums
There was a problem hiding this comment.
Done in 869f471 — the parameter is now typed from the contract: NamespacedNativeEnums<SupabaseExtensionContract>['auth']['AalLevel']['values'][number] (the accessor is literally typed as of this round, so this resolves to the union).
| * `nativeType` is the storage column's own native type (e.g. a native Postgres enum's type name), used in preference to the codec's static `meta` when a SQL renderer decides whether to cast a bound parameter. Absent when the column carries no independent native type, in which case renderers fall back to the codec's static metadata. | ||
| * |
There was a problem hiding this comment.
THIS IS SQL SPECIFIC, IT CANNOT LIVE IN THE FRAMEWORK DOMAIN
There was a problem hiding this comment.
Done in 869f471 — CodecRef.nativeType is reverted entirely; the framework ref is back to { codecId, typeParams?, many? }. The cast now reads off the codec instance: the enum column carries typeParams: { typeName } and the renderer asks the codec via a new optional nativeTypeFor hook (same delegate shape as renderValueLiteralFor). Reverting this also fixed a live bug: the ref-carried transport shadowed static meta on every column and produced spurious $N::int4/$N::bool casts on non-enum binds — a regression test now locks it.
| */ | ||
| export interface AuthoringEntityRefResolution { | ||
| readonly codecId: string; | ||
| readonly nativeType: string; |
There was a problem hiding this comment.
Same as column-spec: pre-existing family-shared authoring vocabulary (Mongo writes the same field; four pre-existing nativeType carriers in this file) — the extraction/rename decision is TML-2966. The runtime half of the leak (CodecRef.nativeType) is gone in 869f471.
| typeParams: instanceParams as JsonValue, | ||
| nativeType: columnDef.nativeType, | ||
| } | ||
| : { codecId: instance.codecId, nativeType: columnDef.nativeType }; |
There was a problem hiding this comment.
Why does codecRef carry nativeType everywhere? Shouldn't we be reading that off the codec instance?
There was a problem hiding this comment.
You were right — it shouldn't, and now it doesn't (869f471). The stamping is reverted; the per-instance type name rides the codec's own typeParams (pg/enum@1 is parameterized by { typeName }) and the renderer reads it off the codec instance via the nativeTypeFor hook. The static codec meta can't serve it (one codec id, many enum types), which is why it's an instance parameter.
| * Resolves `pg.enum(<ref>)` — a field type naming a `native_enum` block in | ||
| * the same document — against the namespace's already-lowered extension | ||
| * entities (see `namespaceExtensionEntities` threaded through PSL field | ||
| * resolution). `entities['native_enum']` is the `native_enum` entries slot | ||
| * (keyed by block name); a hit yields the `pg/enum@1` codec, the enum's | ||
| * `typeName` as the column's `nativeType`, and the block name as the | ||
| * `valueSetEntityName` — the `native_enum` entity derives a value-set of the | ||
| * same name (`deriveValueSet` on the `native_enum` entityType descriptor, | ||
| * §2.5 of authoring-design.md), so the caller builds a `valueSet` ref | ||
| * pointing at it without this resolver needing to know the ref shape. | ||
| * `valueSetEnforcement: 'native-type'` — the native Postgres enum TYPE | ||
| * enforces membership; no `CHECK` is written (authoring-design.md §5). | ||
| * | ||
| * `nativeType` is schema-qualified (`<namespaceId>.<typeName>`) when the | ||
| * enum's namespace is a real, named, non-default schema — matching what | ||
| * Postgres's `format_type()` reports for a non-`public` type, so the | ||
| * `$N::<nativeType>` cast and `db verify`'s column-type comparison both stay | ||
| * correct. The default namespace (`public`) and the unbound/late-bound | ||
| * namespace (resolved by `search_path` at runtime) both stay bare, mirroring | ||
| * `PostgresSchema.qualifyTable` / `PostgresUnboundSchema.qualifyTable`'s own | ||
| * qualify-vs-don't-qualify split for tables. |
There was a problem hiding this comment.
OMG can you write longer comments
There was a problem hiding this comment.
Trimmed in 869f471 — the resolver doc is down to the essentials (what it resolves, why the name is qualified, the public/unbound exception).
| // TODO(TS-mirror parity): this diverges from `applyNaming(..., 'snake_case')` | ||
| // on acronym runs. The TS mirror (`field.column(pg.enum(handle))`) must reuse ONE | ||
| // canonical snake_case so PSL and TS lower to a byte-identical contract — pick | ||
| // the single source of truth then, don't leave two implementations. |
There was a problem hiding this comment.
NO TODOS UNLESS THEY NAME A LINEAR TICKET ID
There was a problem hiding this comment.
Gone in 869f471 — the TODO died with the snakeCase helper it described (see the case-manipulation thread).
| function snakeCase(name: string): string { | ||
| return name | ||
| .replace(/([a-z0-9])([A-Z])/g, '$1_$2') | ||
| .replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2') | ||
| .toLowerCase(); | ||
| } |
There was a problem hiding this comment.
Why are we doing case manipulation
There was a problem hiding this comment.
We aren't anymore (869f471) — typeName defaults to the block name verbatim; @@map is the mapping mechanism (matching the RLS-template naming and @@map conventions). The snakeCase helper is deleted, which also removes the PSL/TS parity risk CodeRabbit flagged.
| // `control` is left unset here — the effective grade (`external` for the | ||
| // Supabase pack, `managed` by default) is resolved at read time via | ||
| // `effectiveControlPolicy(node.control, contract.defaultControlPolicy)`, | ||
| // exactly as `StorageTable`/`StorageColumn` leave `control` unset and rely | ||
| // on the contract-level default (see `applySpecifierDefaultControlPolicy`). |
There was a problem hiding this comment.
Not sure "do nothing" needs a five line comment
| * Postgres's default schema. `postgresTargetDescriptorMeta.defaultNamespaceId` | ||
| * is this value; a leaf constant so other Postgres-target modules (e.g. | ||
| * `pg.enum` ref resolution in `authoring.ts`) can compare against it without | ||
| * importing `descriptor-meta.ts` and creating a cycle. |
There was a problem hiding this comment.
It breaks an import cycle: authoring.ts and descriptor-meta.ts import each other, and both need the default-namespace id — a leaf constant is the standard break. The file now says so in a one-line comment (869f471).
…ativeEnums; review conventions Address the PR #906 review. Three changes, one per review theme: The cast is a codec-instance parameter. pg/enum@1 is now genuinely parameterized: an enum column carries typeParams { typeName: '<qualified>' } and the renderer asks the codec for its per-instance native type via a new optional nativeTypeFor hook on CodecDescriptor/CodecLookup (the renderValueLiteralFor delegate shape), falling back to static meta. CodecRef.nativeType is reverted entirely — the framework ref is back to { codecId, typeParams?, many? }. Only pg/enum implements the hook, which also fixes a live bug the review surfaced: the ref-carried transport shadowed static meta on EVERY column, flipping plain $N into spurious $N::int4 / $N::bool casts for non-enum binds (a regression test now locks this). StorageColumn.nativeType is unchanged (db verify / DDL read it). db.nativeEnums, typed. The accessor is camelCased (the client surface is camelCase; the entries key / PSL block stay native_enum), and now literally typed: the emitter type-emits every storage entries slot generically (literalized from the canonical serialized JSON — role/policy get typed for free), and NamespacedNativeEnums maps native_enum members through the shared enum-accessor type machinery (values: readonly ['aal1','aal2','aal3']). The shared EnumEntryValues/Names mapped types are now homomorphic so tuples stay tuples. The runtime walk is rewritten typed via isPostgresSchema (the structural PostgresStorageLike + its blindCast are gone); the example derives its parameter type from the contract instead of a hand-written union. Conventions. PostgresNativeEnum.is() static (SqlQueryError.is precedent) replaces the free type guard; typeName defaults to the block name verbatim — no case manipulation (the snakeCase helper + TODO are deleted; @@Map is the mapping mechanism, per the RLS-template and @@Map conventions); long comments trimmed; namespace-ids.ts documents the import cycle it breaks; the serializer's five per-entity-kind loops collapse into serializeEntries. Gates: typecheck 143/143; test:packages 11638 passed (3 pre-existing config-loader macOS-path flakes); extension-supabase 51/51 + example-supabase 12/12 against real Postgres (executed $1::auth.aal_level cast + literal accessor typing assertion); adapter-postgres 664+4, target-postgres 555, emitter 122; fixtures re-emitted and idempotent; lint:casts delta 0; 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]>
…ves the union Naming an enum's value type required plumbing: EnumValues<typeof Priority> (a helper import) or ['values'][number] indexed-access gymnastics, and the supabase example had fallen all the way to applying an internal generic to the raw contract type. The accessor now carries a type-only Value property (absent at runtime — the drizzle $inferSelect pattern), so the idiom is plain typeof along the same path used at runtime, for both enum kinds: type Priority = typeof db.enums.public.Priority.Value; type AalLevel = typeof db.nativeEnums.auth.AalLevel.Value; type AalLevel2 = SupabaseInternalDb['nativeEnums']['auth']['AalLevel']['Value']; Declared on ContractEnumAccessor only (the typed twin): putting it on the runtime EnumAccessor interface would force an undefined assignment or an optional marker that poisons typeof with | undefined. Emitter-independent by construction — it derives from the client's accessor types, where the emitted and no-emit paths converge. EnumValues stays exported as named sugar; the examples (demo, retail-store, supabase) all move to the new idiom. Gates: contract 197; demo 66; retail-store 55; example-supabase 12 (incl. the native Value assertion); typecheck 143/143; test:packages green minus the known config-loader macOS flakes; fixtures unchanged; lint:casts delta 0; 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]>
Resolves the overlap between the native-enums branch and 9 commits from main. Beyond the mechanical unions (export lists, serializer imports, test-input shapes), three semantic resolutions: - nativeEnums moves into PostgresStaticContext (TML-2955's client-safe static surface), built beside enums in buildPostgresStaticContext and destructured by the connected client — the accessor is now also available on the driver-free static context. - main's enumInferenceCodecs (TML-2915) is grafted into the branch's relocated extension-block-lowering pass in the PSL interpreter (the branch had moved that pass ahead of model/field resolution; main had enriched the old copy). - capabilities (now a required interpreter input, from the scalar-lists work) is supplied by the branch's native-enum authoring tests. Gates on the merged tree: build 68/68; typecheck 143/143; fixtures:check clean; test:packages, integration (1134), e2e (109) green — the handful of extra reds were 100ms/30s timeout flakes under load, each passing in isolation; the only persistent red is the pre-existing config-loader macOS path flake. lint:casts delta -1; 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]>
@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: |
size-limit report 📦
|
…res enums #906 touches examples/ and packages/3-extensions/ with the external native-enum work, so check:upgrade-coverage requires a per-PR declaration in both skill clusters. The diff is additive: native enums are opt-in, EnumValues stays exported (the .Value phantom is an optional style adoption), and db.nativeEnums is a new accessor — nothing existing breaks. Recorded as incidental in both instructions.md files (user + extension author), matching the transition's existing convention. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…file coverage The native-enum interpreter refactor (#906) dropped contract-psl below the per-file coverage threshold: psl-column-resolution.ts (the new native-enum column resolution) was under-tested, and psl-authoring-arguments.ts fell to 65% because the refactor changed which of its argument-parsing branches the existing tests exercise. Add direct unit tests for mapPslHelperArgs argument-kind parsing (string/boolean/number/stringArray, with the reject/diagnostic branches) and for the entity-ref type-constructor interpretation path. Both files now clear the per-file thresholds (statements 85 / branches 81 / functions 95); package branch coverage 80.66% -> 86.35%. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…amily-neutral #918's lint:framework-vocabulary ratchet (now on main) flagged five lines this PR added under packages/1-framework — all doc-comment prose naming family concepts (StorageColumn/computeColumnType/column.valueSet, and "native types … the SQL family's isSqlEntityRefResolution" as examples). Reword them to describe the same framework mechanism without family vocabulary, rather than raise the threshold for our own additions. Comment-only; count back to 967 = threshold. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
| * predicate is a contributor bug in the pack that registered the entity-ref type constructor, not | ||
| * a user-schema error — callers should throw, naming the constructor path. | ||
| */ | ||
| export function isSqlEntityRefResolution(payload: object): payload is SqlEntityRefResolution { |
There was a problem hiding this comment.
Partly addressed in 9989162, and I want to be honest about the residue. SqlEntityRefResolution → SqlColumnBinding and the predicate is now a real structural narrowing (no blindCast). But the parameter is still object because the framework resolve hook returns object | undefined to stay family-blind (the SQL family narrows the opaque return to its own shape) — object is the most specific family-neutral base available. I could introduce a named framework brand (e.g. EntityRefResolutionPayload) to narrow from instead of bare object, but it adds no real type safety over object. Left unresolved for your call.
… binding
Review follow-up on the native-enum authoring path (design in
projects/native-postgres-enums/specs/generic-value-set-column-binding.md).
- De-opaque the resolver: it returns a concrete SqlColumnBinding
({ codecId, typeParams?, valueSetEntityName? }) instead of the bespoke
SqlEntityRefResolution re-narrowed through a predicate; nativeType drops out
(the codec owns it via nativeTypeFor). Deletes SqlEntityRefResolution and
isSqlEntityRefResolution; psl-column-resolution derives the column nativeType
from typeParams.typeName like the renderer does.
- Sweep the five framework authoring-descriptor predicates that took `unknown`
+ a bare cast — they now narrow structurally with no cast (lint:casts -11).
- Explicit CHECK in the ContractIR: delete the codec enforcesValueSet marker
(EnforcesValueSetCodecDescriptor/providesEnforcesValueSet/codecEnforcesValueSet
and PgEnumDescriptor.enforcesValueSet). build-contract now emits a CHECK in
the authoring loop when a value set is domain-authored (enumType handle) or a
list column, and none for an entity-ref-bound (native-enum) column — decided
from the authoring path, not a marker consulted downstream.
- Keep nativeTypeFor: the renderer holds only a codec lookup and cannot
materialize a per-typeParams instance at the cast chokepoint, so the
params-level native-type delivery stays.
fixtures:check byte-identical; typecheck 143/143; lint:framework-vocabulary
967/967; target-postgres / sql-contract-psl / adapter-postgres / example-supabase
green (incl. the executed $1::auth.aal_level cast and the pg.enum no-CHECK case).
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…taFor Review pushback: a parameterized codec's native type shouldn't need a bespoke hook — resolving codec metadata is core framework machinery. Make `metaFor` params-aware (`metaFor(id, typeParams)`) so a parameterized codec computes its own metadata from its params, the same way it already computes `renderOutputType(params)`; the descriptor gains an optional `metaFor(params)` alongside. `extractCodecLookup` prefers the descriptor's params-aware meta and falls back to the static `meta` (byte-identical when typeParams is absent or the codec has no hook). The Postgres renderer now reads `metaFor(codecId, typeParams).db.sql.postgres.nativeType` in one call. Deletes the whole bolt-on: native-type-hook.ts (NativeTypeForCodecDescriptor, providesNativeTypeFor, attachNativeTypeFor, SqlCodecLookup) and its export, plus the attachNativeTypeFor wiring in the adapter. Framework stays family-blind — nativeType lives in the opaque CodecMeta the descriptor returns, never named in packages/1-framework. fixtures:check byte-identical; typecheck 143/143; lint:framework-vocabulary 967/967; lint:casts -11; target-postgres / adapter-postgres (incl. sql-renderer.cast-policy + executed $1::auth.aal_level) / sql-contract-psl / example-supabase green. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…-type hook) Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
| ...(Object.keys(valueSetOut).length > 0 ? { valueSet: valueSetOut } : {}), | ||
| ...(Object.keys(roleOut).length > 0 ? { role: roleOut } : {}), | ||
| ...(Object.keys(policyOut).length > 0 ? { policy: policyOut } : {}), | ||
| ...(Object.keys(nativeEnumOut).length > 0 ? { native_enum: nativeEnumOut } : {}), |
There was a problem hiding this comment.
wtf is this? Why isn't this just serializing the whole entries dict? How is an extension supposed to extend this further?
There was a problem hiding this comment.
Partly, and I want to be straight about the boundary. The collapse removed native_enum's specific footprint here: under Option B it is no longer serialized at all (authoring-time-only, carried non-enumerable). But the GENERIC defect you named — the serializer enumerating every entry kind by hand, so a pack can't add a serializable kind without editing it — is real (the architect graded this O1, strong-agree) and it touches every entity kind, so it is out of scope for this native-enum refactor and wants its own slice. Left open — want me to file it as a follow-up ticket?
| get nativeEnum(): Readonly<Record<string, PostgresNativeEnum>> { | ||
| return this.entries.native_enum ?? Object.freeze({}); | ||
| } |
There was a problem hiding this comment.
Wtf is this either? Why do we need this special-case getter?
There was a problem hiding this comment.
Same boundary as the serializer above. get nativeEnum() remains, but the entity it returns is now authoring-only / non-enumerable. The architect pushed back partway here (O2): the typed per-kind getters are defensible under the concrete-class IR-alphabet pattern, and the real fix is the generic serializer (O1), not deleting the getters. Deferred with O1 — left open.
…-spec # Conflicts: # skills/extension-author/prisma-next-extension-upgrade/upgrades/0.14-to-0.15/instructions.md
…odec hook Stage 1 of the review-driven native-enum collapse (design: projects/native-postgres-enums/specs/native-enum-generic-collapse.md §1). `pg.enum(Ref)` is now an ordinary parameterized type-constructor whose argument is a resolved entity reference — declared via `entityRefArg` on the type-constructor descriptor and converted to column params by a codec-owned `columnFromEntity(entity, namespaceId)` hook, structurally identical to `vector(1536)`. Deletes the bespoke `entityRefTypeConstructor` framework kind (type, AuthoringContributions slot, predicate, collision wiring), `resolvePgEnumRef`, `SqlColumnBinding` (+ predicate + entry point), and the interpreter's `'typeName'` knowledge — that key now lives only in the codec, killing the H1 layering leak. Pure refactor — emitted contract byte-identical (fixtures:check clean). The entity-ref types leaving the framework drop lint:framework-vocabulary 967→906; typecheck 143/143; lint:casts steady (-11, new casts are test-only/exempt); target-postgres / sql-contract-psl / adapter-postgres / example-supabase green (incl. the executed $1::auth.aal_level cast; the lone red was a 100ms-timeout flake, green in isolation). vector(1536) still resolves through the one kind. Stages 2 (Option B: value-only members + emission removal) and 3 (F01/F06/F07) follow. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…ot emission
Stage 2 of the native-enum collapse (design §2 / F02).
- Option B: a native-enum member is a value, not a name→value pair (matching
`CREATE TYPE … AS ENUM ('a','b')`). `PostgresNativeEnum.members` is now
`readonly string[]`; `db.nativeEnums.members`/`names`/`Value` are value-keyed.
PSL `memberName = "value"` still parses (name used only for dup-checking).
- `db.nativeEnums` types off the generic `entries.valueSet` surface (the same one
`db.enums` and column typing use), not the raw `native_enum` entity slot.
Deletes `literalizeSerializedEntriesSlot` and the all-slots emission loop — the
review found three of its four slots (valueSet/role/policy) were unread dead
weight bloating every RLS contract's .d.ts; `valueSet` now gets one dedicated
typed block.
- F02: `db.nativeEnums` reads plain contract data, so a `validateContract`'d JSON
contract yields populated accessors (previously silently empty via class
getters). Test added.
- Hash self-consistency: `native_enum` is authoring-time-only (never serialized;
its values live via the derived valueSet), so it's carried non-enumerable on
the schema — like `kind` — so the storage hash matches the serialized JSON.
Its type name is still hashed via each column's `typeParams`.
Emitted output changes as intended (fixtures regenerated): the raw native_enum
slot leaves contract.d.ts/json (+ storageHash update) and members go value-only;
a benign alphabetical valueSet reorder in .d.ts. No column-type or lost-value-set
drift. typecheck 143/143; lint:framework-vocabulary 906/906; lint:casts -11;
emitter/target-postgres/contract-psl/adapter-postgres/example-supabase green.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Stage 3 of the native-enum collapse — the independent review-finding fixes. - F01: drop the inert `field.many` disjunct from the CHECK-emission gate (build-contract.ts). A native-enum array is a Postgres array of the enum type; Postgres enforces element membership, so the CHECK was inert. Domain/text-backed value sets (scalar OR array) still get their CHECK via `storageValueSetRef`. Adds tests: domain-enum array still checked; native-enum scalar and array get no CHECK. - F06: single-source the default schema — `resolve-ddl-schema.ts`, `verify-postgres-namespaces.ts`, and `operations/dependencies.ts` now import `DEFAULT_NAMESPACE_ID` instead of hardcoding `'public'`. - F07: split the run-on `metaFor` comment in sql-renderer.ts and anchor each half to the code it explains. typecheck 143/143; lint:framework-vocabulary 906/906; lint:casts -11; fixtures:check zero drift; sql-contract-ts / target-postgres / adapter-postgres / example-supabase green. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
wmadden
left a comment
There was a problem hiding this comment.
A couple of cosmetic comments. This is looking much better
| if (typeof value !== 'object' || value === null) return false; | ||
| if (!('kind' in value) || value.kind !== 'entity') return false; | ||
| if (!('discriminator' in value) || typeof value.discriminator !== 'string') return false; | ||
| if (value.discriminator.length === 0) return false; | ||
| if (!('output' in value)) return false; | ||
| const output = value.output; | ||
| if (typeof output !== 'object' || output === null) return false; | ||
| const factory = 'factory' in output ? output.factory : undefined; | ||
| const template = 'template' in output ? output.template : undefined; | ||
| return typeof factory === 'function' || template !== undefined; |
There was a problem hiding this comment.
Wtf is all this? Change the input type so it's not unknown and this won't be so difficult. You don't need to check every property exists on the damn thing
| // `entityTypes` only — these are user-facing helper paths that PSL must | ||
| // resolve unambiguously. `pslBlockDescriptors` is an internal framework | ||
| // index consumed by parser and printer dispatch, not a user-facing helper | ||
| // path; the natural authoring pattern is the same path key in | ||
| // `entityTypes` and `pslBlockDescriptors` for a single contribution. The | ||
| // block→factory link is enforced by `assertPslBlocksHaveFactories` via the | ||
| // discriminator string, not by path. |
| // No early diagnostics checkpoint here (unlike after the field-resolution | ||
| // loop below): this pass runs early specifically so its output | ||
| // (`namespaceExtensionEntities`) is available to field resolution, and an | ||
| // immediate return would also discard any diagnostics already present from | ||
| // symbol-table seeding (`input.seedDiagnostics`) without ever reaching | ||
| // field resolution to accumulate its own. The first real checkpoint after | ||
| // model/field resolution below catches failures from this pass too. |
There was a problem hiding this comment.
what it this wall of texxt?
| // `valueSet` is merged specifically (rather than let `entities` overwrite | ||
| // it wholesale): `nsInput.entries.valueSet` may already carry PSL `enum` | ||
| // block-derived value-sets (built in `buildSqlContractFromDefinition` from | ||
| // `definition.enums`, independently of this pass), and `entities.valueSet` | ||
| // may carry `deriveValueSet`-hook-derived ones — a namespace authoring both | ||
| // an `enum` and a value-set-deriving extension entity needs both to survive. | ||
| // Name collisions between the two are already rejected above, so this merge | ||
| // only ever unions distinct names. |
…nknown Review follow-up on PR #906 (cosmetic pass). - The four `isAuthoring*Descriptor` predicates took `unknown` and re-validated every field. They now take that family's `Descriptor | Namespace` union and narrow on the `kind` discriminant alone — a type-predicate's actual job. The callers (the three `getAuthoring*` walkers, the interpreter/printer/helper walks, the merge/collect walkers, control-stack) pass the typed namespace node rather than erasing it to `unknown` via a `blindCast`, so this drops casts (lint:casts -14 vs merge-base, down from -11). - Boundary validation is preserved, not deleted: a type-bypassing pack (`as unknown as never`) that registers a descriptor-shaped-but-incomplete node is still rejected with the same path-aware error. That deep check moved out of the exported predicates into a private `isWellFormedDescriptor(value, kind)` used only by the composition walkers. The malformed-descriptor assembly tests pass unchanged; the two direct-predicate unit tests now assert narrowing (valid descriptor vs sub-namespace). - Trimmed three over-long comments (framework-authoring collision check; two in the PSL interpreter). typecheck 0 errors (whole repo); framework-components 464/464; sql-contract-psl 346/346; sql-contract-ts 384/384; lint:framework-vocabulary 906/906; lint:casts 1031 (-14); fixtures:check zero drift. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
Reconciles the one-differ-two-ir-planner slice (retired coordinate issue vocabulary, SchemaDiff/SchemaFindingLists collapse, SchemaOwnership) with main's #906 (native Postgres enums) and #919 (extension-aware contract infer). Conflicts in five files: - migrations/types.ts + control-target-descriptor.ts: main moved SqlControlTargetDescriptor into its own file and widened inferPslContract with describedContracts + SqlDescribedContractSpace; kept that move and re-applied our diff-hook reshape (diffDatabaseSchema/verifyDatabaseSchema -> diffSchemaForVerdict) plus the vocabulary retirement (verifyType returns SchemaDiffIssue, keepDiffIssue -> ownership). - exports/control.ts: kept both main's new control-target-descriptor export and our ColumnOpRenderer export. - control-instance.ts: kept both our verifySqlSchemaByDiff verify path and main's describedContracts threading; dropped main's verifyDatabaseSchema read (referenced the deleted coordinate hook). - infer-psl-contract.ts: kept main's resolveForeignKeys cross-space FK logic and constructed its rebuilt tables as real SqlTableIR instances (our slice made SqlTableIR a DiffableNode class, so main's plain-object clone no longer typed). - 0.14-to-0.15 upgrade instructions: kept every changes[] entry and narrative from both sides. Adapted main's #919 test (psl-infer-described-contracts.test.ts) to the required nodeKind/diffRole discriminants and dropped its stubs for the deleted descriptor hooks. pnpm install linked main's new @prisma-next/psl-printer devDep. Build 68/68, forced typecheck 143/143. Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…-framework (prisma#918) ## Linked issue No ticket — review-process infrastructure, adopted as an intervention during the [PR prisma#906](prisma#906) review rounds. ## At a glance ``` $ pnpm lint:framework-vocabulary lint:framework-vocabulary: scope=packages/1-framework current=201 merge-base=200 delta=+1 NEW: packages/1-framework/1-core/framework-components/src/shared/codec-types.ts:24: readonly nativeType?: string; ``` A PR that adds family vocabulary to the framework domain now fails CI with the offending line, instead of waiting for a human review round to catch it. ## Decision The framework domain (`packages/1-framework`) is family-blind, but family vocabulary has repeatedly leaked into framework types through review misses — the identical defect class was flagged across three review rounds on PR prisma#906 (`CodecRef.nativeType`, a `nativeTypeFor` framework hook, a strategy-enum field). This PR turns that review comment into a machine check, plus the rulecards that encode the discipline: 1. **`lint:framework-vocabulary`** — a merge-base ratchet in the exact mold of `lint:casts`: counts forbidden-term occurrences (declarative per-scope config: `nativeType`, `native-type`, `postgres`, `sqlite`, `mysql` under `packages/1-framework`, source files only) at HEAD vs the merge-base; growth fails with new sites listed; the 200 pre-existing hits are grandfathered and can only shrink. Wired into the CI Lint job beside `lint:casts`. 2. **`no-family-vocabulary-in-framework.mdc`** — the rule the ratchet enforces: the family-blindness test (*would Mongo populate or consume this meaningfully?*), the "family-agnostic dressing" tells (never-param bridges, duplicated "structurally identical" shapes, strategy string-enums), strategies as codec-owned hooks. 3. **`fix-the-class-not-the-instance.mdc`** (alwaysApply) — review-response discipline: a comment names a class, not a point-fix; sweep the whole diff, fix every instance in one round; new surface never inherits grandfathering; design is never settled. ## Reviewer notes - The scanner counts line-hits per term in `git ls-files`-tracked `*.ts`/`*.tsx` under each scope, excluding tests and `dist/`. Matching is substring, case-insensitive per config — deliberately blunt; the ratchet (not precision) is what makes it safe, since pre-existing hits never fail. - Baseline under `packages/1-framework`: `postgres` 136 · `nativeType` 41 · `sqlite` 13 · `mysql` 8 · `native-type` 2 (200 total, 45 files). Shrinking these is tracked debt (TML-2966 covers the `nativeType` authoring surface). - The config supports more scopes (e.g. target names under `packages/2-sql`) — seeded with the one scope this intervention is about. ## Testing performed - `scripts/lint-framework-vocabulary.test.mjs` — 17 tests via the `lint-casts.test.mjs` fixture-repo pattern: baseline passes, new occurrence fails with site listed, negative delta passes, exclusions hold, scope isolation, worktree cleanup. - `pnpm test:scripts` 183/183 · `pnpm lint:framework-vocabulary` exits 0 on this branch · `package.json`/`ci.yml` parse-validated. ## Alternatives considered - **An allowlist file of pre-existing sites** instead of the merge-base ratchet. Rejected: allowlists rot and invite append-to-pass; the merge-base comparison grandfathers exactly what exists with zero maintenance, the same trade `lint:casts` already made. - **Precise AST-level detection** (only flag identifiers, not comments). Rejected: vocabulary in doc comments is the same leak (it documents family semantics on framework surface), and the ratchet makes false-positive cost near zero. - **Judgment-only enforcement** (rulecards without the lint). Rejected by three empirical rounds of review evidence. ## Checklist - [x] DCO sign-off on every commit. - [x] Tests added. - [ ] `TML-NNNN:` title — no ticket; process infrastructure (see Linked issue). <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added a framework vocabulary guard that flags newly introduced forbidden database/domain terms in the framework layer. * Enabled the vocabulary guard in CI via a dedicated lint step. * **Documentation** * Updated review rules to require class-first feedback with full PR-wide sweeps, plus strengthened layering guidance for framework changes. * Added calibration guidance for repeated “point-fixed” defect patterns. * **Tests** * Added/updated automated coverage for the vocabulary checker’s matching, scoping, and threshold behavior. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]> Co-authored-by: Claude Opus 4.8 <[email protected]>
…r kind (prisma#931) ## At a glance Serializing a namespace's entity kinds used to mean one hand-written branch per kind, repeated in every SQL target: ```ts // before — postgres-contract-serializer.ts entries: { table: tablesOut, ...(Object.keys(valueSetOut).length > 0 ? { valueSet: valueSetOut } : {}), ...(Object.keys(roleOut).length > 0 ? { role: roleOut } : {}), ...(Object.keys(policyOut).length > 0 ? { policy: policyOut } : {}), } ``` Now it means walking the whole `entries` dict once, in the shared base: ```ts // after — SqlContractSerializerBase protected serializeNamespaceEntries(entries) { const out = { table: this.serializeEntries(entries['table'] ?? {}) }; for (const [kind, record] of Object.entries(entries)) { if (kind === 'table' || Object.keys(record).length === 0) continue; out[kind] = this.serializeEntries(record); } return out; } ``` ## The decision Serialize a namespace's entity kinds by iterating the `entries` dict generically, in `SqlContractSerializerBase` — no target names a kind. This makes writing a contract match how we already read one: hydration has always iterated the entity-kind registry, so an entity kind now round-trips in *both* directions with no serializer edit. ## Why — the asymmetry we're fixing Deserialize was already generic — it walks the registered kinds: ```ts hydrateNamespaceEntities(entriesInput, this.entryKinds, 'fail', id) ``` Serialize was not — each target listed `table` / `valueSet` / `role` / `policy` by hand. The consequence: an extension that contributes a new entity kind reads back for free but is **silently dropped on the way out**, until someone remembers to edit the target serializer. There was no signal that the write path needed touching — the kind just quietly vanished from `contract.json`. ## What changes - A new `SqlContractSerializerBase.serializeNamespaceEntries` walks `Object.entries(entries)`. The Postgres and SQLite serializers — and their unbound-slot branches — delegate to it; the JSON round-trip helpers move down into the base beside it. - `table` is the one kind still named: it is the universal SQL base kind, always emitted even when empty. Every other kind is emitted only when it holds an entry — the exact rule the old branches applied by hand. - A pack-contributed kind is already an enumerable key on `entries` and already hydrated via the registry, so it now serializes with zero serializer edits. ## The one thing to trust: output is byte-identical The old code emitted kinds in a fixed order; the new walk uses insertion order. That does not change the emitted file, because the contract is **canonicalized — recursive key sort — after serialization** on every path that writes or hashes it, so walk order never reaches disk. The emitted key *set* is unchanged too (`table` always; others only when non-empty). `fixtures:check` shows zero drift. Two details keep it that way: - **`native_enum` stays excluded.** It is authoring-time-only, carried non-enumerable on `entries` (its values survive via the derived `valueSet`), so `Object.entries` skips it with no special case. - **SQLite is unaffected.** It sets `sql.enums: false`, so its only non-`table` slot is always empty and stays omitted; a future SQLite kind would round-trip instead of being dropped. ## Tests A base-level test serializes a namespace whose `entries` carry `table`, a real non-`table` kind, a synthetic extension `widget` kind, an empty kind, and a non-enumerable `native_enum` — asserting the extension kind round-trips while `native_enum` and the empty kind drop out. Existing target-serializer tests plus `fixtures:check` are the byte-identical proof. ## Alternatives considered - **Fix it per-target** — make each serializer iterate its own kinds. Rejected: it leaves the duplication in place and the next SQL target repeats the mistake. The asymmetry is with the base's generic hydrate, so the fix belongs in the base. - **Add an `alwaysPresent` flag to the kind descriptor** instead of naming `table` directly. Rejected: speculative generality for a set of size one. `table` is the only universal base kind; naming it is honest and cheaper than a descriptor field one kind would ever set. - **Drive serialization off the `entryKinds` registry** (mirroring hydrate's exact mechanism) rather than `Object.entries`. The enumerable-key walk is simpler and gets `native_enum` exclusion for free via non-enumerability; consulting the registry would add a lookup the write path doesn't need. --- Origin: review point O1 on prisma#906. Shaping spec: `projects/native-postgres-enums/slices/generic-namespace-entries-serialization/spec.md`. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Bug Fixes** * Improved serialization of namespace entries so empty table entries are preserved consistently, while empty optional sections are omitted. * Fixed handling of undefined or non-enumerable namespace sections so they no longer appear in serialized output. * Made contract serialization more consistent across database targets, including cleaner handling of stored type metadata. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]> Co-authored-by: Claude Opus 4.8 <[email protected]>
Linked issue
TML-2976 — Native Postgres enums (MVP): external Supabase types as typed value unions. The MVP was shaped and tracked in-repo under
projects/native-postgres-enums/(spec, plan, and the authoring/querying/migration design docs). Cross-cutting follow-ups: TML-2965 (TS-DSL authoring surface), TML-2960 (no-emit per-instance column typing), TML-2966 (authoring-layernativeTypevocabulary).At a glance
Supabase's database ships enum types Prisma Next didn't create and must not migrate —
auth.aal_levelisCREATE TYPE auth.aal_level AS ENUM ('aal1','aal2','aal3'), owned by the platform. This PR makes such a type representable, typed, and reachable. Authored in PSL (here, in the Supabase extension's contract):Consumed against real Postgres (from the Supabase example's integration test):
Before this PR there was no representation for a native Postgres enum; a column over one had to fall back to text, losing the value union entirely.
Decision
This PR ships the MVP for externally-managed native Postgres enums: the database owns the type, Prisma Next represents it, types it, and exposes it — emitting no DDL. Five pieces:
native_enumPSL block lowers to a Postgres storage entity plus a derivedStorageValueSet; a fieldpg.enum(Ref)lowers to a column bound to thepg/enum@1codec with avalueSetref and noCHECK(the type itself enforces membership).'aal1' | 'aal2' | 'aal3') in the query builder, ORM, and emittedcontract.d.ts— via the existing value-set → codec typing path, with zero new typing code.pg/enum@1is a parameterized codec: each column carriestypeParams: { typeName: 'auth.aal_level' }(schema-qualified for non-publicschemas), and the SQL renderer asks the codec for its per-instance native type through a new optionalnativeTypeForhook — producing the$N::auth.aal_levelcast. The same qualified name on the column'snativeTypeis what makesdb verifyagree with Postgres introspection.db.nativeEnums— a Postgres-only runtime accessor (sibling ofdb.enums, which is untouched), literally typed from the emitted contract:valuesis the readonly tuple, notstring[].auth.aal_leveland the example proves the whole path — typed read, runtime accessor, executed cast, cleandb verify— against a live database.Two framework-level mechanisms land in support and deserve their own line: a generic entity-ref type constructor (how
pg.enum(Ref)resolves an argument against another document-local entity — contributed by Postgres, named by no target), and generic type-emission of storage entries (the emitter literalizes every entries slot intocontract.d.ts, so pack entities likenative_enum— androle/policyfor free — become type-visible).How it fits together
Represent.
native_enumis a pack-contributed Postgres entity on the same generic mechanism as RLSrole/policy: a variadic PSL block descriptor + a lowering factory (members must bekey = "value";typeNameis the block name verbatim unless@@mapped) + aPostgresNativeEnumIR node + validator + serializer. A genericderiveValueSethook derives theStorageValueSetfrom the members — the value-set, not the enum, is the typing input.Type.
pg.enum(Ref)resolves the ref and produces the column: codec +valueSetref + the instancetypeParams. Typing flows through the existing value-set → codec path unchanged — a check-enum column and a native-enum column are typed by identical machinery.Cast. At render time,
renderTypedParamconsultscodecLookup.nativeTypeFor(codecId, typeParams)(the same delegate shape as the existingrenderValueLiteralFor) and falls back to the codec's static meta. Onlypg/enum@1implements the hook, so every other column renders exactly as before.Access.
db.nativeEnumswalks thenative_enumstorage entities and reuses the frameworkcreateEnumAccessor; its type maps the emittedentries.native_enumthrough the shared enum-accessor type machinery. Attached to the Postgres client and to the Supabase client's.supabaseroot (where theauthnamespace lives).Prove. The Supabase example seeds the external type (Prisma Next emits no DDL for it) and demonstrates the typed read, the literal accessor, and the executed schema-qualified cast against a disposable real-Postgres instance.
Reviewer notes
nativeTypeonto everyCodecRef; review surfaced that this shadowed the codec's static meta for all columns, flipping plain$Ninto spurious$N::int4/$N::boolcasts on non-enum binds (invisible to CI — real Postgres tolerates the redundant cast). The codec-instance parameter +nativeTypeForhook replaced it; a regression test locks the non-enum behavior, andCodecRefis back to{ codecId, typeParams?, many? }. All 14 review-thread comments from the first round are addressed and answered inline on the PR.publicenum type must be referenced asauth.aal_level— for the cast and fordb verify(Postgresformat_type()reports the qualified name for non-publictypes). Both read the same authored-in name;public/default and the unbound namespace stay bare, mirroringPostgresSchema.qualifyTable's split. Spot-check the predicate inresolvePgEnumRef.contract.d.tsfiles grow accordingly (e.g. the supabase example's RLSpolicyslot becomes type-visible) — expected, and the reason the accessor can be literally typed.EnumEntryValues/EnumEntryNamesin@prisma-next/contract/enum-accessorare now homomorphic, so member tuples yield real tuples (previously{0:…,1:…}objects). Strictly an improvement for domain enums too; public aliases unchanged.nativeType(ColumnTypeDescriptor, template fields) is pre-existing, family-shared vocabulary — Mongo populates the same fields — and is deliberately not relocated here: TML-2966.config-loadermacOS/var-vs-/private/varpath assertions; an occasionalcli control-api/client.test.tsordering flake (passes 28/28 in isolation).Compatibility / migration / risk
Additive throughout.
CodecRefis unchanged frommain; the newnativeTypeForhook andAuthoringEntityRefResolution.typeParamsare optional;db.nativeEnumsis a new surface introduced by this PR (never released, so the review-round rename had no consumers). Existing columns render identical SQL — locked by the cast-policy regression test. External native enums emit no DDL and are never diffed.Testing performed
Run on the final HEAD:
pnpm typecheck— 143/143.pnpm test:packages— 11638 passed; the only failures are the three pre-existing config-loader macOS-path flakes.pnpm --filter @prisma-next/example-supabase test— 12/12 against real Postgres (@prisma/dev): typed read, literalnativeEnumsassertion, executed$1::auth.aal_levelcast.pnpm --filter @prisma-next/extension-supabase test— 51/51 against real Postgres, including cleandb verifyfor the external schema.pnpm fixtures:checkclean ·pnpm lint:castsdelta 0 ·pnpm lint:depsclean.Follow-ups
helpers.nativeEnum+field.column(pg.enum(handle))); needs genericContractDefinitionpack-entity attachment, shared with RLS role/policy.typeof contract) per-instance column typing.nativeType/ColumnTypeDescriptorvocabulary (pre-existing, family-shared).Alternatives considered
nativeTypeon theCodecReffor the cast. Tried first, reverted during review: every column has anativeType, so the stamp rides every ref and shadows static meta for non-enum binds (int4vsinteger→ spurious casts), and it puts a SQL-only field on the family-agnostic ref Mongo shares. The codec-instance parameter is opt-in per codec, so neither failure mode exists.typeParams,renderOutputType). Rejected for typing: post-TML-2952 the value-set → codec path is the general, enum-agnostic column-typing mechanism; a native column reuses it with zero new typing code. (The codec is parameterized — by the type name for the cast, not by the values for typing.)pg/text@1instead of a distinctpg/enum@1. Chose distinct: identifiability, the per-instancetypeNameparameter, and the future managed phase.StorageColumn.typeRef+storage.typesfor the column→type join. Rejected: that slot is the codec-alias mechanism (vector/geometry) — never a managedCREATE TYPEobject.CREATE TYPE/DROP TYPE/ADD VALUE, adoption, diffing). Deferred to a separate project — the MVP is external Supabase enums, which are never diffed, so no migration machinery ships here.@@map— no case manipulation, matching the RLS-template naming and Prisma's@@mapconvention.Checklist
TML-NNNN:convention — intentionally omitted; this MVP was tracked in-repo, not in Linear (see Linked issue).Summary by CodeRabbit
New Features
Bug Fixes