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

Native Postgres enums: contract infer adopts external enum types (R6) - #944

Merged
wmadden-electric merged 12 commits into
mainfrom
infer-native-enum-adoption
Jul 10, 2026
Merged

wmadden-electric merged 12 commits into
mainfrom
infer-native-enum-adoption

Conversation

@wmadden-electric

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

Copy link
Copy Markdown
Contributor

What this does

Running contract infer against a database that contains native Postgres enum types used to hard-fail:

contract infer: the database contains native Postgres enum type(s): aal_level.
Native Postgres enums (CREATE TYPE … AS ENUM) are not adoptable by contract infer.
Drop the native type and replace each column with a text column carrying a CHECK constraint …

That remediation is useless against a database the user doesn't own — Supabase's auth schema alone carries five native enum types. After this PR, the same run adopts them, emitting the Phase-1 authoring surface:

namespace auth {
  native_enum AalLevel {
    aal1 = "aal1"
    aal2 = "aal2"
    aal3 = "aal3"
    @@map("aal_level")
  }

  model Session {
    aal pg.enum(AalLevel)?
    @@map("sessions")
  }
}

The emitted contract parses, builds, and passes db verify against 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 both public and the auth.aal_level shape.

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/storage contract) 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

  • Inferred blocks carry no explicit control — they inherit the contract's defaultControl, like every other inferred element (the project spec's "all inference is managed"). Transitional gap, documented at the old throw site: under defaultControl: '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.
  • Enum-bearing output is namespace-wrapped. The interpreter deliberately skips extension entities in the unspecified top-level bucket, so a native_enum block only lowers inside an explicit namespace { … } block. Infer wraps its output in namespace <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.
  • Enum arrays are emitted, not diagnosed. 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.
  • Pack-owned enum types are subtracted by type name via a dedicated walk over 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.
  • Qualified spellings alias to their bare type. Live introspection reports an out-of-search_path enum column's type schema-qualified (format_type → auth.aal_level) while pg_type.typname is bare; the infer entry registers both spellings, blocks stay keyed bare. db verify needed nothing — authored columns already carry the qualified spelling via qualifyColumnType, so both sides agree.

Mechanics (by commit)

  1. Introspection reads ordered member values (pg_enum joined on enumsortorder, aggregation ordered inside array_agg), carried as an additive nativeEnums: { typeName, values }[] on PostgresNamespaceSchemaNode; the names-only view is derived from the same rows so the two cannot drift.
  2. The PSL printer renders variadic extension blocks (previously any such block printed an empty body and @@ attributes were dropped — a generic, family-blind fix) and the infer writer emits native_enum blocks (@@map when the PSL name transforms; members sanitized with explicit member = "value"; enum-vs-model collisions rename with a counter suffix, recoverable via @@map) plus pg.enum(Name) call-syntax columns.
  3. The infer entry threads introspected values straight into the printer seams (the dead annotations path is deleted, not left as a second seam), subtracts pack-owned types, wraps, and handles enum-typed defaults non-silently: 'aal1'::aal_level → @default("aal1"); schema-qualified casts preserve as dbgenerated(...).
  4. Hardening from review rounds: parsePgNameArray now honors Postgres array-literal quoting (an enum label containing commas/quotes/whitespace parses to the true label — also strictly extends RLS roles parsing); unwrapQuotedString now exactly inverts the printer's escape set (round-trip pinned).

Known gaps (recorded in the slice spec § Follow-ups, not addressed here)

  • Serialized pack contracts strip native_enum entries, so pack subtraction matches in-memory contracts only — inert while infer is single-namespace, needs resolving before multi-namespace infer (TML-2958).
  • The CLI cannot introspect a non-default schema (introspect() defaults to public) — pre-existing; the auth journey 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

    • PostgreSQL native enums are now introspected and adopted into generated PSL contracts, including ordered values, schema names, mappings, and enum-typed columns.
    • Generated contracts support native enum lists and namespace-aware output.
    • Variadic extension parameters and block attributes are now rendered correctly.
  • Bug Fixes

    • Improved escaping and unescaping of quoted PostgreSQL strings, including quotes, backslashes, and line breaks.
    • Preserved native enum metadata during schema comparison and migration workflows.
    • Improved enum naming and collision handling for valid and reserved identifiers.

…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]>
@wmadden-electric
wmadden-electric requested a review from a team as a code owner July 10, 2026 07:16
@coderabbitai

coderabbitai Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@wmadden-electric, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 25 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: ae4c1e5a-2b63-46c7-95b7-ca0a661842d7

📥 Commits

Reviewing files that changed from the base of the PR and between fc0f21c and 961778f.

📒 Files selected for processing (5)
  • packages/1-framework/2-authoring/psl-printer/src/serialize-print-document.ts
  • packages/1-framework/2-authoring/psl-printer/test/generic-extension-block-printer.test.ts
  • packages/3-targets/3-targets/postgres/test/psl-infer/fixtures.ts
  • packages/3-targets/6-adapters/postgres/src/core/control-adapter.ts
  • packages/3-targets/6-adapters/postgres/test/control-adapter.test.ts
📝 Walkthrough

Walkthrough

This change adds native Postgres enum introspection and adoption into PSL inference, including ordered enum values, generated native_enum blocks, pg.enum(...) column types, name collision handling, escaping symmetry, and end-to-end public/auth round-trip coverage.

Changes

Native enum adoption

Layer / File(s) Summary
Printer and enum naming contracts
packages/1-framework/..., packages/2-sql/...
The PSL printer emits variadic parameters and block attributes, while enum member names are validated, camel-cased, and escaped.
Enum introspection and schema IR
packages/3-targets/3-targets/postgres/src/core/schema-ir/..., packages/3-targets/6-adapters/postgres/...
Postgres introspection captures ordered enum labels, parses array literals, and stores immutable native enum metadata.
PSL enum adoption and emission
packages/3-targets/3-targets/postgres/src/core/psl-infer/...
Inference adopts introspected enums, handles ownership and namespace rules, emits native_enum blocks, and types columns with pg.enum(...).
Lowering and unit validation
packages/3-targets/3-targets/postgres/test/psl-infer/..., packages/3-targets/3-targets/postgres/src/core/authoring.ts
Tests cover printing, sanitization, collisions, defaults, lists, escaping, and interpret-chain lowering.
End-to-end round trips
packages/3-targets/6-adapters/postgres/test/migrations/..., test/integration/...
Integration tests verify introspection, inference, emission, schema verification, ordered values, public/auth flows, and idempotency.

Estimated code review effort: 4 (Complex) | ~60 minutes

Possibly related PRs

  • prisma/prisma-next#805: Adds related extension-block parsing and AST support for variadic members and block attributes.
  • prisma/prisma-next#894: Introduces schema-node changes extended here with native enum introspection data.

Suggested reviewers: aqrln

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: contract inference now adopts native Postgres enum types instead of failing.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch infer-native-enum-adoption

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

❤️ Share

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

@github-actions

github-actions Bot commented Jul 10, 2026 •

Copy link
Copy Markdown

size-limit report 📦

Path Size
postgres / no-emit 153.5 KB (+0.21% 🔺)
postgres / emit 128.82 KB (+0.25% 🔺)
mongo / no-emit 98.36 KB (0%)
mongo / emit 89.39 KB (0%)
cf-worker / no-emit 180.48 KB (+0.16% 🔺)
cf-worker / emit 153.46 KB (+0.2% 🔺)

@pkg-pr-new

pkg-pr-new Bot commented Jul 10, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@prisma-next/extension-author-tools

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

@prisma-next/mongo-runtime

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

@prisma-next/family-mongo

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

@prisma-next/sql-runtime

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

@prisma-next/family-sql

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

@prisma-next/extension-arktype-json

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

@prisma-next/middleware-cache

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

@prisma-next/mongo

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

@prisma-next/extension-paradedb

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

@prisma-next/extension-pgvector

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

@prisma-next/extension-postgis

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

@prisma-next/postgres

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

@prisma-next/sql-orm-client

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

@prisma-next/sqlite

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

@prisma-next/extension-supabase

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

@prisma-next/target-mongo

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

@prisma-next/adapter-mongo

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

@prisma-next/driver-mongo

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

@prisma-next/contract

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

@prisma-next/utils

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

@prisma-next/config

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

@prisma-next/errors

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

@prisma-next/framework-components

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

@prisma-next/operations

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

@prisma-next/ts-render

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

@prisma-next/contract-authoring

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

@prisma-next/ids

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

@prisma-next/psl-parser

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

@prisma-next/psl-printer

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

@prisma-next/cli

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

@prisma-next/cli-telemetry

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

@prisma-next/config-loader

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

@prisma-next/emitter

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

@prisma-next/language-server

npm i https://pkg.pr.new/@prisma-next/language-server@944

@prisma-next/migration-tools

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

prisma-next

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

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

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

@prisma-next/mongo-codec

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

@prisma-next/mongo-contract

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

@prisma-next/mongo-value

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

@prisma-next/mongo-contract-psl

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

@prisma-next/mongo-contract-ts

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

@prisma-next/mongo-emitter

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

@prisma-next/mongo-schema-ir

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

@prisma-next/mongo-query-ast

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

@prisma-next/mongo-orm

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

@prisma-next/mongo-query-builder

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

@prisma-next/mongo-lowering

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

@prisma-next/mongo-wire

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

@prisma-next/sql-contract

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

@prisma-next/sql-errors

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

@prisma-next/sql-operations

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

@prisma-next/sql-schema-ir

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

@prisma-next/sql-contract-psl

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

@prisma-next/sql-contract-ts

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

@prisma-next/sql-contract-emitter

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

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

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

@prisma-next/sql-relational-core

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

@prisma-next/sql-builder

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

@prisma-next/target-postgres

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

@prisma-next/target-sqlite

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

@prisma-next/adapter-postgres

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

@prisma-next/adapter-sqlite

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

@prisma-next/driver-postgres

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

@prisma-next/driver-sqlite

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

commit: 961778f

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Check owned enums across all namespaces before lowering tables. ownedEnumTypes is only loaded for namespace.schemaName, so a table in schema A that references B.some_enum can bypass this guard when A has no owned enums. That path later falls back to Unsupported(...) 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

📥 Commits

Reviewing files that changed from the base of the PR and between 9175ebb and fc0f21c.

⛔ Files ignored due to path filters (4)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
  • projects/native-postgres-enums/plan.md is excluded by !projects/**
  • projects/native-postgres-enums/slices/infer-native-enum-adoption/plan.md is excluded by !projects/**
  • projects/native-postgres-enums/slices/infer-native-enum-adoption/spec.md is excluded by !projects/**
📒 Files selected for processing (27)
  • packages/1-framework/2-authoring/psl-printer/src/serialize-print-document.ts
  • packages/1-framework/2-authoring/psl-printer/test/generic-extension-block-printer.test.ts
  • packages/2-sql/9-family/src/core/psl-contract-infer/name-transforms.ts
  • packages/2-sql/9-family/src/exports/psl-infer.ts
  • packages/2-sql/9-family/test/psl-contract-infer/name-transforms.test.ts
  • packages/3-targets/3-targets/postgres/src/core/authoring.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/diff-database-schema.ts
  • packages/3-targets/3-targets/postgres/src/core/psl-infer/infer-psl-contract.ts
  • packages/3-targets/3-targets/postgres/src/core/psl-infer/postgres-type-map.ts
  • packages/3-targets/3-targets/postgres/src/core/schema-ir/postgres-namespace-schema-node.ts
  • packages/3-targets/3-targets/postgres/src/exports/types.ts
  • packages/3-targets/3-targets/postgres/test/postgres-namespace-schema-node.test.ts
  • packages/3-targets/3-targets/postgres/test/psl-infer/fixtures.ts
  • packages/3-targets/3-targets/postgres/test/psl-infer/infer-psl-contract.enum-adoption.test.ts
  • packages/3-targets/3-targets/postgres/test/psl-infer/infer-psl-contract.test.ts
  • packages/3-targets/3-targets/postgres/test/psl-infer/postgres-type-map.test.ts
  • packages/3-targets/3-targets/postgres/test/psl-infer/print-psl/print-psl.enums.test.ts
  • packages/3-targets/3-targets/postgres/test/psl-infer/print-psl/print-psl.naming-and-constraints.test.ts
  • packages/3-targets/3-targets/postgres/test/psl-native-enum-authoring.test.ts
  • packages/3-targets/3-targets/postgres/test/psl-pg-enum-column.test.ts
  • packages/3-targets/6-adapters/postgres/src/core/control-adapter.ts
  • packages/3-targets/6-adapters/postgres/test/control-adapter.test.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/native-enum-infer-adoption.integration.test.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/native-enum-infer-diagnostic.integration.test.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/native-enum-introspection.integration.test.ts
  • test/integration/package.json
  • test/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]>
@wmadden-electric
wmadden-electric added this pull request to the merge queue Jul 10, 2026
Merged via the queue into main with commit 05b915f Jul 10, 2026
21 checks passed
@wmadden-electric
wmadden-electric deleted the infer-native-enum-adoption branch July 10, 2026 10:20
wmadden-electric added a commit that referenced this pull request Jul 10, 2026
…+ 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]>
wmadden-electric added a commit that referenced this pull request Jul 10, 2026
…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]>
paulwer pushed a commit to paulwer/prisma-next that referenced this pull request Jul 12, 2026
….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]>
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants