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

TML-2918: PG AddColumn — schema-qualified op ids + codecRef round-trip - #837

Merged
wmadden-electric merged 6 commits into
mainfrom
pg-addcolumn-opid-and-codecref-roundtrip
Jun 16, 2026
Merged

wmadden-electric merged 6 commits into
mainfrom
pg-addcolumn-opid-and-codecref-roundtrip

Conversation

@wmadden-electric

@wmadden-electric wmadden-electric commented Jun 16, 2026 •

Copy link
Copy Markdown
Contributor

Linked issue

Refs TML-2918 — Phase-2 follow-up of Marker/ledger via typed query AST. Two correctness gaps deferred from Slice 7 (#813) under tracker note task_41556b53.

At a glance

Two changes, both in packages/3-targets/3-targets/postgres/src/core/migrations/op-factory-call.ts:

// 1. AddColumn op id includes schema — was `column.${tableName}.${columnName}`
id: `column.${schemaName}.${tableName}.${columnName}`,
// 2. renderDdlColumnAsTsCall now emits codecRef
function renderDdlColumnAsTsCall(col: DdlColumn): string {
  const opts: string[] = [];
  if (col.notNull) opts.push('notNull: true');
  if (col.primaryKey) opts.push('primaryKey: true');
  if (col.default) opts.push(`default: ${renderDdlColumnDefault(col.default)}`);
  if (col.codecRef) opts.push(`codecRef: ${jsonToTsSource(col.codecRef)}`);   // ← added
  // …
}

Before this PR, two tables with the same name in different schemas (e.g. public.user.email and audit.user.email) collided on their AddColumn op id — the planner/runner's key for uniqueness, drift detection, and ledger entries. And a DdlColumn carrying a codecRef would round-trip — migration.ts → re-parse → re-emit — without it, silently losing the codec mapping the DDL walker uses to encode literal defaults.

Reviewer notes

  • Sibling defect intentionally out of scope. NOT-NULL columns without defaults take a different code path: AddNotNullColumnDirectCall → buildAddColumnOperationIdentity in planner-recipes.ts, which still produces the old column.${table}.${column} format. Same correctness defect, different site. Flagged in the dispatch artifact (dispatches/01-fixes.md) as a follow-up sweep. The pgvector planner-behavior test helper was updated to dynamically select the correct op-id format based on whether the column is nullable / has a default — when the follow-up lands and the formats converge, the dynamic helper can revert to a literal assertion.
  • One unbound-namespace literal surfaces in tests. In postgres-control-policy-planner.test.ts, the contract is constructed namespace-less, so schemaName resolves to the UNBOUND_NAMESPACE_ID sentinel and the op id renders as column.__unbound__.users.email. Mechanically correct under the new format; whether the sentinel should be rendered differently in op ids is a separate design question.
  • CodecRef render shape. jsonToTsSource(col.codecRef) — same form already used in this function for col.name / col.type. CodecRef is { codecId: string, typeParams?: ... }, JSON-renderable; no exotic fields. col()'s DdlColumnOptions already accepts codecRef via spread, so the re-parsed DdlColumn round-trips identically without changes to the factory.
  • Largest commit is the op-id fix (91dc9fa8d) because it shifts test literals across the postgres package; the cross-package test update (7c2970b04) followed when the heavy suites surfaced two stale assertions outside the postgres package.

Decision

This PR ships two scoped fixes:

  1. AddColumn op ids include schemaName — column.${schema}.${table}.${column}. Eliminates the cross-schema collision; the planner/runner now has a uniquely-keyed identifier for every AddColumn op.
  2. renderDdlColumnAsTsCall serializes codecRef — present round-trip preserved across migration.ts re-emission, so codec-routed default encoding doesn't silently fall back to raw-literal wire semantics.

Behavior changes & evidence

  • AddColumn op ids are now schema-qualified. Two same-named tables in different schemas produce distinct op ids; the planner emits ids of shape column.<schema>.<table>.<column>. Implementation: op-factory-call.ts (AddColumnCall.toOp). Evidence: cross-schema-uniqueness test in op-factory-call.construction.test.ts; existing op-id literal assertions in op-factory-call.lowering.test.ts updated to the new format.
  • AddColumnCall.renderTypeScript() preserves codecRef across migration-source round-trips. A DdlColumn carrying a codecRef re-emits as col(name, type, { …, codecRef: { codecId: '…', typeParams: { … } } }); re-parsing yields a DdlColumn whose codecRef deep-equals the original. Implementation: op-factory-call.ts (renderDdlColumnAsTsCall). Evidence: three new round-trip tests in op-factory-call.rendering.test.ts.

Testing performed

  • pnpm build, pnpm typecheck, pnpm lint:code, pnpm lint:packages, pnpm lint:deps, pnpm lint:casts, pnpm fixtures:check — all green.
  • pnpm test:packages — 829/830 (one flaky CLI file test/control-api/client.test.ts — passes 28/28 in isolation; known recurring CLI parallel-load flake).
  • pnpm test:integration — 1089/1089 tests passed; exit 1 from a trailing teardown error only (no test failures).
  • Targeted re-runs of the flaky CLI test and the failing integration tests confirmed in isolation.

Skill update

n/a — internal only. No CLI command, public API, config, or error-code surface changes. The op-id format change is observable on ops.json for ops authored against this branch; existing migrations on origin/main did not regenerate (the planner only produces the new format for new ops, and fixtures:check is clean).

Follow-ups

  • Sibling site for op-id schema namespacing. AddNotNullColumnDirectCall → buildAddColumnOperationIdentity in planner-recipes.ts still produces column.${table}.${column}. Small, scoped, separate PR.

Alternatives considered

  • Widen this PR to cover the sibling buildAddColumnOperationIdentity site. Rejected: it's a different code path, in a different file, exercised by different tests — keeping the slice scoped to the originally-deferred items (AddColumnCall.toOp + renderDdlColumnAsTsCall) means one self-contained change per PR. The sibling sweep is tracked above.
  • Render __unbound__ differently in the namespace-less op-id case. Out of scope — that's a question about how the sentinel surfaces in user-visible identifiers, independent of this slice's "include schemaName" intent. Flagged in reviewer notes.

Checklist

  • All commits are signed off (git commit -s) per the DCO. The DCO status check will block merge if any commit is missing a Signed-off-by: trailer.
  • I read CONTRIBUTING.md and the change is scoped to one logical concern.
  • Tests are updated.
  • The PR title is in TML-NNNN: <sentence-case title> form.
  • The Skill update section above is filled in.

Summary by CodeRabbit

  • Bug Fixes
    • Improved migration operation IDs to be schema-aware for add-column scenarios, producing distinct IDs per schema.
    • Updated column TypeScript rendering to include codecRef when provided.
  • Tests
    • Updated migration planner and operation expectations to match the new schema- and namespace-aware add-column operation ID formats.

wmadden-electric and others added 5 commits June 16, 2026 10:22
AddColumnCall.toOp now produces `column.<schema>.<table>.<column>` instead of
`column.<table>.<column>`, matching the pattern used by other op id kinds and
ensuring ops for identically-named columns in different schemas have distinct ids.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
renderDdlColumnAsTsCall now includes `codecRef: {...}` in the rendered col()
call when the DdlColumn carries one, so migration scaffold TypeScript
preserves the codec mapping for re-parse.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…ced format

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
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 June 16, 2026 09:20
@coderabbitai

coderabbitai Bot commented Jun 16, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: ba9066a7-e3a4-4907-a87b-89834d9c1817

📥 Commits

Reviewing files that changed from the base of the PR and between 7c2970b and 008cd59.

📒 Files selected for processing (1)
  • skills/extension-author/prisma-next-extension-upgrade/upgrades/0.13-to-0.14/instructions.md
✅ Files skipped from review due to trivial changes (1)
  • skills/extension-author/prisma-next-extension-upgrade/upgrades/0.13-to-0.14/instructions.md

📝 Walkthrough

Walkthrough

AddColumnCall.toOp now includes schemaName in the generated operation ID (column.<schema>.<table>.<column>). renderDdlColumnAsTsCall conditionally emits codecRef in col() options. Planner logic uses an __unbound__ namespace prefix for nullable/default-bearing columns. All affected tests are updated to match.

Changes

Schema-qualified AddColumn op IDs and codecRef rendering

Layer / File(s) Summary
Source: schema-qualified ID and codecRef
packages/3-targets/3-targets/postgres/src/core/migrations/op-factory-call.ts
AddColumnCall.toOp generates column.<schema>.<table>.<column> instead of column.<table>.<column>. renderDdlColumnAsTsCall appends codecRef to col() options when present.
Unit tests: construction, lowering, and codecRef rendering
packages/3-targets/6-adapters/postgres/test/migrations/op-factory-call.construction.test.ts, op-factory-call.lowering.test.ts, op-factory-call.rendering.test.ts
Construction test expects schema-prefixed op.id and adds a cross-schema uniqueness assertion. Lowering test updates expected ID to column.public.user.email. Rendering adds four codecRef test cases (presence, typeParams, round-trip equality, absence).
Planner and E2E tests: __unbound__ namespace and schema-qualified IDs
packages/3-extensions/pgvector/test/migrations/planner.behavior.test.ts, planner.contract-to-schema-ir.test.ts, packages/3-targets/6-adapters/postgres/test/migrations/planner.fk-config.test.ts, test/integration/test/cross-package/postgres-control-policy-planner.test.ts, test/integration/test/cli-journeys/migration-round-trip.e2e.test.ts
pgvector planner conditionally computes opId with __unbound__ prefix for nullable/default columns. All planner and E2E assertions updated to reflect new __unbound__ and schema-qualified ID forms. Documentation updated to note test-only changes.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Suggested reviewers

  • aqrln

Poem

🐇 Hop, hop! The schema's joined the id's name,
__unbound__ columns now play a new game.
codecRef nestles in col()'s embrace,
Each schema unique — no more ambiguous space.
The tests all nod along, tidy and neat,
Another migration made perfectly sweet! 🥕

🚥 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 pull request title clearly and specifically describes the main changes: schema-qualified operation IDs and codecRef round-trip support for PostgreSQL AddColumn operations.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch pg-addcolumn-opid-and-codecref-roundtrip

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 and usage tips.

@github-actions

github-actions Bot commented Jun 16, 2026 •

Copy link
Copy Markdown

size-limit report 📦

Path Size
postgres / no-emit 153.29 KB (0%)
postgres / emit 121.55 KB (0%)
mongo / no-emit 78 KB (0%)
mongo / emit 72.09 KB (0%)
cf-worker / no-emit 181.7 KB (0%)
cf-worker / emit 146.74 KB (0%)

@pkg-pr-new

pkg-pr-new Bot commented Jun 16, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@prisma-next/extension-author-tools

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

@prisma-next/mongo-runtime

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

@prisma-next/family-mongo

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

@prisma-next/sql-runtime

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

@prisma-next/family-sql

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

@prisma-next/extension-arktype-json

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

@prisma-next/middleware-cache

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

@prisma-next/mongo

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

@prisma-next/extension-paradedb

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

@prisma-next/extension-pgvector

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

@prisma-next/extension-postgis

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

@prisma-next/postgres

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

@prisma-next/sql-orm-client

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

@prisma-next/sqlite

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

@prisma-next/extension-supabase

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

@prisma-next/target-mongo

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

@prisma-next/adapter-mongo

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

@prisma-next/driver-mongo

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

@prisma-next/contract

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

@prisma-next/utils

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

@prisma-next/config

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

@prisma-next/errors

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

@prisma-next/framework-components

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

@prisma-next/operations

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

@prisma-next/ts-render

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

@prisma-next/contract-authoring

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

@prisma-next/ids

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

@prisma-next/psl-parser

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

@prisma-next/psl-printer

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

@prisma-next/cli

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

@prisma-next/cli-telemetry

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

@prisma-next/emitter

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

@prisma-next/migration-tools

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

prisma-next

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

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

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

@prisma-next/mongo-codec

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

@prisma-next/mongo-contract

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

@prisma-next/mongo-value

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

@prisma-next/mongo-contract-psl

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

@prisma-next/mongo-contract-ts

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

@prisma-next/mongo-emitter

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

@prisma-next/mongo-schema-ir

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

@prisma-next/mongo-query-ast

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

@prisma-next/mongo-orm

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

@prisma-next/mongo-query-builder

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

@prisma-next/mongo-lowering

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

@prisma-next/mongo-wire

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

@prisma-next/sql-contract

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

@prisma-next/sql-errors

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

@prisma-next/sql-operations

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

@prisma-next/sql-schema-ir

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

@prisma-next/sql-contract-psl

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

@prisma-next/sql-contract-ts

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

@prisma-next/sql-contract-emitter

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

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

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

@prisma-next/sql-relational-core

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

@prisma-next/sql-builder

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

@prisma-next/target-postgres

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

@prisma-next/target-sqlite

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

@prisma-next/adapter-postgres

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

@prisma-next/adapter-sqlite

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

@prisma-next/driver-postgres

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

@prisma-next/driver-sqlite

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

commit: 008cd59

…l for 0.13→0.14

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
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 Jun 16, 2026
Merged via the queue into main with commit 5ce94dd Jun 16, 2026
20 checks passed
@wmadden-electric
wmadden-electric deleted the pg-addcolumn-opid-and-codecref-roundtrip branch June 16, 2026 10:36
wmadden-electric added a commit that referenced this pull request Jun 16, 2026
…ified form (pre-existing main drift)

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
wmadden-electric added a commit that referenced this pull request Jun 16, 2026
…-2918

Post-rebase regen: TML-2918 (#837) landed schema-qualified op ids
(`column.${schema}.${table}.${column}`) for the PG AddColumn op. The
prisma-next-demo migration ops.json files now carry `column.public.*`
ids; migrationHash updates accordingly.

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
…isma#841)

## Decision

Type SQL enum columns using a **baked storage column lookup** computed
in the SQL family emitter. The storage plane now carries its own map of
column types — keyed `[namespace][table][column]` — so the query builder
reads it with a single indexed access and never reaches across into
domain-keyed tables.

```ts
// What a consumer sees — unchanged from before
type PriorityField = FieldOutputTypes['public']['Post']['priority'];
//=> 'low' | 'high' | 'urgent'

// What the query builder reads — new, storage-keyed surface
type PriorityColumn = StorageColumnTypes['public']['post']['priority'];
//=> 'low' | 'high' | 'urgent'
```

Both maps are flat literal types baked at emit time. No type-level
traversal anywhere in the emitted `.d.ts`.

## Vocabulary

- **Domain layer** — the model/field view of data;
`FieldOutputTypes`/`FieldInputTypes` key by `[namespace][model][field]`.
- **Storage layer** — the table/column view; the new
`StorageColumnTypes` keys by `[namespace][table][column]`.
- **Value-set** — the set of allowed string values for an enum column,
stored as a `valueSet` entry in the SQL namespace and enforced by a
CHECK constraint.
- **Reference (ref)** — in the emitted contract, a column may carry a
`valueSet` ref that names the owning value-set entry. The rejected
design from PR prisma#833 followed this ref at the type level; this PR bakes
the resolution into the emitter.

## Why baked lookup, not ref-following

PR prisma#833 (closed) typed each enum column by following the `valueSet` ref
through the contract at the type level — an expression of the form
`ContractBase['storage']['namespaces'][Ns]['entries']['valueSet'][Ref]['members'][number]['value']`,
re-evaluated for every column in every selected row type. This was
rejected on two grounds:

1. **TypeScript evaluation cost is the binding constraint.** A
ref-following expression compounds type instantiations: one multi-hop
traversal per column, nested inside the query result's mapped type,
repeated for every selected column. On a contract with many tables this
hits TypeScript's "excessively deep" limit and stalls the language
server. A baked literal property access — `StorageColumnTypes[Ns][T][C]`
— pulls nothing else into the type graph and costs exactly one indexed
access.

2. **The real defect was the cross-plane reach, not the lookup table.**
The old query builder typed columns via a path that walked storage
column → domain model field → `FieldOutputTypes`. The lookup table was
the correct tool; the bug was reaching into a domain-keyed table from
the storage plane. Giving storage its own column-type lookup removes the
reach at the root.

The baked lookup exists for exactly this reason: derivation happens once
in the emitter (generator code), not on every consumer type evaluation.

## What changed

**SQL family emitter** (`packages/2-sql/3-tooling/emitter`):
- Emits a top-level `StorageColumnTypes` map — codec output narrowed by
value-set literals for enum columns, parameterized codec types for
`Char<N>`/`Vector<N>` columns, plain codec output otherwise.
- Derives `FieldOutputTypes`/`FieldInputTypes` from `StorageColumnTypes`
at emit time via the field→column mapping each model carries. The
derivation is a domain→storage projection, the legal read direction.
- Framework emitter (`packages/1-framework/3-tooling/emitter`) gains a
`resolveFieldType` hook that the SQL family answers from its column
lookup. No value-set or column knowledge enters the framework layer
(A5).

**Query builder** (`packages/2-sql/4-lanes/sql-builder`,
`packages/2-sql/4-lanes/query-builder`):
- `ResolvedColumnTypes` and `ExtractOutputType` index
`StorageColumnTypes` directly. The
`FindModelForTable`/`FindFieldForColumn` walk and the
`FieldOutputOverride` fallback chain are deleted.
- ORM (`packages/2-sql/4-lanes/relational-core`,
`packages/3-extensions/sql-orm-client`) is unchanged —
`ComputeColumnJsType` still reads `FieldOutputTypes`; its source file is
byte-identical to main.

**No-emit path** (`packages/2-sql/2-authoring/contract-ts`):
`StorageColumnChannelTypes` added — a structural projection re-keyed
from models to tables, re-using `FieldChannelType` per entry. No new
ref-following. The `enum-surface.types.test-d.ts` tests keep passing.

**SQL-only realization**: Mongo is unchanged — collections are ~1:1 with
model fields, no cross-plane reach to fix. `MongoTypeMaps` is untouched.

## Verification

**Self-checks:**
- `grep -rn 'ContractBase\['
examples/prisma-next-demo/src/prisma/contract.d.ts` → empty (A4: no
ref-following in emitted output)
- `grep -rnE 'valueSet|ValueSetRef|StorageColumn|EnumValuesResolver'
packages/1-framework/3-tooling/emitter/src/` → empty (A5: framework
stays target-agnostic)
- `git diff --stat origin/main HEAD -- ':(glob)**/contract.json'` →
empty (A7: contract.json/hashes byte-identical)
- `FieldOutputTypes` block in the demo `contract.d.ts` byte-identical to
main

**Reviewer break-and-revert evidence** (rev-2886-v2b, verdict SATISFIED,
branch tip `44816fe9e`):
- Char/Vector refinement guard: switching `renderRefinedCodecType` to
`if (false && …)` collapsed parameterized types in both maps;
`resolved-field-types.test-d.ts` failed naming `Char<36>` explicitly.
- Value-set narrowing guard: switching `if (column.valueSet)` to `if
(false && …)` collapsed `Post.priority` to `string`; all three
`expectTypeOf().toEqualTypeOf<'low' | 'high' | 'urgent'>()` assertions
in `demo-dx.types.test.ts` bit — covering the direct `FieldOutputTypes`
index, the query-builder row type, and the ORM-via-typed-rows path.

**D3 gate:**
- `pnpm build` ✓, `pnpm typecheck` (138 packages) ✓, `pnpm
fixtures:check` ✓
- `pnpm lint:deps` ✓, `pnpm lint:casts` ✓, `pnpm check:upgrade-coverage
--mode pr` ✓
- Targeted suites (`@prisma-next/sql-contract-emitter`,
`@prisma-next/emitter`, `@prisma-next/sql-orm-client`,
`@prisma-next/sql-builder`, `@prisma-next/sql-relational-core`) ✓
- `@prisma-next/integration-tests typecheck`, `prisma-next-demo
typecheck` ✓
- Full `pnpm test:packages` ✓

## Alternatives considered

- **Ref-following (PR prisma#833, rejected).** Type each column by following
the `valueSet` ref at the type level through the emitted contract.
Rejected: TS evaluation cost is unbounded across large contracts; the
cross-plane type-level traversal is the violation this work was meant to
fix.
- **Keep cross-plane reach, fix nothing.** Storage continues typing
columns via domain `FieldOutputTypes`. Rejected: wrong read direction;
breaks enum typing for raw value-set columns with no domain field.
- **Storage-encapsulated lookup with derivation (chosen).** Bake storage
column types in the emitter; derive field types from storage types. The
derivation captures the honest data-flow direction, and both lookups are
flat literals — O(1) indexed access for consumers.

## Upgrade coverage

The `examples/` and `packages/3-extensions/` diffs are purely generated
artifacts: the new `StorageColumnTypes` block appears in every
regenerated `contract.d.ts`; `FieldOutputTypes` is byte-identical to
main; `contract.json` and hashes are unchanged. No consumer action
required — a re-emit picks up `StorageColumnTypes` automatically.
Declared incidental in
`skills/upgrade/prisma-next-upgrade/upgrades/0.13-to-0.14/instructions.md`
and
`skills/extension-author/prisma-next-extension-upgrade/upgrades/0.13-to-0.14/instructions.md`.

## Context

This is a redo of closed PR prisma#833. The original cut followed the
`valueSet` ref at the type level; this redo bakes the resolution in the
emitter. Design pivot recorded in
`projects/enums-as-domain-concept/slices/type-columns-from-valueset-ref/spec.md`.
Commit `23e8809b8` on this branch is a pre-existing fixture drift fix
(migration op-id format from prisma#837), kept here so `fixtures:check` stays
green.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **Bug Fixes**
* Improved generated type definitions so database column shapes are
handled more consistently across supported projects.

* **Documentation**
* Updated upgrade guidance to reflect the latest type-generation
behavior and clarify that no consumer action is required.

* **Tests**
* Expanded type-level coverage for generated contracts and query
building to verify column typing and enum handling.
<!-- 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 Sonnet 4.6 <[email protected]>
paulwer pushed a commit to paulwer/prisma-next that referenced this pull request Jul 12, 2026
…uildAddColumnSql (prisma#840)

## Linked issue

Refs [TML-2919](https://linear.app/prisma-company/issue/TML-2919). First
slice of [Typed DDL migration ops — complete the
conversion](https://linear.app/prisma-company/project/typed-ddl-migration-ops-complete-the-conversion-9a86e44d4c38)
(Phase 2 of the marker-ledger typed-query-AST work). PG-first.

## At a glance

The not-null-with-temporary-default recipe used to glue its ADD COLUMN
step as raw SQL; it now builds the typed `AddColumn` DDL node and lowers
it through the adapter — the same path `AddColumnCall` already uses:

```ts
// planner-recipes.ts — buildAddNotNullColumnWithTemporaryDefaultOperation
const ddlColumn = new DdlColumn({ ...spec, notNull: true, default: new FunctionColumnDefault(temporaryDefault) });
const addColumn = await lowerer.lowerToExecuteRequest(
  contractFreeDdl.alterTable({ schema, table, actions: [contractFreeDdl.addColumnAction(ddlColumn)] }),
);
```

`buildAddColumnSql` (the last raw ADD COLUMN string-builder) is deleted.

## Decision

1. **Convert the not-null-temp-default recipe to the typed path.** Its
ADD COLUMN step lowers a typed `AddColumn` node; prechecks/postchecks
lower through the adapter; the lowerer is threaded through (the recipe
is already async). `AddNotNullColumnDirectCall` now carries a real
`DdlColumn` (from the shared `buildColumnSpec`) instead of a pre-built
SQL string.
2. **Delete `buildAddColumnSql`** (+ its export + tests). `git grep
buildAddColumnSql` is empty. After this, the only PG op still on raw SQL
is `CreateExtension` — its own slice (TML-2920, an entity-kind modeling
change).
3. **Data-transform `EXISTS(<user sql>)` wrapper stays raw —
sanctioned.** Its inner check is user-supplied SQL, lowered to `{sql,
params}` before the wrapper is built, so there's no `SelectAst` to feed
`cfExpr.exists()`; typing it would need new AST substrate, out of scope.
Left with a comment marking it the sanctioned user-SQL-adjacent remnant.

## Behavior change (benign, reviewed)

The temporary default now renders `DEFAULT (expr)` (via
`FunctionColumnDefault`) instead of `DEFAULT expr`. Every value the
recipe can produce is an atomic primary (literal / keyword / typecast /
bit-string), so the parentheses are pure grouping — semantically
identical in Postgres. No committed `ops.json` pins the recipe's output;
the pgvector `planner.behavior.test.ts` assertions were updated to the
parenthesized form.

## Verification

- Fresh workspace typecheck 138/138; target-postgres 320 /
adapter-postgres 629 / pgvector 140 pass.
- `pnpm test:integration` 1089/1089 (PGlite — the recipe executes here;
isolated re-run, the per-run flakes are the documented PGlite load
flakes).
- `pnpm fixtures:check` clean; `pnpm lint:deps` clean; cast ratchet
delta 0.
- Focused review (principal-engineer lens): SATISFIED, no blockers.

## Follow-ups

- `buildCreateTableSql` is now callerless but still exported — left for
a later slice (deletes with the remaining table-builder cleanup).
- The TML-2918/prisma#837 example migrations carry stale unqualified op-ids
(`column.<t>.<c>`) because prisma#837 didn't regenerate the example chains;
not caught by CI (`fixtures:check` doesn't diff `ops.json`).
Pre-existing, out of this slice — worth a regen follow-up.

## Checklist

- [x] All commits signed off (DCO).
- [x] Scoped to one logical concern (PG recipe conversion + dead-builder
deletion).
- [x] Tests updated.
- [x] Title in `TML-NNNN: <sentence-case>` form.
- [x] Skill update: n/a — internal refactor, no public-surface/behavior
change for consumers.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **Refactor**
* Improved PostgreSQL DDL generation for NOT NULL column operations with
temporary defaults, transitioning to typed structures for enhanced
consistency and maintainability.
  * Updated default value formatting in generated SQL statements.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
paulwer pushed a commit to paulwer/prisma-next that referenced this pull request Jul 12, 2026
…substrate; delete workspace (prisma#867)

## Linked issue

Close-out of [Marker/ledger via typed query
AST](https://linear.app/prisma-company/project/markerledger-via-typed-query-ast-dc62ab25d151).
Phase-2 op porting + the project's deferred ADR migrate into the new
project [Typed DDL migration ops — complete the
conversion](https://linear.app/prisma-company/project/typed-ddl-migration-ops-complete-the-conversion-9a86e44d4c38)
(TML-2919/2920/2921/2922/2923/2925/2927/2866).

## At a glance

```
137 files changed, 9067 deletions(-)
```

Removes `projects/migrate-marker-ledger-to-typed-query-ast-commands/`
after the final retro, and migrates the durable design notes (the seven
design principles, the DDL visitor + dispatch model, the table-level
constraint shape, the codec-handling split, the planner-lowering
mechanism, the Mongo runner-boundary lowering) into the successor
project's workspace as draft material for **TML-2923**'s ADR. No
source-code changes. External-reference scan was clean before the
delete.

The design notes land at
[`projects/typed-ddl-migration-ops/typed-ddl-design-notes.md`](projects/typed-ddl-migration-ops/typed-ddl-design-notes.md)
— the workspace of the successor "Typed DDL migration ops" project,
whose `spec.md`/`plan.md` arrive on `main` with PR
[prisma#840](prisma#840) (in flight). The
notes are voice-rewritten to strip the project-shaping framing (the
close-out workflow's Step 4.5 disposition) and banner-marked as
draft-for-TML-2923 — its ADR slice absorbs/replaces this file when it
lands.

## Decision

Project closes; workspace is deleted. The project's DoD is met or
explicitly-deferred-with-ticket:

1. All 11 slices merged.
2. Final retro recorded (commit `36279033f` immediately preceding the
delete).
3. Long-lived methodology — the seven design principles + the
DDL-as-target-contributed-AST model + the table-constraint shape +
codec-handling split + planner lowering mechanism — migrated to the
successor project's workspace as draft material that TML-2923's ADR
absorbs. The canonical ADR ("DDL as a target-contributed query-AST kind
+ adapter DDL-lowering seam") + Adapters & Targets / Migration System
subsystem-doc updates are owned by TML-2923 in the successor project,
where the dust from Phase-2's remaining design decisions has to settle
first.
4. No external references to the project dir; nothing to re-point or
remove.

## Project DoD verification (acceptance criteria in
[spec.md](https://github.com/prisma/prisma-next/blob/fbcda64af/projects/migrate-marker-ledger-to-typed-query-ast-commands/spec.md))

| AC | Status | Evidence |
|---|---|---|
| Team-DoD floor | ✅ met | repo-wide gates green on every merged slice;
Linear close-out via this PR; ADR audit covered by AC prisma#9 (deferred) |
| SQL query AST represents `CREATE TABLE` + `CREATE SCHEMA` as
target-contributed nodes | ✅ met | Slice 1 (TML-2761, foundational) —
merged |
| All in-scope marker/ledger ops execute via `adapter.lower()` → driver;
zero `db.collection()` in `marker-ledger.ts` | ✅ met | Slice 2 (TML-2753
SQL) + Slice 3 (TML-2825 Mongo) — both merged |
| Each family's marker CRUD behind one control-adapter SPI; duplicate
read paths + `parseContractMarkerRow` + raw-SQL write builders collapsed
| ✅ met | TML-2753 outcome (sql-marker-ops-through-adapter) |
| `SqlControlAdapter` exposes marker-write methods symmetric with
`MongoControlAdapter` | ✅ met | TML-2753 |
| Contract-free construction surface per family; no in-scope op
hand-builds nodes by object literal or concatenates raw SQL | ✅ met |
TML-2761 (SQL DDL surface) + TML-2825 corrective round 2 (Mongo).
Phase-2 op-porting tracked by TML-2919/2920/2921/2922 in the successor
project. |
| Two `as` casts in Mongo `marker-ledger.ts` eliminated; cast ratchet
not regressed | ✅ met | TML-2825 |
| Invariant-merge converges on accumulate-dedupe across PG + SQLite;
test pins for both dialects | ✅ met | TML-2753 |
| Migration planner adopts typed AST across all three targets (or
residual deferred with tracked follow-ups) | ✅ met | Phase 1 closed:
Slice 5 SQLite ([prisma#768](prisma#768) /
TML-2859), Slice 7 PG ALTER
([prisma#813](prisma#813)), Slice 6 Mongo
([prisma#816](prisma#816) / TML-2888).
Residual op-porting deferred to the successor project. |
| ADR "DDL as a target-contributed query-AST kind + adapter DDL-lowering
seam" + subsystem-doc updates (Adapters & Targets, Migration System) | 🟡
partially met | Durable design notes migrated to
[`projects/typed-ddl-migration-ops/typed-ddl-design-notes.md`](projects/typed-ddl-migration-ops/typed-ddl-design-notes.md)
as draft material; canonical ADR + subsystem-doc updates owned by
**TML-2923** in the successor project, where the dust from Phase-2's
remaining design decisions has to settle first. |

## Slices merged in this project

| Slice | Linear | PR |
|---|---|---|
| `ddl-in-query-ast` (foundational) | TML-2761 | merged |
| `sql-marker-ops-through-adapter` | TML-2753 | merged |
| `mongo-marker-ledger-through-adapter` | TML-2825 | merged |
| `planner-create-table-adopts-ddl-ast` | TML-2754 |
[prisma#751](prisma#751) |
| `codec-routed-ddl-defaults` | TML-2867 |
[prisma#794](prisma#794) |
| `sqlite-create-table-adoption` (Phase 1) | TML-2859 |
[prisma#768](prisma#768) |
| `pg-add-column-pioneer` (Phase 1) | — |
[prisma#813](prisma#813) |
| `mongo-planner-create-collection-and-index-adoption` (Phase 1) |
TML-2888 | [prisma#816](prisma#816) |
| `typed-migration-verification-queries` | TML-2889 |
[prisma#825](prisma#825) |
| `un-namespaced-pg-defaults-to-public` | TML-2916 |
[prisma#838](prisma#838) |
| `pg-addcolumn-opid-and-codecref-roundtrip` | TML-2918 |
[prisma#837](prisma#837) |

## What follows in the successor project

[Typed DDL migration ops — complete the
conversion](https://linear.app/prisma-company/project/typed-ddl-migration-ops-complete-the-conversion-9a86e44d4c38)
owns:

- **TML-2919** (in flight as
[prisma#840](prisma#840)) — PG: remaining
raw-SQL op-builders → typed DDL; delete `buildAddColumnSql`.
- **TML-2920** — PG: model `CREATE EXTENSION` as first-class entity
kind.
- **TML-2921** — SQLite: convert op execute steps to typed DDL.
- **TML-2922** — SQLite: `RecreateTable` + AST growth (`CASE WHEN`,
row-tuple `IN`).
- **TML-2866** — SQLite inline-autoincrement: stop smuggling column
options through `DdlColumn.type`.
- **TML-2923** — ADR + subsystem docs (the deferred AC prisma#10 from this
project).
- **TML-2925** — Rewrite `dataTransform` op factory: defer lowering,
type the EXISTS wrapper.
- **TML-2927** — Introduce `PostgresTableRef` end-to-end (typed table
refs).

## Reviewer notes

- **Deletion is the only behavioral change** — 56 files removed, 5087
deletions, zero additions outside the final retro. Source code,
fixtures, examples, and tests are untouched.
- **External-reference scan was empty** before delete (`rg -l
"projects/migrate-marker-ledger-to-typed-query-ast-commands/" --glob
'!projects/migrate-marker-ledger-to-typed-query-ast-commands/**' --glob
'!.git/**'` returned no matches). No links to re-point.
- **The two commits are intentionally split** (`docs(marker-ledger):
final close-out retro` then `chore: close out … — delete workspace`) so
the final retro is preserved as a tracked commit on `main` for
archeology if anyone later asks "how did Phase 2 get extracted out
cleanly?"
- **The migrated doc is *draft material*, not a finished ADR.** The
design notes capture the steady-state architecture (the principles, the
visitor/dispatch model, the constraint shape, the codec split, the
lowering mechanism); they live in the successor project's workspace
alongside its `spec.md`/`plan.md`, where TML-2923's ADR slice
absorbs/replaces it. Writing the canonical ADR here, before the
remaining Phase-2 design decisions (TML-2919/2920/2921/2922) land, would
produce a doc that drifts within weeks.
- **The doc lands on `main` before the successor project's workspace
does** (TML-2919/prisma#840 also creates `projects/typed-ddl-migration-ops/`
but is in flight). If this PR merges first, my commit creates the dir;
if prisma#840 merges first, my file lands next to its spec/plan. Either order
works.

## Testing performed

- Worktree gates not re-run for a delete-only PR; the merged slices each
shipped with their own gate runs.
- `rg` reference scan confirmed pre-delete.

## Skill update

n/a — internal project workspace removal.

## Checklist

- [x] All commits signed off (DCO).
- [x] Scoped to one logical concern (project close-out).
- [x] Tests are updated — `n/a` (delete-only, no behavioral change).
- [x] PR title in `<TICKET-or-scope>: <sentence-case title>` form.
- [x] **Skill update** filled in (`n/a`).

---------

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Co-authored-by: Claude Sonnet 4.6 <[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