Repository navigation
Native Postgres enums: contract infer adopts external enum types (R6) - #944
Conversation
…lan) Pulls R6 (adoption) forward of the managed-lifecycle slices to unblock Supabase extension Slice F. contract infer will emit native_enum blocks + pg.enum(Ref) columns instead of throwing. Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
The Postgres control adapter enum query returned type names only. Join
pg_enum ordered by enumsortorder so introspection carries each enum
type's member values in declaration order, not just its name.
PostgresNamespaceSchemaNode gains an optional `nativeEnums` field
(`{ typeName, values }[]`) alongside the existing `nativeEnumTypeNames`.
The two are independent inputs, not derived from one another, so every
existing construction site and reader of `nativeEnumTypeNames` (codec
planTypeOperations hooks, the infer throw, the many test fixtures that
pass `nativeEnumTypeNames: []`) keeps compiling and behaving unchanged
without fabricating values. Only the adapter (producer) and the
normalize-for-diff carry-through (which forwards a real actual
namespace's data) needed to pass nativeEnums through.
No DiffableNode is minted for enum types and the differ/planner
semantics are untouched — this is introspection only, laying the
ground for the infer adoption path to read ordered values.
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…sform The generic extension-block printer walked only the descriptor's declared parameters, so a variadic block (native_enum, the family enum block) printed an empty body and dropped its @@ block attributes. Render undeclared parameters of variadicParameters blocks in AST insertion order (raw literals — no per-param descriptor means no codec) and render blockAttributes as @@name(args) lines. Add toEnumMemberName to the family name transforms: a native-enum value that is already a valid, non-reserved identifier stays verbatim as its member name; anything else camelCases/escapes like a field name. The value itself always prints explicitly (member = "value"), so no map result is needed. Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…om EnumInfo buildPslDocumentAst now consumes PslPrinterOptions.enumInfo (declared but unread until now): one native_enum extension block per definition — block name via the shared toEnumName top-level transform (intra-enum collisions throw like model collisions), reserved against model names with a numeric suffix on collision, @@Map carrying the type name whenever it differs, members as explicit `member = "value"` pairs with sanitized, deduplicated member names. An enum-typed column emits the pg.enum(<Name>) type-constructor call (the Phase-1 authoring form), with ?/[] composing like any other field type; enum PSL names are reserved in the named-type registry. The two `new Map()` enumNameMap dead-wirings are replaced by the map derived from enumInfo. Enum arrays: settled as EMIT — a psl-pg-enum-column test proves the Phase-1 interpreter accepts pg.enum(E)[] under the scalarList capability, so infer emits the list form for `<enum type>[]` columns rather than a diagnostic. print-psl.enums.test.ts inverts from asserting the adoption throw to asserting emission, driven through buildPslDocumentAst (now exported from the module) with hand-fed EnumInfo; emitted PSL is proven to parse via @prisma-next/psl-parser with zero diagnostics, including the @@Map + sanitized-member and model-collision + array shapes. The infer entry throw itself stays (still covered by print-psl.naming-and-constraints.test.ts) — the adoption dispatch removes it. Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
… throwing
Delete the "drop the native type" remediation throw. The introspected
tree's nativeEnums ({ typeName, values }) thread directly from the
namespace nodes into PslPrinterOptions.enumInfo at the infer entry — the
annotations-based extractEnumInfo path (always-empty definitions, no
production callers) is removed rather than left as a second dead seam. A
transitional-grade note stands where the throw lived: inferred blocks
inherit defaultControl; the managed lifecycle lands with Phase 2 of
projects/native-postgres-enums/spec.md.
Enum-bearing output wraps in an explicit `namespace <schemaName> { }`
block (pinned design: a top-level native_enum never lowers — the
interpreter skips extension entities in the unspecified bucket);
enum-free output stays flat and byte-identical. Adoption with content
across multiple schemas throws the TML-2958-style stopgap error, and a
type name reported without member values is an internal-invariant error,
never a silent Unsupported fallback.
Pack-owned subtraction matches by TYPE NAME: entries.native_enum is
keyed by handle name, so a dedicated walk indexes each entity's typeName
(the kind map is non-enumerable on PostgresSchema.entries — the generic
elementCoordinates walk never sees it). A surviving app column typed by
a pack-owned enum type throws an actionable error naming the type and
the owning space: a cross-space enum-typed column has no authorable PSL
form yet.
Enum-typed defaults, proven by test: a bare cast ('aal1'::aal_level)
parses to @default("aal1"); a schema-qualified cast is preserved raw as
@default(dbgenerated("...")) — no mis-parse.
New infer-entry tests cover adoption + wrap (public and auth shapes),
flat enum-free regression, subtraction (omission, namespace scoping,
owned-column error), defaults, and the production interpret chain:
wrapped output lowers to the same coordinates as the flat form for
public, closing the parses-but-does-not-lower gap. The adapter e2e that
asserted the old throw inverts to prove adoption on the real
introspect→infer path.
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…-ups Spec amendments from the D2a/D2b rounds: enum-bearing infer output is namespace-wrapped (interpreter skips the unspecified bucket); enum-array question settled (lists were already authorable); serialized pack contracts strip native_enum entries, so subtraction matches in-memory contracts only — recorded as a follow-up. D3 carry-overs: name[] parser and @@Map unquote hardening. Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
New CLI journey: a PGlite database with native enum types + enum-typed columns round-trips — `contract infer` writes a namespace-wrapped contract.prisma (declaration-ordered members, @@Map, pg.enum columns), `contract emit` builds it, and `db verify --schema-only` passes against the SOURCE database; the emitted contract.json valueSet carries the ordered member value union. Covers public (full CLI chain) and the auth.aal_level shape. The auth inference drives the family instance with an auth-declaring contract because the CLI infer entry passes no contract to introspection and can only reach the default schema — a real CLI limitation, reported to the slice. The live run exposed a gap the D2b unit fixtures missed: `format_type` reports an enum column's nativeType schema-qualified whenever the type sits outside the connection's search_path (`auth.aal_level`), while `pg_type.typname` — the definitions key — stays bare. The infer entry now registers the qualified spelling as an alias (type-map membership, enum name map, pack-owned column check); block emission stays keyed on the bare name. Without the alias the auth shape emitted Unsupported("auth.aal_level"). Verify itself needed nothing: authored columns carry the same qualified spelling via qualifyColumnType, so both sides agree. Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
parsePgNameArray (review carry-over from the introspection dispatch): the string branch split the raw name[] literal on every comma and trimmed every element, silently corrupting a label containing a comma, quote, backslash, brace, or significant whitespace. Replace it with a scanner that honors Postgres array-literal quoting: quoted elements unescape \\" and \\\\ and keep their whitespace; unquoted elements trim as before. unwrapQuotedString (review carry-over from the emission dispatch): the @@Map / policy-param unwrap only inverted \\" — a backslash-bearing type name printed as \\\\ round-tripped back with the escape intact. Invert the full escapePslString set (backslash, quote, \\n, \\r), keeping unknown sequences verbatim like the printer-side unescape. Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
… statuses The project plan gains the infer-adoption slice under shipped work (R6 pulled forward; managed lifecycle remains with Phase-2 Slices A/B), marks the generic entries serialization (PR #931) and the TS authoring mirror (PR #935) as merged, and points Phase-2 Slice C at the shipped slice. Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
contract infer cannot introspect a non-default schema (introspect() defaults to public) — pre-existing, surfaced by the D3 auth-shaped journey; blocks the CLI leg of Supabase Slice F alongside TML-2958. Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
|
Warning Review limit reached
Next review available in: 25 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Path: .coderabbit.yml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (5)
📝 WalkthroughWalkthroughThis change adds native Postgres enum introspection and adoption into PSL inference, including ordered enum values, generated ChangesNative enum adoption
Estimated code review effort: 4 (Complex) | ~60 minutes Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 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 |
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: |
There was a problem hiding this comment.
Actionable comments posted: 4
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/3-targets/3-targets/postgres/src/core/psl-infer/infer-psl-contract.ts (1)
357-395: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick winCheck owned enums across all namespaces before lowering tables.
ownedEnumTypesis only loaded fornamespace.schemaName, so a table in schema A that referencesB.some_enumcan bypass this guard when A has no owned enums. That path later falls back toUnsupported(...)instead of the targeted cross-pack error. Consider indexing owned enums globally by type name, or scanning all namespace maps here.🤖 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/psl-infer/infer-psl-contract.ts` around lines 357 - 395, Update the table-lowering logic around ownedEnumTypes and the namespace iteration to validate enum ownership globally, not only against the current namespace schema. Build or use an index mapping every native enum type name to its owning extension-pack space across all namespace maps, then check each table column against that index before creating SqlTableIR; preserve the targeted cross-space error and ensure references such as B.some_enum from schema A cannot fall through to Unsupported(...).
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In
`@packages/1-framework/2-authoring/psl-printer/src/serialize-print-document.ts`:
- Around line 136-138: Replace the `paramName in descriptor.parameters` check in
the parameter serialization loop with `Object.hasOwn(descriptor.parameters,
paramName)` so inherited Object.prototype names are emitted correctly, and add a
regression test covering variadic names such as `toString`, `constructor`, or
`valueOf`.
In `@packages/3-targets/3-targets/postgres/test/psl-infer/fixtures.ts`:
- Around line 70-80: readNativeEnums currently accepts enum entries whose values
array contains non-string members. Extend its type guard to require
values.every((value): value is string => typeof value === 'string') alongside
the existing checks, so only valid string-label arrays are returned.
In `@packages/3-targets/6-adapters/postgres/src/core/control-adapter.ts`:
- Line 1253: In the loop containing the character assignment, replace the
production type assertion on inner[i] with inner.charAt(i), preserving the
existing indexing behavior without using a bare cast.
In `@packages/3-targets/6-adapters/postgres/test/control-adapter.test.ts`:
- Around line 1690-1728: Update parsePgNameArray to reject unterminated quoted
literals: before the final pushCurrent() or return, check whether parsing ended
with inQuotes === true and return [] instead of appending the partial value. Add
a regression test for parsePgNameArray('{"unterminated}') expecting [].
---
Outside diff comments:
In
`@packages/3-targets/3-targets/postgres/src/core/psl-infer/infer-psl-contract.ts`:
- Around line 357-395: Update the table-lowering logic around ownedEnumTypes and
the namespace iteration to validate enum ownership globally, not only against
the current namespace schema. Build or use an index mapping every native enum
type name to its owning extension-pack space across all namespace maps, then
check each table column against that index before creating SqlTableIR; preserve
the targeted cross-space error and ensure references such as B.some_enum from
schema A cannot fall through to Unsupported(...).
🪄 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: c9c2fc91-d3e1-4b15-9ba1-8d42963fb66b
⛔ Files ignored due to path filters (4)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yamlprojects/native-postgres-enums/plan.mdis excluded by!projects/**projects/native-postgres-enums/slices/infer-native-enum-adoption/plan.mdis excluded by!projects/**projects/native-postgres-enums/slices/infer-native-enum-adoption/spec.mdis excluded by!projects/**
📒 Files selected for processing (27)
packages/1-framework/2-authoring/psl-printer/src/serialize-print-document.tspackages/1-framework/2-authoring/psl-printer/test/generic-extension-block-printer.test.tspackages/2-sql/9-family/src/core/psl-contract-infer/name-transforms.tspackages/2-sql/9-family/src/exports/psl-infer.tspackages/2-sql/9-family/test/psl-contract-infer/name-transforms.test.tspackages/3-targets/3-targets/postgres/src/core/authoring.tspackages/3-targets/3-targets/postgres/src/core/migrations/diff-database-schema.tspackages/3-targets/3-targets/postgres/src/core/psl-infer/infer-psl-contract.tspackages/3-targets/3-targets/postgres/src/core/psl-infer/postgres-type-map.tspackages/3-targets/3-targets/postgres/src/core/schema-ir/postgres-namespace-schema-node.tspackages/3-targets/3-targets/postgres/src/exports/types.tspackages/3-targets/3-targets/postgres/test/postgres-namespace-schema-node.test.tspackages/3-targets/3-targets/postgres/test/psl-infer/fixtures.tspackages/3-targets/3-targets/postgres/test/psl-infer/infer-psl-contract.enum-adoption.test.tspackages/3-targets/3-targets/postgres/test/psl-infer/infer-psl-contract.test.tspackages/3-targets/3-targets/postgres/test/psl-infer/postgres-type-map.test.tspackages/3-targets/3-targets/postgres/test/psl-infer/print-psl/print-psl.enums.test.tspackages/3-targets/3-targets/postgres/test/psl-infer/print-psl/print-psl.naming-and-constraints.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/control-adapter.tspackages/3-targets/6-adapters/postgres/test/control-adapter.test.tspackages/3-targets/6-adapters/postgres/test/migrations/native-enum-infer-adoption.integration.test.tspackages/3-targets/6-adapters/postgres/test/migrations/native-enum-infer-diagnostic.integration.test.tspackages/3-targets/6-adapters/postgres/test/migrations/native-enum-introspection.integration.test.tstest/integration/package.jsontest/integration/test/cli-journeys/native-enum-adoption.e2e.test.ts
💤 Files with no reviewable changes (2)
- packages/3-targets/6-adapters/postgres/test/migrations/native-enum-infer-diagnostic.integration.test.ts
- packages/3-targets/3-targets/postgres/src/core/psl-infer/postgres-type-map.ts
…t, reject unterminated pg array literal)
1. serialize-print-document: the variadic-block skip used `paramName in
descriptor.parameters`, which also matches Object.prototype keys — a
member literally named toString/constructor/valueOf would be dropped
from emitted PSL. Use Object.hasOwn (repo rule object-hasown). New
printer regression test renders a member named toString/constructor.
2. parsePgNameArray: replace the bare `inner[i] as string` cast with
`inner.charAt(i)` (equivalent under the `i < inner.length` guard) —
no-bare-casts. The sibling `inner[i + 1] ?? ""` is not a cast and
stays.
3. parsePgNameArray: an unterminated quoted element (`{"unterminated}`)
left the loop with inQuotes still true and pushed the partial value;
reject with `[]` instead. New adapter regression test; the terminated
quoted cases (commas, escapes, braces, whitespace) still parse.
4. test fixtures readNativeEnums: tighten the values guard to require
every element is a string, so a malformed fixture cannot feed
non-string enum labels into inference (test-helper only).
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
The variadic-block rendering added to serialize-print-document.ts had branches no test exercised, dropping psl-printer below the 95% statement threshold. Add focused tests driving printPslFromAst with: - each variadic value kind (value, ref, option, nested list); - block attributes with args (@@Map("x")) and without (@@something); - a bare member (renders as its bare name) and a bare inside a list (covers renderVariadicValue's bare arm); - a variadic block whose descriptor also declares a parameter, so the Object.hasOwn guard skips re-rendering the declared one. serialize-print-document.ts statements 93.75 -> 100 on the variadic paths; package All-files 93.59% -> 95.72% statements, 85.45% -> 89.69% branches. Whole-line assertions; each fails if its render arm breaks. Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…+ plan) Flip the native_enum entity from authoring-time-only (non-enumerable, stripped from contract.json) to a serialized entries kind like role/policy. Unblocks Phase-2 CREATE TYPE/ADD VALUE planning (planner reads ordered members from the storage segment) and pack-owned infer subtraction on JSON-hydrated contracts (follow-up from PR #944). Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…ge fix) The native-enum PRs (#941/#944/#946) added infer-psl-contract.enum-adoption.test.ts, which constructs a PostgresTableSchemaNode; this slice made rlsEnabled a required field, so the merged tree failed the (now stricter, per #941) typecheck. Supply rlsEnabled: false at the one construction site — the same mechanical ripple every other construction site in this slice already carries. Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
….json (prisma#946) > **Stacked on prisma#944** (`infer-native-enum-adoption`). Review/merge that first; this branch rebases onto main once it lands. The net diff below is against prisma#944's head. ## What this does A `native_enum` entity used to be **authoring-time-only** — carried non-enumerable on `PostgresSchema.entries`, so the serializer, the hashing pipeline, and `contract.json` all walked past it. Only the *derived* `entries.valueSet` survived. That was Phase 1's "no readers after emit" assumption, and it has expired twice: 1. **Phase 2 owns DDL for these types** (`CREATE TYPE`/`ADD VALUE`). The migration planner must derive the expected type — name and *ordered* members — from the storage segment of `contract.json` alone (storage-only planning, ADR 004/199). It can't, if the entity isn't there. 2. **Pack-owned enum subtraction was blind on hydrated contracts.** prisma#944 taught `contract infer` to omit an introspected enum type that a stack pack already declares — but only when the pack's contract was *in memory*. In production, `describedContracts` hydrate from `contract.json`, which carried no enum type names, so the subtraction silently matched nothing. After this PR, `entries.native_enum` serializes like `role`/`policy`: ```jsonc "entries": { "native_enum": { "AalLevel": { "kind": "postgres-enum", "typeName": "aal_level", "members": ["aal1", "aal2", "aal3"] } }, "valueSet": { "AalLevel": { /* derived, unchanged */ } } } ``` and a JSON-hydrated Supabase pack contract exposes `aal_level` to the infer subtraction — closing prisma#944's follow-up the production way. ## The change is a deletion The entity was excluded from `contract.json` by exactly one thing: a non-enumerable-property trick in `postgres-schema.ts`. The generic serializer (TML-2981, prisma#931) already iterates the entries dict; hydration already composes `nativeEnumEntityKind`. So the fix is **deleting the carve-out** — the entity then serializes, hydrates, and is captured by `storageHash` with no serializer or validator edit. Confirmed by reading the machinery, not assuming it. **Hash coherence is preserved, inverted.** The carve-out's own comment said its purpose was keeping `computeStorageHash`'s `JSON.stringify` walking past the entity, so the hash matched serialized bytes. Enumerability restores that coherence in the inclusive direction: bytes and hash now move *together*, and only for enum-bearing contracts. A storageHash-differ test fails RED under the old carve-out and passes only after the deletion — the coherence proof can't false-pass. **`contract.d.ts` type surface is unchanged.** The generic-collapse review removed raw-slot emission from the `.d.ts`; that stays true. The only `.d.ts` movement is the `StorageHash` literal (the hash is baked into the type), and it matches the moved `storageHash` in `contract.json` byte-for-byte. ## Commits 1. **`native-enums(D1)`** — delete the carve-out; the entity flows through the generic serialize/hydrate/hash path. Round-trip + absent-key-tolerance + enum-free-byte-identity tests. 2. **`native-enums(D2)`** — prove the payoff production-shaped: an infer-entry test builds the Supabase-shaped described contract, round-trips it through serialize→JSON→hydrate, and asserts `contract infer` omits the pack-owned `aal_level` while emitting a non-pack-owned `factor_type` in the same run (selective, not blanket). No change to the subtraction code — D1 was the whole enabler. 3. **`native-enums(D3)`** — regenerate the artifacts the byte/hash change touches (Supabase pack `contract.{json,d.ts}`, parity `expected.contract.json`) via `pnpm fixtures:emit`; drift reviewed to be exactly `+ entries.native_enum + moved hashes` on enum-bearing contracts, enum-free artifacts and all example ledgers byte-identical. ## What's out of scope (deliberately) - **Phase-2 planner/differ/ops.** The entity is now *available* to the planner from storage; nothing reads it yet. Slice A wires the projection + `CREATE TYPE`/`ADD VALUE`. - **Multi-namespace infer** (TML-2958) and the **CLI schema-selection limitation** — separate follow-ups; this PR makes the subtraction *capable* on hydrated contracts, which those will exercise at scale. ## Verification Full gate run (independently re-run by the coordinator on top of the implementer's logged runs): `pnpm build`, `pnpm typecheck`, `lint:casts` (−1), `lint:deps`, `lint:framework-vocabulary` (836/836), `pnpm fixtures:check` (clean post-regeneration), `pnpm test:packages`, `pnpm test:integration`, PSL↔TS parity, and the Supabase example suite (db-verify passes against the regenerated pack). Residual test failures were the repo's known flake families (PGlite portal-race, `/var`→`/private/var` macOS symlink, 100ms teardown timeouts), each passing on isolation rerun — the diff is regeneration-only, so no failure can be a logic regression. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **New Features** - PostgreSQL native enum definitions are now preserved in contract data and remain available after serialization and rehydration. - Contract outputs now include native enum metadata, including names, members, and database type names. - Storage hashes now reflect changes to native enum definitions. - **Bug Fixes** - Improved compatibility with contracts that omit native enum information. - Preserved correct enum handling when identifying pack-owned and externally defined enums. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
What this does
Running
contract inferagainst a database that contains native Postgres enum types used to hard-fail:That remediation is useless against a database the user doesn't own — Supabase's
authschema alone carries five native enum types. After this PR, the same run adopts them, emitting the Phase-1 authoring surface:The emitted contract parses, builds, and passes
db verifyagainst the source database, with the column typed as the member value union ('aal1' | 'aal2' | 'aal3') — proven live against PGlite in a new CLI journey test, for bothpublicand theauth.aal_levelshape.This pulls requirement R6 (adoption) of the native-postgres-enums project forward of the managed-lifecycle slices, because it unblocks the Supabase extension's Slice F (introspect→emit of the full
auth/storagecontract) and has no code dependency on the differ or migration ops. Slice spec:projects/native-postgres-enums/slices/infer-native-enum-adoption/spec.md.Decisions
control— they inherit the contract'sdefaultControl, like every other inferred element (the project spec's "all inference is managed"). Transitional gap, documented at the old throw site: underdefaultControl: 'managed'the planner doesn't yet enforce the enum lifecycle (Contract→SchemaIR projects no enum types until Phase-2 Slices A/B); A/B make the grade true retroactively with no contract change. For the Supabase use case (external) the emitted contract is faithful today.native_enumblock only lowers inside an explicitnamespace { … }block. Infer wraps its output innamespace <schema> { … }only when the introspected namespace contains native enums — enum-free output stays byte-identical to today (fixtures:check zero drift), and flat-vs-wrapped coordinate parity is pinned by test.pg.enum(E)[]was already authorable in Phase 1 (proven through the production interpret chain with zero implementation change), so infer emits the list form.entries.native_enum— the generic coordinate owners can't see the kind map (non-enumerable) and entries are keyed by handle name, not type name. An app column typed by a pack-owned enum throws an actionable error: no cross-space form is authorable (pg.enum(Ref)resolves same-namespace only), so a named diagnostic is the honest interim.format_type→auth.aal_level) whilepg_type.typnameis bare; the infer entry registers both spellings, blocks stay keyed bare.db verifyneeded nothing — authored columns already carry the qualified spelling viaqualifyColumnType, so both sides agree.Mechanics (by commit)
pg_enumjoined onenumsortorder, aggregation ordered insidearray_agg), carried as an additivenativeEnums: { typeName, values }[]onPostgresNamespaceSchemaNode; the names-only view is derived from the same rows so the two cannot drift.@@attributes were dropped — a generic, family-blind fix) and the infer writer emitsnative_enumblocks (@@mapwhen the PSL name transforms; members sanitized with explicitmember = "value"; enum-vs-model collisions rename with a counter suffix, recoverable via@@map) pluspg.enum(Name)call-syntax columns.'aal1'::aal_level→@default("aal1"); schema-qualified casts preserve asdbgenerated(...).parsePgNameArraynow honors Postgres array-literal quoting (an enum label containing commas/quotes/whitespace parses to the true label — also strictly extends RLSrolesparsing);unwrapQuotedStringnow exactly inverts the printer's escape set (round-trip pinned).Known gaps (recorded in the slice spec § Follow-ups, not addressed here)
native_enumentries, so pack subtraction matches in-memory contracts only — inert while infer is single-namespace, needs resolving before multi-namespace infer (TML-2958).introspect()defaults topublic) — pre-existing; theauthjourney drives the family-level path the CLI wraps. Blocks the CLI leg of Supabase Slice F alongside TML-2958.Verification
Full gate run (independently re-run by the coordinator on top of the implementer's logged runs):
pnpm build,pnpm typecheck,pnpm lint:casts(delta −1),pnpm lint:deps,pnpm lint:framework-vocabulary(836/836, config untouched),pnpm fixtures:check(zero drift),pnpm test:packages,pnpm test:integration, plus the new journey (test/integration/test/cli-journeys/native-enum-adoption.e2e.test.ts).🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Bug Fixes