Skip to content

TML-3278: a field's domain type matches its column, and every stored value and default is read by its codec - #30451

Merged
wmadden merged 118 commits into
mainfrom
tml-3278-psl-typeparams-list-fields
Oct 1, 2026
Merged

wmadden merged 118 commits into
mainfrom
tml-3278-psl-typeparams-list-fields

Conversation

@wmadden-electric

@wmadden-electric wmadden-electric commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

At a glance

A contract has a domain half, the fields as the application sees them, and a storage half, the columns. The same declared type used to come out differently in the domain half depending on how it was written:

types {
  Short = VarChar(10)
}

enum Role {
  @@type("pg/text@1")
  ADMIN = "admin"
  USER  = "user"
}

type Address {
  code Short
  role Role
}

model Member {
  id    Int     @id
  role  Role
  roles Role[]  @noCheck(elementNotNull)
  code  Short
  home  Address
}

Before this PR, on main:

  • roles Role[] had no domain valueSet, although role Role did.
  • code Short had no domain typeParams, although the same field written code VarChar(10) had { length: 10 }.
  • The composite member Address.code lost its typeParams, and Address.role lost its valueSet.

After this PR, a field's domain type is the same whether it is single or a list, inline or named, on a model or on a composite type member. The storage half and every hash are unchanged.

What this PR changes

  1. The PSL interpreter no longer rewrites domain fields after the shared SQL contract builder built them. That rewrite is what dropped typeParams and valueSet.
  2. The builder builds every domain field through one function: model scalar fields, model value-object fields, and composite type members. It no longer hard-codes Postgres jsonb for value objects; the storage type comes from the target the stack declares.
  3. A field or member typed by a named type carries the named type's parameters in its domain type. The SQL emitter no longer looks them up in storage.
  4. Value-object fields: a multi-table-inheritance variant links to a base keyed by one; a list of them takes @default([]) or a JSON array literal for its one column; a default must match the composite type, with each member value read by the member's codec; a stack with no value-object storage refuses the field instead of dropping it; an attribute inside a type block is refused instead of ignored.
  5. Every built-in codec's decodeJson, SQL and Mongo, refuses a JSON value that is not a stored form of its type, including one its type parameters rule out (VarChar(3) holding "toolong"), instead of passing it through. The rule is stated once, on Codec.decodeJson, and the checks live in one set of shared readers. Float codecs read and write "NaN", "Infinity" and "-Infinity", and a non-finite float default renders in DDL. mongoCodec no longer compiles a codec narrower than JsonValue without a decodeJson.
  6. prisma contract print writes and reads back enum list fields, parameterized and enum-typed composite members, and value-object list defaults.
  7. One function writes every column default to SQL: a new table, a new column, a changed default, a rebuilt SQLite table. It reads each literal, and each list element, through the column's codec, so a default the codec refuses stops with CONTRACT.DEFAULT_INVALID naming the table and column instead of reaching the database.
  8. A changed default on an existing Postgres column is now applied. Before, the migration runner skipped the SET DEFAULT because the old default already satisfied its check, and verification then failed.
  9. Verification compares PostgreSQL type names through one normaliser, so a column written with an alias (char, varchar, int, float) or without a length (Char, Bit) verifies after apply instead of reporting a mismatch. A numeric column takes every scale PostgreSQL accepts, including a negative one.
  10. The CLI reports a library error under its own code, removes the connection string from every field of it, and lets a Prisma bug surface as an internal error instead of reporting it as the user's mistake.

Of the 427 changed files, about 160 are source and documentation; the rest are tests and regenerated contracts and fixtures.

Why the domain fields were wrong

The PSL interpreter (packages/2-sql/2-authoring/contract-psl/src/interpreter.ts) resolves each field to a column descriptor and hands model nodes to the shared contract builder (packages/2-sql/2-authoring/contract-ts/src/build-contract.ts), which builds the domain field. The interpreter then ran a second pass that replaced every scalar list field and every value-object field with an object built from a few properties, dropping the rest.

That pass existed because the builder's value-object node hard-coded Postgres jsonb storage, while PSL takes the storage type from the target. The interpreter sent value-object fields to the builder disguised as scalar columns and patched the result. Composite type members were hand-built twice, once in the interpreter and once in the builder, and the two copies had drifted.

Value objects are built once

ValueObjectFieldNode now carries its storage descriptor, and the builder reads it like any column. Composite types reach the builder as ValueObjectNodes whose members are ScalarMemberNode or ValueObjectMemberNode; a model field is a member with a column (FieldNode extends ScalarMemberNode). A member is typed by ScalarTypeDescriptor, a codec id and type parameters only, so it cannot carry a column name or a storage-only value set. buildDomainField builds all of them.

A value-object default is now read the way the database will read it: a list field takes an array, a single field an object, keys must be members, required members must be present, and each member value goes through the member codec's decodeJson. An enum member must hold one of the enum's values.

Codecs check the JSON they read

Checking member values through their codecs exposed that many codecs' decodeJson was a cast: pg/text@1 returned a number unchanged, so {"street": 1} on a String member loaded, and a hand-edited contract with "default": 1 on a text column passed. decodeJson also runs on database-produced JSON for relation includes, so every accepted form was checked against what Postgres and SQLite actually write (to_json, json_agg, json_group_array), including text[] NULL elements, padded char, infinity timestamps and float NaN. Each codec now refuses anything else with RUNTIME.DECODE_FAILED naming the codec and the value. Where a type has a constraint the database enforces, the codec checks it too: on PostgreSQL, char/varchar length, bit/varbit length, numeric precision and scale, and the int4 range. Each check was compared against what PostgreSQL itself accepts. A shared SQL codec checks only what every SQL target stores, and the PostgreSQL target adds its own rules where it adapts the codec; SQLite enforces no declared length, so its codecs check none. A uuid default is written in the canonical form PostgreSQL stores, whatever spelling the schema used, and pg/uuid@1 reads only that form.

The checks are one set of readers in @internal/framework-components/codec (decodeJsonString, decodeJsonInteger, decodeJsonFloat and others), used by the SQL, PostgreSQL, SQLite and Mongo codecs and by pgvector and PostGIS. The rule they implement is written once, on Codec.decodeJson; the ADRs and the codec authoring guide point at it.

The float codecs previously refused the "NaN" PostgreSQL writes, so an include of a row holding NaN failed; that is fixed, and SQLite's float projection now writes an infinity as the same text. A .default(Infinity) renders as 'Infinity'::float8 on PostgreSQL and 9e999 on SQLite.

The Mongo runtime reads documents through decode, not decodeJson; its decodeJson is used by the PSL enum reader, which accepted "low" as an int32 member. The mongoCodec factory defaulted decodeJson to identity, which is where the pattern came from; it is now required for narrower types.

Every default goes through one renderer

Once codecs checked the JSON they read, the remaining gap was the paths that wrote a default without reading it at all: Postgres SET DEFAULT, and SQLite ADD COLUMN and table rebuilds rendered their own SQL. Each adapter now implements one renderColumnDefault, used by CREATE TABLE and by every planner operation, so all four paths refuse and render identically. Replacing the Postgres SET DEFAULT path exposed that the runner skipped a changed default whose old value satisfied the operation's check; a changed default now always runs. SQLite reads a BigInt default back as a number, so its codec now stores the canonical digit text, and PostgreSQL int8 defaults compare through the same canonical form. The migration.ts that migration plan writes carries each column's codec on both targets, so running it writes exactly what the planner would. A migration.ts still written in the earlier setDefault({ defaultSql }) form stops with MIGRATION.OPERATION_OPTION_REMOVED instead of silently dropping the default.

The text-backed date and time codecs now read only ISO forms, as the Temporal codecs already did, so an include of such a column needs PostgreSQL's default DateStyle of ISO.

Tests

Each behaviour change has a test that failed before its fix: interpreter and builder tests assert whole field and diagnostic shapes; table-driven decode-form tests per codec; codec conformance cases against live Postgres and SQLite; PGlite integration tests reading text[]/int4[] with NULL elements and float NaN/Infinity through relation includes; printer round-trip cases; a type-level test that a narrow mongoCodec without decodeJson does not compile.

Fixtures regenerated by pnpm fixtures:check gain domain entries only. No storage, profile or execution hash moves. The example migration snapshots are regenerated by the same command; user snapshots need no change, because snapshot checks recompute the storage hash only.

Upgrading

upgrade-instructions/pending/domain-types-match-their-columns/ records the changes for applications and extension authors, each with its fix:

  • Re-emit the contract. prisma contract print refuses a contract emitted before this change until it is re-emitted.
  • Some schemas that loaded on main are refused at contract emit: a value-object default of the wrong shape or with a member value its codec refuses, an attribute inside a type block, a SQL enum member its @@type codec does not take, and a literal default its column type rules out (VarChar(3) @default("toolong"), Uuid @default("nope")).
  • A literal default of the wrong JSON kind in a hand-edited contract.json fails when a migration is planned.
  • pg/text-array@1 now reads a NULL element as null and its type is readonly (string | null)[]. Writing NaN through sqlite/real@1 now throws instead of storing NULL.
  • A Mongo codec narrower than JsonValue needs a decodeJson.
  • A contract with a uuid default written in another spelling gets a new storage hash when re-emitted; the note says how to bring a database up to it.
  • mapCaughtMigrationError is removed from @prisma/orm-toolchain/cli/control-api; errorFromCaught replaces it.
  • A hand-written migration.ts that calls setDefault with defaultSql, or builds SQLite column specs with defaultSql, no longer compiles and stops with MIGRATION.OPERATION_OPTION_REMOVED when run; it takes the column instead. Its ops.json still applies. A migration planned by an earlier version that changes a default must have its setDefault call rewritten and its migration.ts run again (or be deleted and planned again), so the default is actually set.
  • An include of a text-backed date or time column needs DateStyle set to ISO, PostgreSQL's default.

Alternatives considered

  • Delete only the scalar-list rewrite branch. The first version of this PR did that. It fixed the report and left the rewrite pass, the jsonb constant and the duplicated member builders that caused it.
  • Keep the old lenient decodeJson and check value-object member values separately. That would leave hand-edited contracts and relation includes unchecked, and duplicate each codec's knowledge of its own stored form.
  • Accept @default([]) only through a JSON literal on a list of value objects. A list literal is how users write a list default, and it loaded on main.
  • Check type parameters only when a default is authored, not in decodeJson. That would leave hand-edited contracts unchecked and put a second copy of each type's rules outside its codec.

This also fixes TML-2089 (a changed Postgres default was never applied).

Related, and deliberately separate: TML-3341 (composite types always land in the default namespace) and TML-3384 (the Mongo runtime returns a document field as whatever BSON type it holds).

Agent: nestor-25

🤖 Generated with Claude Code

@wmadden-electric
wmadden-electric requested a review from a team as a code owner September 28, 2026 07:59
@coderabbitai

coderabbitai Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository: prisma/orm/.coderabbit.yml

Review profile: CHILL

Plan: Advanced

Run ID: ee476e2d-db25-4d2e-beaf-9ad4757224ae

📥 Commits

Reviewing files that changed from the base of the PR and between 8253664 and 91c49fe.

📒 Files selected for processing (20)
  • docs/reference/error-reference.md
  • packages/2-sql/2-authoring/contract-psl/src/interpreter.ts
  • packages/2-sql/2-authoring/contract-psl/test/interpreter.scalar-list-storage.test.ts
  • packages/2-sql/2-authoring/contract-psl/test/interpreter.value-object-domain.test.ts
  • packages/2-sql/2-authoring/contract-psl/test/interpreter.value-object-storage.test.ts
  • packages/2-sql/2-authoring/contract-psl/test/interpreter.value-objects.test.ts
  • packages/2-sql/2-authoring/contract-ts/src/build-contract.ts
  • packages/2-sql/2-authoring/contract-ts/src/contract-definition.ts
  • packages/2-sql/2-authoring/contract-ts/src/exports/contract-builder.ts
  • packages/2-sql/2-authoring/contract-ts/test/contract-builder.default-refusal.test.ts
  • packages/2-sql/2-authoring/contract-ts/test/contract-builder.value-object-domain.test.ts
  • packages/2-sql/2-authoring/contract-ts/test/contract-builder.value-object-storage.test.ts
  • packages/2-sql/2-authoring/contract-ts/test/contract-builder.value-objects.test.ts
  • packages/2-sql/2-authoring/contract-ts/test/value-object-nodes.test-d.ts
  • packages/3-targets/3-targets/postgres/src/core/psl-print/domain-types.ts
  • packages/3-targets/3-targets/postgres/src/core/psl-print/refusals.ts
  • packages/3-targets/3-targets/postgres/test/psl-pg-enum-column.test.ts
  • packages/3-targets/3-targets/postgres/test/psl-print/refusals-storage.test.ts
  • test/integration/test/psl-print/authored-contract-roundtrip.integration.test.ts
  • test/integration/test/psl-print/extension-types-roundtrip.integration.test.ts
💤 Files with no reviewable changes (2)
  • packages/2-sql/2-authoring/contract-ts/test/contract-builder.value-objects.test.ts
  • packages/2-sql/2-authoring/contract-psl/test/interpreter.value-objects.test.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • test/integration/test/psl-print/authored-contract-roundtrip.integration.test.ts
  • test/integration/test/psl-print/extension-types-roundtrip.integration.test.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 4 remain after this review.


📝 Walkthrough

Walkthrough

The authoring pipeline now represents value-object members separately from storage fields and carries their type parameters, nullability, list shape, and enum metadata into contracts. The PostgreSQL printer handles supported parameterized and enum-backed members, with updated validation and round-trip coverage.

Changes

Value-object field interpretation and printing

Layer / File(s) Summary
Represent and build value-object members
packages/2-sql/2-authoring/contract-ts/src/contract-definition.ts, packages/2-sql/2-authoring/contract-ts/src/build-contract.ts, packages/2-sql/2-authoring/contract-ts/src/exports/contract-builder.ts, packages/2-sql/2-authoring/contract-ts/test/*
The node model separates column-free scalar and value-object members from storage fields. Contract construction derives domain fields and storage columns from the unified nodes and preserves member metadata, including authored enum references.
Lower resolved fields into contract nodes
packages/2-sql/2-authoring/contract-psl/src/interpreter.ts, packages/2-sql/2-authoring/contract-psl/src/psl-field-resolution.ts, packages/2-sql/2-authoring/contract-psl/test/*
The interpreter builds value-object nodes from composite types and lowers model fields into scalar or value-object field nodes. Resolved fields no longer retain scalarCodecId; tests cover list metadata, enum references, and storage mapping.
Print supported member types and enum fields
packages/3-targets/3-targets/postgres/src/core/psl-print/*, packages/3-targets/3-targets/postgres/test/*, test/integration/test/psl-print/*, docs/reference/error-reference.md
The PostgreSQL printer renders supported parameterized member types and enum-backed scalar or list members. Validation checks enum references and codec constraints; tests cover refusals and round trips.

Priority: ➖ Normal

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Bug fix

Sequence Diagram(s)

sequenceDiagram
  participant PSL as PSL schema
  participant Interpreter as PSL interpreter
  participant Builder as SQL contract builder
  participant Printer as PostgreSQL PSL printer
  PSL->>Interpreter: Resolve model and composite fields
  Interpreter->>Builder: Supply field and value-object nodes
  Builder->>Printer: Provide contract with member descriptors
  Printer->>PSL: Render supported member types
Loading

Suggested reviewers: tensordreams

Merge Risk: ⚪ Minimal · up to 91c49

No actionable issue remains from this review; the change is ready for normal merge checks.

Security Architecture Review

Security architecture risk: 🟡 Moderate · up to 91c49

The change affects contracts used to describe database fields, but the reviewed paths retain type resolution and consistency checks. No new security weakness was established. Validation before a generated contract is used for SQL remains insufficiently evidenced, so a minimal-risk assessment would be premature.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The relevant exposure is authored schema input becoming domain metadata, storage-column metadata, and printable PostgreSQL types. The reviewed change does not establish a new runtime caller or attacker privilege.

Trust Boundaries and Controls

  • observed — Descriptor resolution and composite-member diagnostics constrain PSL input before node construction; builder and printer checks constrain conflicting or underived enum metadata afterward.

Hardening Proposals

  • proposed — Confirm that enum handles resolve to declared enums and that duplicate field or member names are rejected before generated contracts are used for SQL; the focused evidence does not establish those preconditions or a PR-introduced failure.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 42.42% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 33 functions across 26 files. (1 skipped:… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
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.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the codec-based field and default handling changes. It is specific and related to a major part of the pull request, although it does not mention list fields or composite…
Full details: Docstring Coverage

Explanation

Docstring coverage is 42.42% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 33 functions across 26 files. (1 skipped: 1 unsupported.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR

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

@wmadden-electric
wmadden-electric force-pushed the tml-3278-psl-typeparams-list-fields branch from 3d1fa13 to 287ccc2 Compare September 28, 2026 08:05
@pkg-pr-new

pkg-pr-new Bot commented Sep 28, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@prisma/orm-extension-arktype-json

npm i https://pkg.pr.new/@prisma/orm-extension-arktype-json@30451

@prisma/orm-extension-middleware-cache

npm i https://pkg.pr.new/@prisma/orm-extension-middleware-cache@30451

@prisma/orm-extension-paradedb

npm i https://pkg.pr.new/@prisma/orm-extension-paradedb@30451

@prisma/orm-extension-pgvector

npm i https://pkg.pr.new/@prisma/orm-extension-pgvector@30451

@prisma/orm-extension-postgis

npm i https://pkg.pr.new/@prisma/orm-extension-postgis@30451

@prisma/orm-extension-supabase

npm i https://pkg.pr.new/@prisma/orm-extension-supabase@30451

@prisma/orm-family-mongo

npm i https://pkg.pr.new/@prisma/orm-family-mongo@30451

@prisma/orm-family-sql

npm i https://pkg.pr.new/@prisma/orm-family-sql@30451

@prisma/orm-framework

npm i https://pkg.pr.new/@prisma/orm-framework@30451

@prisma/orm-mongo

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

@prisma/orm-postgres

npm i https://pkg.pr.new/@prisma/orm-postgres@30451

@prisma/orm-sqlite

npm i https://pkg.pr.new/@prisma/orm-sqlite@30451

@prisma/orm-target-mongo

npm i https://pkg.pr.new/@prisma/orm-target-mongo@30451

@prisma/orm-target-postgres

npm i https://pkg.pr.new/@prisma/orm-target-postgres@30451

@prisma/orm-target-sqlite

npm i https://pkg.pr.new/@prisma/orm-target-sqlite@30451

@prisma/orm-toolchain

npm i https://pkg.pr.new/@prisma/orm-toolchain@30451

commit: f8e8d9e

@github-actions

github-actions Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

size-limit report 📦

Path Size
postgres / no-emit 212.72 KB (+1.34% 🔺)
postgres / emit 191.02 KB (+1.46% 🔺)
mongo / no-emit 195.71 KB (+0.34% 🔺)
mongo / emit 174.98 KB (+0.35% 🔺)
cf-worker / no-emit 268.58 KB (+1.24% 🔺)
cf-worker / emit 244.24 KB (+1.31% 🔺)

@wmadden-electric wmadden-electric changed the title TML-3278: PSL list fields keep their type parameters, enum value set and composite-type member type parameters TML-3278: PSL list fields and composite members keep their full type; value-object fields are built once by the contract builder with target-declared storage Sep 28, 2026
wmadden-electric and others added 22 commits September 30, 2026 12:00
… composite type members

Scalar list fields on models lost typeParams: patchModelDomainFields rebuilt
every scalar list field from only its codec id, nullability and many. The shared
domain field builder already emits many: true and typeParams from the model
node, so the branch is deleted, along with the now-unread
ResolvedField.scalarCodecId. The same branch also dropped valueSet on
text-backed enum list fields and typeParams.typeName on pg.enum list fields, so
the regenerated integration fixtures now carry them.

Composite type members were built with only the codec id. They now include the
resolved descriptor typeParams when present.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…ameterized composite type members

The PSL printer refused two shapes the PSL interpreter now emits. It required an
enum list field to carry no domain valueSet, so every Enum[] field was refused.
It refused any composite type member with type parameters, so members such as
Numeric(65, 30) or pgvector.Vector(3) were refused.

The printer now expects the domain valueSet on list fields as on single fields,
and prints composite type members with their type parameters, single and list.
It still refuses a composite type member that carries a valueSet.

The two interpreter test files for list fields are merged into one that asserts
whole field shapes.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
… built once, by the contract builder, with target-declared storage

The PSL interpreter sent value-object fields to the SQL contract builder as
scalar fields, then overwrote the domain fields the builder produced
(patchModelDomainFields). It also built composite type members by hand, apart
from the builder, and dropped the domain valueSet of enum-typed members.

ValueObjectFieldNode now carries the storage descriptor, and the builder stores
the field in a column of that descriptor instead of a hard-coded pg/jsonb
column. The interpreter resolves the descriptor from the target-declared
valueObjectStorageType, emits ValueObjectFieldNodes, and passes composite types
to the builder as ValueObjectNodes. The builder builds model domain fields and
value-object members through one function, so members keep many, typeParams and
the domain valueSet of an enum. patchModelDomainFields is deleted.

The Postgres PSL printer now writes an enum-typed composite member as the enum
name, and refuses only a value set the PSL source would not derive.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…n name

A scalar member of a value object was a FieldNode, so it had to carry a
columnName although a member has no column. It is now a ScalarMemberNode:
field name, descriptor, nullability, list marker and enum handle. FieldNode
extends it with the column, defaults and noCheck. ValueObjectNode.fields is
(ScalarMemberNode | ValueObjectRefNode)[], and buildDomainField takes either
member shape; model fields pass as their subtypes.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…rs "members"

The printer said "value-object field" for a member of a value object, while
contract-ts uses that name for a model field typed by a value object. The
refusals, messages and error reference now say "value-object member".

The member value-set refusal now states in its message that the member must
have no type parameters, and gains tests for a member naming an enum the
domain does not declare and for a member with type parameters.

The enum-member round-trip case is labelled as a guard: it did not fail on
the old code, it fails when the interpreter emits a member value set the
printer does not write.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
… not a column

- Rename ValueObjectRefNode to ValueObjectMemberNode, so the pairs read the
  same way: a *MemberNode has no column, a *FieldNode has one.
- A scalar member is typed by MemberTypeDescriptor (codec id and type
  parameters). FieldNode keeps the full column descriptor.
- isValueObjectNode is the one predicate for the node kinds, used by the
  builder and the PSL interpreter.
- One helper builds both refs of an authored enum. A field that carries an
  enum handle and a storage value set from its type constructor is now an
  invariant failure instead of a silent precedence.
- Delete the unread domainFieldRefs and the comments that said the domain
  field takes its type parameters from the storage column.
- PSL resolves composite members against the default namespace, with its
  extension entities and the codec lookup, as it does for model fields. A
  member typed pg.enum(E) is now refused with PSL_UNSUPPORTED_FIELD_TYPE,
  saying a member has no column to store a storage enum in. Before, it
  failed with "no entity named E was found in namespace (unspecified)".
- Value-object tests are split by what they prove: storage, domain, and
  scalar list storage. Duplicated cases are merged; storage cases that
  passed before the builder change are grouped as guards.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…ur they keep

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…elper, which no longer takes them

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…ase keyed by a value-object field

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…has the named type parameters in its domain type

A member typed by a PSL named type kept only the codec, and a model field typed by one had no domain type parameters, unlike the same type written inline. The domain type now takes the named type parameters inline, for model fields in the builder and for members in the PSL interpreter. The printer compares a field with its column through the column named type, and writes a member typed by a named type inline.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
…fault of its one column

A list of value objects is stored in one column, so its default is read by that column type, as a JSON literal, not as a list literal. The storage shape now decides this, as it already did for @nocheck.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
…e parameters only when it carries none

A member whose type parameters its codec rejects now reports the codec error instead of a refusal claiming the member carries no parameters.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
…or what they are

isValueObjectNode becomes isValueObjectMember, MemberTypeDescriptor becomes ScalarTypeDescriptor and BuildValueObjectsInput becomes BuildValueObjectNodesInput; neither isValueObjectMember nor ScalarTypeDescriptor is exported any longer, since nothing outside the package reads them. The printer names the refs of a domain enum by plane, like the builder. The type test is named for what it proves and asserts that a member descriptor has no storage part. Member print cases move out of the storage refusals into their own file.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
…he value-object docs

A literal default on a value object and on a list of value objects is tested on the real SQLite stack. The SQLite storage test asserts the id field and column it used to compare to themselves, and the storage bridge test reads the contract without a cast. The error reference states the member refusals by the conditions the printer checks, the spec describes where list type parameters come from today, and the polymorphism pass result is named for what it holds.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
… types

The value-object defaults test also reads the loaded storage as SQL storage, which the integration typecheck requires.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
…of value objects

A list of value objects is stored in one column whose value is the list. A list literal such as `@default([])` fills that value element by element and gives the same default as the JSON literal json`[]`. A list literal on a single value object is still refused.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…cts is written

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…object storage is refused, not dropped

A field typed by a composite type was skipped without a word when the stack declares no value-object storage type, so the field was lost. It is now PSL_UNSUPPORTED_FIELD_TYPE, naming the field, the composite type and the target. The Postgres and SQLite adapters both declare a storage type, so no shipped stack reaches this.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…e snapshot edits

The fragment is renamed domain-types-match-their-columns and lists the four domain additions: named-type parameters on model fields, the enum value set on enum list fields, and type parameters and enum value sets on composite type members. Migration snapshots need no change: with the pre-change snapshots in place, migration check, list, graph, status, plan, show and db migrate and verify all succeed.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…h its named type

resolvedTypeParams, next to toStorageTypeInstance, returns a type's own parameters or else its named type's, and reads empty parameters as none, as a codec does. The builder's column default codec and domain field, the PSL interpreter's composite members, the printer's field and column check and member native type, the SQL emitter's column types and the relational codec ref all call it. Emitted contracts and default encoding are unchanged.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…e only

The SQL emitter looked up a named type's parameters in storage through EmissionSpi.resolveFieldTypeParams, because the domain field used not to carry them. The SQL contract builder now puts them in the domain for every SQL source, so the hook is removed from the SQL emitter, from EmissionSpi and from the framework field-type maps. No other family implemented it. Emitted contract.d.ts files are unchanged. ADR 208 and the emitter subsystem doc describe the current behaviour.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
… a list column

storedAsListColumn says a list of scalars is stored in a list column and a list of value objects is not, because its one column holds the whole list as one JSON array. The builder and the PSL interpreter both call it, and the PSL default and @nocheck inputs name its answer isListColumn.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
wmadden-electric and others added 13 commits September 30, 2026 19:22
This brings in seven main commits: the rc.14 release, Mongo values
through their field's codecs (#30519), `sql` as the tag of
sql/expression (#30534), view bodies parsed as fields only in Prisma 7
and 6 schemas (#30507), and three docs and CI changes.

Both sides' rules hold after the merge.
- Mongo codecs: main's encode checks and this branch's decodeJson
  readers are combined, and the int32 bounds use INT32_RANGE.
- One test codec from main now has the decodeJson that mongoCodec
  requires.
- contract-psl: main's tag reading and sql/expression default replace
  the lowering entry. This branch's stored-value reader, InternalError
  rethrows, list-column and value-object default checks, and
  CodecLookupWithDescriptors are kept.
- A value-object default of the wrong shape uses main's renamed code,
  PSL_VALUE_TYPE_INCOMPATIBLE. A Uuid default the text-to-uuid cast
  refuses is PSL_INVALID_LITERAL, like any other cast refusal.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…as a decode or encode failure

An InternalError marks a bug in Prisma, not a bad value. The runtimes wrapped
every error a codec threw that was not a structured error, so an InternalError
reached the caller as RUNTIME.DECODE_FAILED or RUNTIME.ENCODE_FAILED, which
reads as a problem with the user's data.

Each place that wraps a codec failure now rethrows an InternalError unchanged:
- SQL runtime: result decoding, including each element of a list column, and
  parameter encoding, including each element of a list parameter
- Mongo runtime: document field decoding
- Mongo adapter: parameter encoding
- SQL ORM client: decoding an included relation's values

A plain Error from a codec is still wrapped, with the error on `cause`.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…lumn's codec

`migration plan` builds a new table's columns with their codec, so the
ops.json it writes reads each literal default with the codec. The SQLite
migration.ts it writes next to it left out `codecRef` on each `col(...)`, so
running that file wrote the defaults unread: `DEFAULT '9007199254740993'` for
a BigInt where the plan wrote `DEFAULT 9007199254740993`, and a hand-edited
`lit('not a date')` for a DateTime went through. It now writes `codecRef` as
the PostgreSQL renderer does, and the file writes the plan's ops.json.

`node migration.ts` now also writes an error a library raised with a
structured code, such as CONTRACT.DEFAULT_INVALID, with that code, as it
already did for the CLI's own errors.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…RATION.OPERATION_OPTION_REMOVED

An earlier version wrote a column default in migration.ts as SQL text:
PostgreSQL `setDefault({ column: '<name>', defaultSql })`, and SQLite column
specs with `defaultSql`. `node migration.ts` does not check types, so such a
file still ran: SQLite left the default out of the ops.json it wrote, and
PostgreSQL failed with a bare TypeError.

PostgreSQL `setDefault` and SQLite `addColumn` and `recreateTable` now refuse
that form with MIGRATION.OPERATION_OPTION_REMOVED. The error names the
operation, the table and the column, says how to write the call now or to
plan the migration again, and names the upgrade entry that shows the new
form.

The upgrade notes say so. `postgres-changed-default-applied` no longer tells
users to run an earlier migration.ts as it is: they rewrite its `setDefault`
call first, or delete the package and plan again.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
The extension note covered only the migration.ts form of the change in which
the adapter writes every column default. A new entry,
`adapter-writes-column-defaults`, lists the public SPI changes with detection
that matches the TypeScript that breaks:

- `ExecuteRequestLowerer` and `SqlControlAdapter` gain a required
  `renderColumnDefault(column, table)`, with what an adapter or a fake
  lowerer must write.
- `buildColumnDefaultSql` is removed from `target/planner-ddl-builders`.
- `SetDefaultCall` takes the column instead of its name and SQL text.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…tes a single value

The adapter read each element of a list default with the column's codec, then
threw the encoded elements away and wrote the ARRAY from the contract's JSON.
A single value was written from the codec's wire value, so lists and single
values had two writers, and they disagreed where the JSON form is not the
text PostgreSQL reads: a `bytea[]` default wrote its base64 text as the bytes,
and a string element of a `jsonb[]` default was not JSON.

One writer now serves both. Each element is written as a single value is,
without its own cast: a date or time value as its type's text, a value the
codec reads as SQL NULL as NULL, and anything else as the codec's wire value.
The list is cast to its type once. Every other list the tests and fixtures
write renders as before.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…th sides

PostgreSQL type names were normalised in three places with overlapping alias
tables: `normalizeSchemaNativeType` for the introspected side,
`canonicalPostgresTypeName` for the contract side, and the adapter's
`normalizeFormattedType` for `format_type` output. A new alias had to be added
to each. The rule that a bare `character` or `bit` has length 1 was also
written twice.

`normalizeSchemaNativeType` is now the one normaliser. It maps each alias,
`... with time zone` and `... without time zone`, and a list type's element,
and both sides use it. `normalizeFormattedType` keeps only the `format_type`
handling of lists and quoted user-defined names. `withLengthOneWhenBare`
holds the length rule.

The expected `format_type` of a column with type parameters is now displayed
as PostgreSQL displays it: a timestamptz(3) column is
`timestamp(3) with time zone`, not `timestamptz(3)`. Before this, the check
after an ALTER COLUMN TYPE to such a type could never pass.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…e on both targets

Two rules said that a default read back as a number equals its digit text.
SQLite's is on its data type, as ADR 254 puts canonical forms: `sqlite/bigint`
reads a safe integer as digit text. PostgreSQL's was `isInt64NativeType` in
the SQL family core, which named `int8` and `bigint`.

`pg/int8` now has the same canonical form, which both targets share as
`integerTextCanonicalForm` in relational-core: digit text, a safe integer
read as its digit text, and any other number refused. `isInt64NativeType` is
deleted, and its tests move to where the rule now lives.

A BigInt default past 2^53, single and list, applies, verifies strictly and
plans nothing more. Fixtures are unchanged.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
The rc.14 note `temporal-polyfill-is-a-peer-dependency` names only the
target's control entry as importing `temporal-polyfill`. The adapter's
control entry imports the PostgreSQL type constructors from it, so it now
loads the polyfill as well. A new extension entry says so: a Yarn project
that loads only the adapter's control entry in its tests or tooling adds the
polyfill to its devDependencies. The released note is unchanged.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ults

- The Mongo int32 encoders check their range with `isIntegerIn`.
- The ADR 208 example writes its migration with the current API, without the
  removed `defaultSql`.
- `renderColumnDefaultDdl` built a column and rendered nothing; it is now
  `buildSetDefaultColumn`.
- `SetDefaultCall` no longer copies its column's name into `columnName`. The
  planner's conflict location and the control policy's subject read the
  column's name through `columnNameOfCall`, which also names the column of an
  `AddColumnCall`, which they missed before.
- The SQLite column helper's comment no longer names the deleted
  `buildColumnDefaultSql`.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ues, Prisma 6 Mongo storage

introspectedNativeType from main names a formatted type through the one normaliser, so the alias rules are written once.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
… through the shared readers

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…L stores, and the default fidelity test builds codecs as contract infer does

The default parser writes a uuid literal, and each uuid list element, in the canonical form the uuid cast writes, so contract infer prints it as a literal its codec reads. The fidelity test from main builds each column codec through the type constructor with its type parameters, and a default the column would round (numeric(10,2) DEFAULT 12.345) is now expected to be refused by the codec.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
@wmadden-electric wmadden-electric changed the title TML-3278: PSL list fields and composite members keep their full type; value-object fields are built once by the contract builder with target-declared storage TML-3278: a field's domain type matches its column, and every stored value and default is read by its codec Oct 1, 2026
@wmadden-electric
wmadden-electric force-pushed the tml-3278-psl-typeparams-list-fields branch from 91c49fe to f8e8d9e Compare October 1, 2026 05:09
@wmadden-electric wmadden-electric changed the title TML-3278: a field's domain type matches its column, and every stored value and default is read by its codec TML-3278: a field's domain type matches its column, and every stored value and default is read by its codec Oct 1, 2026
@wmadden
wmadden enabled auto-merge October 1, 2026 05:14
@wmadden
wmadden added this pull request to the merge queue Oct 1, 2026
Merged via the queue into main with commit 5d664d5 Oct 1, 2026
27 checks passed
@wmadden
wmadden deleted the tml-3278-psl-typeparams-list-fields branch October 1, 2026 05:35
wmadden-electric added a commit that referenced this pull request Oct 1, 2026
TML-3278 (#30451) moved the Postgres type constructors from the adapter
to the target's type-constructors.ts, and contract infer now finds a
column's codec through the stack's type constructors instead of the
CODEC_ID_BY_INFERRED_TYPE table. So the branch's edits to that table and
to the adapter's constructor block are dropped; the infer type names
already resolve to the text date codecs through the constructors.

- README: main's printing paragraph, with this branch's wording for the
  type contract print prefers.
- date-codecs.ts: main's isRepresentable and parseDate, using the shared
  EARLIEST_POSTGRES_TIMESTAMP_MILLISECONDS; encodeDate still formats
  through utcTimestamptzText.
- infer-default-codec.ts and control-mutation-defaults.ts: main's
  versions. The comment edit on the text date constructors moves to
  type-constructors.ts.
- inferred-psl.round-trip.test.ts: main's constructors from the stack,
  plus this branch's date and time default round-trip cases.
- postgres-type-map.test.ts: looks up each inferred type's codec through
  the stack's type constructors, since the table it used is gone.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
wmadden-electric added a commit that referenced this pull request Oct 1, 2026
#30451 landed the same fix this branch made: every Postgres
column default, in CREATE TABLE, ADD COLUMN and SET DEFAULT, and each
element of a list default, is read through the column codec by the
adapter's renderColumnDefault, and setDefault takes the column as
col(name, type, { default, codecRef }).

This merge resolves every file this branch touched to main's version.
It drops the branch's renderLiteralDefaultSql, SetDefaultAction,
setDefault option shape, the per-element casts in list defaults, the
upgrade fragments for that option shape, and the README and
error-reference text describing them. The pieces main lacks follow in
separate commits.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
brbousnguar pushed a commit to brbousnguar/orm that referenced this pull request Oct 1, 2026
…es it, and members that store one value are refused (prisma#30512)

## Linked issue

Refs [TML-3360](https://linear.app/prisma-company/issue/TML-3360). The
bug itself, an upper-case uuid default making `db init` fail, was fixed
on `main` by prisma#30451 (TML-3278). This PR adds the end-to-end
test for it and closes the gap that fix leaves in TypeScript enums.

## At a glance

```ts
enumType('Key', uuid,
  member('A', 'A0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A11'),
)
```

On `main` this builds. The uuid codec writes the member in lower case,
so the contract and the CHECK constraint hold `a0eebc99-…`, but the
member's TypeScript type is still the literal `'A0EEBC99-…'`. So
`db.enums.public.Key.members.A` is typed as one string and holds
another. With this PR, `defineContract` refuses it:

```text
CONTRACT.ENUM_INVALID: enumType("Key"): member "A" is written "A0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A11", but the column stores "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11". Write the member as "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11".
```

## Decision

1. **A TypeScript enum member must be written the way its column stores
it.** `main` already refuses a member its codec does not accept at all.
This adds the case the codec accepts but stores differently, such as an
upper-case or braced uuid, or the number `1` on a bigint column, which
stores `"1"`. The error gives the value to write.
2. **Two enum members that store the same value are refused**, in
TypeScript and in PSL enum blocks, and the error names both.
3. **PSL enum blocks read their members through one shared function.**
The loop existed in three copies that had drifted: the SQL family, the
Mongo family and a contract-psl test fixture. It now lives once, in
`framework-components`.
4. **An end-to-end test for TML-3360.** It runs `db init` and `db verify
--strict` on PGlite for uuid defaults in every spelling Postgres reads,
and for uuid enums.

## Reviewer notes

- **This PR shrank after a merge with `main`.** It originally also
converted uuid defaults and PSL enum members to lower case.
prisma#30451 landed first and does the default conversion itself. It
also makes each codec refuse values its type does not store, and
`pg/uuid` now reads only lower-case 8-4-4-4-12 text, so an upper-case
uuid member in a PSL enum is now refused at emit rather than converted.
For uuids, PSL and TypeScript enums therefore agree: write the member as
it is stored. PSL still converts a spelling a codec reads but stores
differently, such as int8 `"01"` stored as `"1"`; that is harmless
there, because PSL enum types are generated from the emitted contract.
This PR's duplicate code for those paths was removed in the merge, in
favour of `main`'s.
- **Small breaking change for TypeScript authors**, recorded in
`upgrade-instructions/pending/enum-members-written-as-stored/app/instructions.md`.
An `enumType` member that is accepted but stored differently now fails
at `defineContract`. No example, fixture or extension in the repo is
affected.
- **Mongo sees one change from the shared function.** Duplicate members
are compared by the value the codec stores instead of by
`String(value)`. So `1` and `"1"` on Mongo's lenient codecs are no
longer treated as one member, and two Dates in the same second but with
different milliseconds are no longer duplicates.
- **The TypeScript check compares a member with what its codec writes
into the contract.** It is exact for uuid. It cannot yet catch codecs
that keep values as written while Postgres stores another form; see the
follow-ups.

## How it fits together

1. **Where the TypeScript check runs.** `encodeEnumMembers` in
`packages/2-sql/2-authoring/contract-ts/src/build-contract.ts` encodes
each member through its codec. `main`'s refusal for a member the codec
rejects runs first. Then the new check compares the stored value, read
back through the codec, with the value as written. A bigint member `1n`
is stored as `"1"` but reads back as `1n`, so it still passes. Finally,
the duplicate check runs on the stored values.
2. **The shared PSL reader.** `readEnumBlockMembers` reads each member
through the block's codec, reports a member the codec refuses at that
member's position in the schema, and reports two members that store one
value. The SQL and Mongo enum factories and the contract-psl fixture
call it.
3. **The error reference.** `CONTRACT.ENUM_INVALID` in
`docs/reference/error-reference.md` now lists every case by its
`reason`, including `main`'s `codec-refused-member` and the new
`member-not-stored-as-written` and `duplicate-member-value`.

## Testing performed

- `pnpm test`, `pnpm lint`, `pnpm typecheck` in framework-components,
family-mongo, contract-prisma6, contract-psl, contract-ts, family-sql,
the postgres extension and target-postgres, with each package's coverage
threshold met
- `test/integration/test/uuid-defaults`
- the default fidelity table, 103 of 103
- `pnpm fixtures:check`, `pnpm check:error-reference`, `pnpm lint:deps`,
`pnpm check:upgrade-coverage --mode pr --prev origin/main`
- `gitleaks git` over this PR's commits: no leaks. Two matches on fixed
test uuids are in `.gitleaksignore`, with the reason.

## Skill update

The upgrade fragment above is published into the `prisma-8/upgrading`
app skill at release. No other shipped skill documents enum member
spelling.

## Follow-ups

Each is older than this PR:

- [TML-3383](https://linear.app/prisma-company/issue/TML-3383): numeric,
inet, timestamp-as-string and float codecs keep values as written, such
as `01.5` or `10.0.0.1/32`, while Postgres stores another form, so the
TypeScript check cannot catch those members yet.
- [TML-3382](https://linear.app/prisma-company/issue/TML-3382):
`db.enums` holds each member's JSON value rather than the decoded one,
so bigint and date members still differ from their type at runtime.
- [TML-3380](https://linear.app/prisma-company/issue/TML-3380): Mongo
ObjectId enum members differing only in case.
- [TML-3381](https://linear.app/prisma-company/issue/TML-3381):
`enumType()`'s own duplicate check compares `String(value)`.

## Alternatives considered

- **Convert TypeScript enum members silently, as `main` does for
defaults.** A default has no literal type to contradict, but an enum
member does: converting it makes the member's type differ from its
value. Refusing with the value to write keeps them equal.
- **Leave the duplicate check to `enumType()`'s own comparison of the
written values.** Two members written differently can store one value,
as `'A0EE…'` and `'a0ee…'` do, so only a comparison of stored values
catches them.

## Checklist

- [x] All commits are signed off (`git commit -s`) per the
[DCO](../CONTRIBUTING.md#developer-certificate-of-origin-dco).
- [x] I read [CONTRIBUTING.md](../CONTRIBUTING.md) and the change is
scoped to one logical concern.
- [x] Tests are updated.
- [x] The PR title is in `TML-NNNN: <sentence-case title>` form.
- [x] The **Skill update** section above is filled in.

Agent: rochester-87
🤖 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**
* Added PostgreSQL UUID normalization across supported UUID spellings,
including UUID defaults and array values.
* **Bug Fixes**
* Enum members are now validated against the values their codecs
actually store. Duplicate stored values and values that do not
round-trip are reported as invalid.
* Improved enum validation diagnostics for duplicate members, codec
rejections, and unsupported encoded values.
* **Upgrade Instructions**
* Existing enum definitions with mismatched stored values may need to be
updated and their database constraints migrated.

<!-- 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 5.5 <[email protected]>
brbousnguar pushed a commit to brbousnguar/orm that referenced this pull request Oct 1, 2026
…nd sql/float@1 lists read as numbers (TML-3358) (prisma#30552)

## At a glance

A hand-written Postgres `migration.ts` that gives an existing column an
`autoincrement()` default:

```ts
this.setDefault({
  schema: 'public',
  table: 'user',
  column: col('id', 'serial', { default: fn('autoincrement()') }),
})
```

On `main` this writes the statement below. Nothing complains until the
migration runs and Postgres reports a syntax error:

```sql
ALTER TABLE "public"."user" ALTER COLUMN "id" SET
```

With this PR, `setDefault` refuses the operation before it renders
anything:

```
CONTRACT.DEFAULT_INVALID: setDefault cannot give the existing column "id" of table "user" an autoincrement() default,
because autoincrement() is written as the column's SERIAL type when the column is created.
Set a sequence default instead, as in fn("nextval('<sequence>'::regclass)").
```

Refs: TML-3358

## The decision

prisma#30451 already sends every Postgres literal default through its column
codec, list elements included, in `CREATE TABLE`, `ADD COLUMN` and `SET
DEFAULT`. This PR started as that same fix and was reduced, after prisma#30451
merged, to the three things `main` still lacks. Main's implementation is
kept everywhere the two overlapped.

## 1. `setDefault` refuses a default it cannot write

Main's `setDefault` writes `ALTER COLUMN ... SET` with nothing after it
in two cases:

- **No default:** the column passed to `setDefault` has no default.
- **`autoincrement()` on a `serial` column:** Postgres can only write
this as the column's `SERIAL` type, when the column is created.

`autoincrement()` on any other type was already refused, but the message
advised switching to `SERIAL`, which leads to the same broken statement.
Both cases now raise `CONTRACT.DEFAULT_INVALID` naming the table and
column, with `reason` set to `set-default-without-default` or
`set-default-autoincrement`. `docs/reference/error-reference.md` lists
both.

## 2. `sql/float@1` on Postgres reads decimal text as a number

The Postgres runtime hands each element of a list column to the element
codec as text. On `main`, `sql/int@1` reads that text through the
Postgres integer codec, but `sql/float@1` used the shared SQL codec,
which returns the text unchanged, so a `sql/float@1` list read back as
an array of strings. `sql/float@1` on Postgres now uses the Postgres
float codec, which reads the text with the same helper as the integer
codec. The shared SQL codecs are unchanged, so SQLite, whose `REAL`
column can hold text, keeps refusing to read that text as a number.

## 3. Tests main lacked

- **Real-database test of stored values.** It covers `bytea`, `bytea[]`,
`jsonb[]` with a string element, `interval` and `interval[]` literal
defaults. Each default is written by `CREATE TABLE` and by the `SET
DEFAULT` operations the planner produces. The test inserts a row and
checks what is stored: the bytea values are the bytes of `hello`, and
the jsonb list holds both elements.
- **pgvector.** A planned `SET DEFAULT` on a `vector(3)` column goes
through the pgvector codec, and a vector of the wrong length is refused.

Both pass on `main` too: prisma#30451 fixed that behaviour, and these tests
now guard it.

## What this does not fix

`db init`, `db update` and `db migrate` still roll back a `bytea` or
`bytea[]` literal default. The schema check that runs after applying
compares `"aGVsbG8="` with the `"\x68656c6c6f"` Postgres prints and
reports a mismatch. Reading a default back through its codec is
TML-3283.

## Testing performed

- Each refusal test and the float-list test failed on `main` before its
fix. The SQLite include test that guards `REAL` columns holding text
passes unchanged.
- Checks run and passing:
  - `pnpm build` and `pnpm typecheck`
- lint and tests for `sql-relational-core`, `target-postgres`,
`target-sqlite`, `adapter-postgres` and `extension-pgvector`
- `pnpm fixtures:check`, `pnpm lint:deps` and `pnpm
check:upgrade-coverage`
- the `control-plane-commands-without-temporal` and `data-type-defaults`
CLI journeys, and every integration file that reads a float column or
float list

## Skill update

`skills/prisma-8/references/migrations.md` gives `setDefault`'s argument
in main's shape: `column: col(name, type, { default, codecRef })`.

## Alternatives considered

- **Keep this PR's own renderer and `setDefault` shape** (`type`,
`default`, `codecRef` beside the column name) and merge it beside
prisma#30451. That would leave two code paths that write a column default, so
it was dropped in favour of main's `renderColumnDefault`.
- **Let `autoincrement()` through `SET DEFAULT` by creating a
sequence.** That means choosing a sequence name and ownership on the
user's behalf. The refusal names the `nextval(...)` default to write
instead.

Agent: atreides-42

🤖 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**
* PostgreSQL migrations now report a clear error when setting a default
on a column without one, or when using `autoincrement()` as a default
for a SERIAL column.
* PostgreSQL float codecs now correctly decode integer-form decimal
values as numbers.
* **Documentation**
* Clarified supported PostgreSQL `setDefault` column configuration,
including literal and expression defaults.
* Documented the cases that make a default invalid and the recommended
sequence-default alternative for autoincrement columns.
* **Tests**
* Added coverage for pgvector default validation and PostgreSQL literal
defaults across several data types.

<!-- 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 5.5 <[email protected]>
shahinsamiur pushed a commit to shahinsamiur/orm that referenced this pull request Oct 6, 2026
shahinsamiur pushed a commit to shahinsamiur/orm that referenced this pull request Oct 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants