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

feat(postgres): adopt typed ALTER TABLE ADD COLUMN (DDL AST pioneer) - #813

Merged
wmadden-electric merged 9 commits into
mainfrom
pg-add-column-pioneer
Jun 11, 2026
Merged

wmadden-electric merged 9 commits into
mainfrom
pg-add-column-pioneer

Conversation

@wmadden-electric

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

Copy link
Copy Markdown
Contributor

At a glance

A migration adds a column:

// before — built raw SQL in the op factory
toOp(): Op { return addColumn(schema, table, { name, typeSql, defaultSql, nullable }); }

// after — builds a typed node that models the grammar, lowered through the adapter
async toOp(lowerer): Op {
  const node = contractFreeDdl.alterTable({ schema, table, actions: [addColumnAction(col)] });
  const { sql, params } = await lowerer.lowerToExecuteRequest(node);   // ALTER TABLE … ADD COLUMN …
  return { …, execute: [step('add column', sql, params)], precheck/postcheck: columnExists(…) };
}

Postgres AddColumn now builds a typed DDL AST node lowered through the control adapter, replacing the raw-SQL addColumn() factory. This is the ALTER TABLE pioneer: CREATE TABLE/CREATE SCHEMA are already adopted; ALTER TABLE is a different shape (mutates an existing object) and the root of ~10 more Postgres subactions in Phase 2, so this slice settles its node shape at the lowest-risk op.

The decision: model the grammar, not a fused per-action node

The Postgres grammar is ALTER TABLE <name> <action> [, <action> …]. The node models that directly:

  • PostgresAlterTable — a frozen PostgresDdlNode carrying schema, table, and actions: AlterTableAction[].
  • AlterTableAction — its own frozen-class polymorphic hierarchy (base + variants + AlterTableActionVisitor), with AddColumnAction(DdlColumn) the only variant in this slice. Phase-2 subactions (DropColumn, AlterColumnType, SetNotNull, constraint ALTERs, …) join the union.
  • A single add is AlterTable { actions: [AddColumnAction(col)] }.

A fused PostgresAlterTableAddColumn node — collapsing the statement and one of its actions into a single kind — was considered and rejected: it isn't how the grammar works, gives you a brittle one-off node per action, and shares no ALTER TABLE structure. (Precedent for a nested action hierarchy inside a node: DdlColumnDefault and DdlTableConstraint.)

Dispatch is accept()-visitor, both layers

The adapter's DDL lowering (pgRenderDdlExecuteRequest) is converted from a hand-written .kind switch to node.accept(PostgresDdlVisitor) — and the action list renders via action.accept(AlterTableActionVisitor). Both gain compiler-checked exhaustiveness: adding a DDL kind or an ALTER action won't build until it's handled. The conversion is behaviour-preserving for CreateTable/CreateSchema (each .kind arm moved verbatim into its visitor method).

Defaults flow through the codec path

AddColumnAction carries a structured DdlColumn (not a pre-rendered SQL string), so its default renders through the same pgRenderDdlColumn → pgRenderDdlColumnDefault codec-encoding path as CreateTable. A codec-routed default (pg/jsonb@1, encrypted columns, …) is encoded correctly — not bypassed by a flattened string.

Authoring surface

addColumn() (a free migration function) becomes this.addColumn({ … }), matching the existing this.createTable()/this.createSchema() methods. The 48 example migrations get shorter (one this.addColumn({ … column: col(…) }) line each).

Column attribute order — byte-parity intentionally not preserved

CreateTable and the old addColumn() factory historically emitted column attributes in different orders (… NOT NULL DEFAULT … vs … DEFAULT … NOT NULL). Unifying onto one shared renderer standardises on … DEFAULT … NOT NULL, which changes CreateTable's emitted SQL. We're pre-release, so the example migration goldens are regenerated rather than preserving two legacy orders behind a per-format renderer split. A new correctness test pins that a column with both a default and NOT NULL renders with no attribute dropped (the gap that would otherwise hide a regression).

Scope

  • PG AddColumn only. The remaining PG ALTER TABLE subactions reuse the shape this slice settles — Phase 2.
  • Left in place: buildAddColumnSql + the not-null-with-temporary-default recipe (a separate emitter, out of scope).
  • Follow-up: a small codec-resolution dedup (extractCodecLookup.forCodecRef vs the runtime resolver) — they share materializeCodec but differ by the runtime's memoization cache, so collapsing isn't trivial; tracked, not forced here.

Verification

pnpm build · pnpm typecheck · DDL lowering suites 22/22 (incl. the new no-attribute-dropped test) · pnpm lint:deps/lint:code/lint:packages clean · pnpm lint:casts delta 0. Every changed example source faithfully declares its columns and its regenerated ops.json/hashes match (verified: no committed golden still uses the old attribute order). The test:packages/fixtures:check prisma-next: command not found failures are a pre-existing PATH issue on the base branch, not from this change.

Slice 7 of migrate-marker-ledger-to-typed-query-ast-commands (Phase 1 — the PG ALTER TABLE pioneer). Builds on the slice-1 DDL substrate and the slice-4 planner-adoption pattern.

Summary by CodeRabbit

  • Refactor
    • Migration authoring moved to a new column-builder pattern for more consistent, type-safe column definitions and regenerated example fixtures.
  • New Features
    • Added ALTER TABLE (add-column) support across the Postgres migration pipeline and improved SQL rendering (DEFAULT now rendered before NOT NULL) and schema-qualified table handling.
  • Tests
    • Expanded tests for ALTER TABLE lowering, rendering, migration round‑trips, and end-to-end DDL snapshots.

wmadden and others added 5 commits June 11, 2026 14:20
Records the settled design: AlterTable {actions:[...]} node shape,
accept()-visitor dispatch at both layers, DdlColumn carrier, and
primaryKey non-issue.

Co-Authored-By: Will Madden <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Introduces PostgresAlterTable and AddColumnAction IR nodes (frozen-class
pattern, visitor dispatch) and lowers them through the control adapter
to a SqlExecuteRequest.

AddColumnCall.toOp() now builds a typed DdlColumn-carrying AlterTable
node rather than raw SQL. AddColumnCall.renderTypeScript() emits
this.addColumn({...}), matching how CreateTableCall uses
this.createTable(). PostgresMigration gains the protected addColumn()
method to support this.

buildColumnSpec() in planner-strategies.ts now returns DdlColumn (via
the col() factory) instead of ColumnSpec, removing the last
ColumnSpec-based code path for new columns. The old addColumn free
function is removed from the migration facade.

pgRenderDdlColumn puts DEFAULT before NOT NULL before PRIMARY KEY, which
matches the pre-existing buildAddColumnSql convention and aligns
column-attribute order across all paths.

Co-Authored-By: Will Madden <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…ddColumn()

The free addColumn() function is removed from the migration facade.
Example migration.ts files now call this.addColumn({ schema, table,
column: col(...) }) and import col from the migration facade.

Co-Authored-By: Will Madden <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…butes for CreateTable

Adds a test case to ddl-create-table-lowering.test.ts pinning that a
column with both `default` and `notNull` set renders DEFAULT before NOT NULL
with neither attribute dropped.

This gap in coverage hid the regression where fixture sources were updated to
drop notNull+default from verified columns while the ops.json still showed the
correct DEFAULT…NOT NULL SQL.

Co-Authored-By: Will Madden <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Signed-off-by: willbot <[email protected]>
… migrations

The sweep that updated example migration.ts files from addColumn() to
this.addColumn() accidentally dropped notNull and default attributes on the
verified bool column in two showcase fixtures:

- 20260601T0727_hotfix: col('verified','bool') → col('verified','bool',{ notNull:true, default:lit(true) })
- 20260601T0728_promote_bob: same fix

The ops.json execute SQL "ALTER TABLE "account" ADD COLUMN "verified" bool DEFAULT true NOT NULL"
was already correct; the migration.ts source is now faithful to that output.

Co-Authored-By: Will Madden <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Signed-off-by: willbot <[email protected]>
@wmadden-electric
wmadden-electric requested a review from a team as a code owner June 11, 2026 15:29
@coderabbitai

coderabbitai Bot commented Jun 11, 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: 5e0e7bdd-0bfa-4479-b58d-0ce702446f90

📥 Commits

Reviewing files that changed from the base of the PR and between 614180b and c856a49.

📒 Files selected for processing (4)
  • skills/upgrade/prisma-next-upgrade/upgrades/0.13-to-0.14/instructions.md
  • test/e2e/framework/test/ddl.test.ts
  • test/integration/test/cli-journeys/migration-round-trip.e2e.test.ts
  • test/integration/test/cross-package/postgres-control-policy-planner.test.ts
✅ Files skipped from review due to trivial changes (1)
  • skills/upgrade/prisma-next-upgrade/upgrades/0.13-to-0.14/instructions.md

📝 Walkthrough

Walkthrough

Adds alter-table DDL nodes and builders, refactors planner/op-factory to use DdlColumn and async lowering, adds PostgresMigration.addColumn, implements ALTER TABLE lowering with DEFAULT-before-NOT NULL ordering, updates tests, and regenerates many migration fixtures to use this.addColumn + col().

Changes

Migration Column-Add DSL Refactoring

Layer / File(s) Summary
DDL contract and builder layer
packages/3-targets/3-targets/postgres/src/core/ddl/nodes.ts, packages/3-targets/3-targets/postgres/src/contract-free/ddl.ts, packages/3-targets/3-targets/postgres/src/exports/ddl.ts, packages/3-targets/3-targets/postgres/src/exports/contract-free.ts
Adds AlterTableAction, AddColumnAction, and PostgresAlterTable DDL node types with visitor support, plus contract-free builder functions addColumnAction() and alterTable() and corresponding exports.
Op-factory & planner refactor
packages/3-targets/3-targets/postgres/src/core/migrations/op-factory-call.ts, packages/3-targets/3-targets/postgres/src/core/migrations/planner-strategies.ts, packages/3-targets/3-targets/postgres/src/core/migrations/issue-planner.ts
Reworks AddColumnCall to accept DdlColumn and async lowering, rewrites TypeScript rendering to emit this.addColumn({ ..., column: col(...) }), and updates planner builders to construct DdlColumn with codec/default metadata.
PostgresMigration.addColumn() API
packages/3-targets/3-targets/postgres/src/core/migrations/postgres-migration.ts
Adds protected addColumn() that validates control adapter and lowers an AddColumnCall to a SqlMigrationPlanOperation.
DDL rendering and ALTER TABLE lowering
packages/3-targets/6-adapters/postgres/src/core/control-adapter.ts
Adds pgRenderAlterTable() to render ALTER TABLE ... ADD COLUMN via action visitor and changes column SQL fragment ordering so DEFAULT appears before NOT NULL/PRIMARY KEY.
Tests: DDL lowering & op-factory
packages/3-targets/6-adapters/postgres/test/ddl-add-column-lowering.test.ts, packages/3-targets/6-adapters/postgres/test/ddl-create-table-lowering.test.ts, packages/3-targets/6-adapters/postgres/test/migrations/*
Adds comprehensive tests for ALTER TABLE ADD COLUMN lowering, updates CreateTable/marker-table expectations for DEFAULT/NOT NULL ordering, and adds AddColumnCall construction/lowering/rendering tests.
Migration fixture updates
examples/prisma-next-demo/fixtures/**/migrations/app/*
Regenerates many example migration fixtures to remove free addColumn helper usage and instead import col and call this.addColumn({ schema, table, column: col(...) }).
Generated migration metadata and ops JSON
examples/prisma-next-demo/migrations/app/20260422T0720_initial/*, examples/prisma-next-demo/migrations/app/*
Updates migrationHash and reorders DEFAULT/NOT NULL fragments in generated ops JSON to match new rendering order.

Sequence Diagram

sequenceDiagram
  participant IssuePlanner
  participant PostgresMigration
  participant AddColumnCall
  participant ExecuteRequestLowerer
  participant ControlAdapter
  IssuePlanner->>PostgresMigration: produce AddColumnCall(DdlColumn)
  PostgresMigration->>AddColumnCall: toOp(controlAdapter)
  AddColumnCall->>ExecuteRequestLowerer: lower alterTable(addColumnAction)
  ExecuteRequestLowerer->>ControlAdapter: render ALTER TABLE SQL
  ControlAdapter-->>PostgresMigration: SqlMigrationPlanOperation
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • prisma/prisma-next#354: Migration authoring surface changes and migration fixture updates to class-based migration model and this.addColumn usage.
  • prisma/prisma-next#672: Introduces the initial col() helper and updates migration fixtures to use the new column builder pattern.

Suggested reviewers

  • wmadden

Poem

🐰 I hopped through columns, tidy and small,
Swapped bulky objects for a neat col() call.
This.addColumn hums, ALTER TABLE sings,
Defaults lead on tiptoe before NOT NULL rings.
Cheers — migrations hop forward with spring in their paws!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: introducing a typed DDL AST approach for Postgres ALTER TABLE ADD COLUMN operations, moving from raw SQL to structured column definitions.
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 docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch pg-add-column-pioneer

@pkg-pr-new

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

Copy link
Copy Markdown

Open in StackBlitz

@prisma-next/extension-author-tools

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

@prisma-next/mongo-runtime

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

@prisma-next/family-mongo

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

@prisma-next/sql-runtime

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

@prisma-next/family-sql

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

@prisma-next/extension-arktype-json

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

@prisma-next/middleware-cache

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

@prisma-next/mongo

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

@prisma-next/extension-paradedb

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

@prisma-next/extension-pgvector

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

@prisma-next/extension-postgis

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

@prisma-next/postgres

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

@prisma-next/sql-orm-client

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

@prisma-next/sqlite

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

@prisma-next/extension-supabase

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

@prisma-next/target-mongo

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

@prisma-next/adapter-mongo

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

@prisma-next/driver-mongo

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

@prisma-next/contract

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

@prisma-next/utils

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

@prisma-next/config

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

@prisma-next/errors

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

@prisma-next/framework-components

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

@prisma-next/operations

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

@prisma-next/ts-render

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

@prisma-next/contract-authoring

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

@prisma-next/ids

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

@prisma-next/psl-parser

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

@prisma-next/psl-printer

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

@prisma-next/cli

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

@prisma-next/cli-telemetry

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

@prisma-next/emitter

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

@prisma-next/migration-tools

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

prisma-next

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

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

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

@prisma-next/mongo-codec

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

@prisma-next/mongo-contract

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

@prisma-next/mongo-value

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

@prisma-next/mongo-contract-psl

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

@prisma-next/mongo-contract-ts

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

@prisma-next/mongo-emitter

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

@prisma-next/mongo-schema-ir

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

@prisma-next/mongo-query-ast

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

@prisma-next/mongo-orm

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

@prisma-next/mongo-query-builder

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

@prisma-next/mongo-lowering

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

@prisma-next/mongo-wire

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

@prisma-next/sql-contract

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

@prisma-next/sql-errors

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

@prisma-next/sql-operations

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

@prisma-next/sql-schema-ir

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

@prisma-next/sql-contract-psl

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

@prisma-next/sql-contract-ts

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

@prisma-next/sql-contract-emitter

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

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

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

@prisma-next/sql-relational-core

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

@prisma-next/sql-builder

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

@prisma-next/target-postgres

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

@prisma-next/target-sqlite

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

@prisma-next/adapter-postgres

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

@prisma-next/adapter-sqlite

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

@prisma-next/driver-postgres

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

@prisma-next/driver-sqlite

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

commit: c856a49

@github-actions

github-actions Bot commented Jun 11, 2026 •

Copy link
Copy Markdown

size-limit report 📦

Path Size
postgres / no-emit 154.46 KB (+0.08% 🔺)
postgres / emit 121.67 KB (+0.09% 🔺)
mongo / no-emit 76.83 KB (0%)
mongo / emit 70.95 KB (0%)
cf-worker / no-emit 183.49 KB (+0.07% 🔺)
cf-worker / emit 147.45 KB (+0.1% 🔺)

@wmadden wmadden left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

A couple of small points, fix them and merge

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@packages/3-targets/3-targets/postgres/src/core/migrations/op-factory-call.ts`:
- Around line 348-355: The generated operation id for add-column currently omits
schemaName causing collisions; update the id construction where id is set (using
schemaName, tableName, columnName) to include schemaName (or call the shared
add-column identity builder if one exists) so the id becomes schema-qualified
and unique; ensure the change is made alongside the existing target/label logic
(see id, schemaName, tableName, columnName, and targetDetails in this return
object).
- Around line 377-395: The generated addColumn call currently omits the
column.codecRef; update renderTypeScript to include a codecRef entry when
this.column.codecRef is present (e.g. push `codecRef:
${jsonToTsSource(this.column.codecRef)}` or the appropriate TS emitter for codec
references) so the emitted this.addColumn({...}) round-trips codec-backed
columns; also ensure importRequirements() includes any symbols needed for the
codec by passing the codec reference into defaultImportSymbols (e.g.
defaultImportSymbols([this.column, this.column.codecRef]) or otherwise add the
codec symbol from this.column.codecRef) so required imports are emitted.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: 2d2abca9-e564-4873-b5b3-969d55b44a19

📥 Commits

Reviewing files that changed from the base of the PR and between 622a001 and 8196fd8.

⛔ Files ignored due to path filters (3)
  • projects/migrate-marker-ledger-to-typed-query-ast-commands/slices/pg-add-column-pioneer/dispatches/01-alter-table-node-shape.md is excluded by !projects/**
  • projects/migrate-marker-ledger-to-typed-query-ast-commands/slices/pg-add-column-pioneer/plan.md is excluded by !projects/**
  • projects/migrate-marker-ledger-to-typed-query-ast-commands/slices/pg-add-column-pioneer/spec.md is excluded by !projects/**
📒 Files selected for processing (67)
  • examples/prisma-next-demo/fixtures/converging-branches/migrations/app/20260302T1000_add_phone/migration.ts
  • examples/prisma-next-demo/fixtures/converging-branches/migrations/app/20260302T1100_add_posts/migration.ts
  • examples/prisma-next-demo/fixtures/converging-branches/migrations/app/20260302T1200_add_avatar/migration.ts
  • examples/prisma-next-demo/fixtures/converging-branches/migrations/app/20260303T1000_merge_phone/migration.ts
  • examples/prisma-next-demo/fixtures/converging-branches/migrations/app/20260303T1100_merge_posts/migration.ts
  • examples/prisma-next-demo/fixtures/converging-branches/migrations/app/20260303T1200_merge_avatar/migration.ts
  • examples/prisma-next-demo/fixtures/diamond/migrations/app/20260302T1000_alice_add_phone/migration.ts
  • examples/prisma-next-demo/fixtures/diamond/migrations/app/20260302T1100_bob_add_avatar/migration.ts
  • examples/prisma-next-demo/fixtures/diamond/migrations/app/20260303T1000_merge_alice/migration.ts
  • examples/prisma-next-demo/fixtures/diamond/migrations/app/20260303T1100_merge_bob/migration.ts
  • examples/prisma-next-demo/fixtures/long-spine/migrations/app/20260302T1000_add_phone/migration.ts
  • examples/prisma-next-demo/fixtures/long-spine/migrations/app/20260303T1000_add_bio/migration.ts
  • examples/prisma-next-demo/fixtures/long-spine/migrations/app/20260304T1000_add_posts/migration.ts
  • examples/prisma-next-demo/fixtures/long-spine/migrations/app/20260305T1000_add_avatar/migration.ts
  • examples/prisma-next-demo/fixtures/long-spine/migrations/app/20260306T1000_add_comments/migration.ts
  • examples/prisma-next-demo/fixtures/long-spine/migrations/app/20260307T1000_add_tags/migration.ts
  • examples/prisma-next-demo/fixtures/long-spine/migrations/app/20260307T1100_late_branch/migration.ts
  • examples/prisma-next-demo/fixtures/long-spine/migrations/app/20260308T1000_add_everything/migration.ts
  • examples/prisma-next-demo/fixtures/multi-branch/migrations/app/20260302T1000_add_phone/migration.ts
  • examples/prisma-next-demo/fixtures/multi-branch/migrations/app/20260302T1100_add_posts/migration.ts
  • examples/prisma-next-demo/fixtures/multi-branch/migrations/app/20260302T1200_add_avatar/migration.ts
  • examples/prisma-next-demo/fixtures/multi-branch/migrations/app/20260303T1000_add_bio/migration.ts
  • examples/prisma-next-demo/fixtures/multi-branch/migrations/app/20260304T1000_parallel_a/migration.ts
  • examples/prisma-next-demo/fixtures/multi-branch/migrations/app/20260304T1000_parallel_b/migration.ts
  • examples/prisma-next-demo/fixtures/multi-branch/migrations/app/20260304T1000_parallel_c/migration.ts
  • examples/prisma-next-demo/fixtures/multi-branch/migrations/app/20260304T1000_parallel_d/migration.ts
  • examples/prisma-next-demo/fixtures/showcase/migrations/app/20260601T0725_add_name/migration.ts
  • examples/prisma-next-demo/fixtures/showcase/migrations/app/20260601T0725_alice_phone/migration.ts
  • examples/prisma-next-demo/fixtures/showcase/migrations/app/20260601T0725_bob_avatar/migration.ts
  • examples/prisma-next-demo/fixtures/showcase/migrations/app/20260601T0726_add_bio/migration.ts
  • examples/prisma-next-demo/fixtures/showcase/migrations/app/20260601T0726_add_locale/migration.ts
  • examples/prisma-next-demo/fixtures/showcase/migrations/app/20260601T0726_fast_forward/migration.ts
  • examples/prisma-next-demo/fixtures/showcase/migrations/app/20260601T0726_merge_alice/migration.ts
  • examples/prisma-next-demo/fixtures/showcase/migrations/app/20260601T0726_merge_bob/migration.ts
  • examples/prisma-next-demo/fixtures/showcase/migrations/app/20260601T0727_hotfix/migration.ts
  • examples/prisma-next-demo/fixtures/showcase/migrations/app/20260601T0728_promote_bob/migration.ts
  • examples/prisma-next-demo/fixtures/showcase/migrations/app/20260601T0730_experiment/migration.ts
  • examples/prisma-next-demo/fixtures/skip-rollback/migrations/app/20260302T1000_add_phone/migration.ts
  • examples/prisma-next-demo/fixtures/skip-rollback/migrations/app/20260303T1000_add_bio/migration.ts
  • examples/prisma-next-demo/fixtures/skip-rollback/migrations/app/20260304T1000_add_posts/migration.ts
  • examples/prisma-next-demo/fixtures/wide-fan/migrations/app/20260302T1000_add_phone/migration.ts
  • examples/prisma-next-demo/fixtures/wide-fan/migrations/app/20260302T1100_add_posts/migration.ts
  • examples/prisma-next-demo/fixtures/wide-fan/migrations/app/20260302T1200_add_avatar/migration.ts
  • examples/prisma-next-demo/fixtures/wide-fan/migrations/app/20260302T1300_add_category/migration.ts
  • examples/prisma-next-demo/fixtures/wide-fan/migrations/app/20260302T1400_add_settings/migration.ts
  • examples/prisma-next-demo/migrations/app/20260422T0720_initial/migration.json
  • examples/prisma-next-demo/migrations/app/20260422T0720_initial/ops.json
  • examples/prisma-next-demo/migrations/app/20260422T0742_migration/migration.ts
  • examples/prisma-next-demo/migrations/app/20260605T1145_mti_variant_link_columns/migration.ts
  • examples/prisma-next-demo/migrations/app/20260610T0000_add_priority_enum/migration.ts
  • packages/3-targets/3-targets/postgres/src/contract-free/ddl.ts
  • packages/3-targets/3-targets/postgres/src/core/ddl/nodes.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/issue-planner.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/op-factory-call.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/planner-strategies.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/postgres-migration.ts
  • packages/3-targets/3-targets/postgres/src/exports/contract-free.ts
  • packages/3-targets/3-targets/postgres/src/exports/ddl.ts
  • packages/3-targets/3-targets/postgres/src/exports/migration.ts
  • packages/3-targets/6-adapters/postgres/src/core/control-adapter.ts
  • packages/3-targets/6-adapters/postgres/test/ddl-add-column-lowering.test.ts
  • packages/3-targets/6-adapters/postgres/test/ddl-create-table-lowering.test.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/marker-table-ddl.test.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/op-factory-call.construction.test.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/op-factory-call.lowering.test.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/op-factory-call.rendering.test.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/render-typescript.roundtrip.test.ts
💤 Files with no reviewable changes (1)
  • packages/3-targets/3-targets/postgres/src/exports/migration.ts

… its own line (review)

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Signed-off-by: willbot <[email protected]>
wmadden-electric and others added 3 commits June 11, 2026 18:09
- `test/e2e/framework/test/ddl.test.ts`: regenerate inline snapshot to
  reflect the new `DEFAULT … NOT NULL` column-attribute order introduced
  by the AlterTable DDL IR alignment (operator-approved).
- `skills/upgrade/prisma-next-upgrade/upgrades/0.13-to-0.14/instructions.md`:
  add incidental HTML comment for PR #813 (`this.addColumn()` migration API
  + column-order change) so `check:upgrade-coverage --mode pr` passes.

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

- `migration-round-trip.e2e.test.ts`: the hand-authored migration.ts
  string imported the now-removed free `addColumn()` from
  `@prisma-next/postgres/migration`. Convert to the `this.addColumn({
  schema, table, column: col(...) })` method form (nullable text column,
  no default — faithful to the old `{ nullable: true, defaultSql: null }`).
- `postgres-control-policy-planner.test.ts`: `AddColumnCall.toOp` is now
  async, so `plan.operations` may hold a `Promise<Op>`. Make `planAddColumn`
  await `Promise.all(plan.operations)` before the deep-equal assertion,
  mirroring the existing `planAgainst` helper. No production change.

Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Signed-off-by: willbot <[email protected]>
@wmadden-electric
wmadden-electric added this pull request to the merge queue Jun 11, 2026
Merged via the queue into main with commit f6240ca Jun 11, 2026
28 of 29 checks passed
@wmadden-electric
wmadden-electric deleted the pg-add-column-pioneer branch June 11, 2026 17:05
paulwer pushed a commit to paulwer/prisma-next that referenced this pull request Jun 15, 2026
…tired (prisma#816)

## Linked issue

Refs [TML-2888](https://linear.app/prisma-company/issue/TML-2888) —
Slice 6 of [Marker/ledger via typed query
AST](https://linear.app/prisma-company/project/markerledger-via-typed-query-ast-dc62ab25d151).
Closes Phase 1 of that project: SQLite (prisma#768) and Postgres ALTER TABLE
(prisma#813) landed earlier; this PR is the Mongo pioneer.

## At a glance

The migration runner's DDL dispatch — before, a separate executor
reached past the adapter to driver helper calls; after, DDL takes the
same path the runner's data-transform arm already uses
([mongo-runner.ts](packages/3-mongo-target/1-mongo-target/src/core/mongo-runner.ts)):

```ts
// before — step.command.accept(commandExecutor) → db.createCollection(...) / db.collection(...).createIndex(...)
// after  — one path to the wire, same as DML:
for (const step of ddlOp.execute) {
  const wire = await adapter.lower({ command: step.command }, {});
  for await (const _ of driver.execute(wire)) {
    /* consume */
  }
}
```

And the planner's op factories stop hand-authoring AST nodes — the
contract-free builder constructs them
([migration-factories.ts](packages/3-mongo-target/1-mongo-target/src/core/migration-factories.ts)):

```ts
// before — command: new CreateIndexCommand(collection, keys, { ...options, name }),
//          filter: MongoFieldFilter.eq('key', keysToKeySpec(keys))
const f = createFieldAccessor<IndexInfoDocShape>();
const fullFilter = options?.unique ? filter.and(f.unique.eq(true)) : filter;
execute: [{ command: collection(collectionName).createIndex(keys, { ...options, name }) }],
```

The emitted commands and database effects are identical to before — this
PR changes *how they're constructed and executed*, not what they do.

## Reviewer notes

- **An internal review already ran on this branch** (architect +
principal-engineer pass): verdict SHIP, no blocker/major findings; its
two minor findings (oracle exactness, lazy DDL arms) are fixed in the
final commit. The artifact is committed at
`projects/migrate-marker-ledger-to-typed-query-ast-commands/slices/mongo-planner-create-collection-and-index-adoption/reviews/code-review.md`.
- **DDL lowers to typed wire-command union members**
(`CreateCollectionWireCommand` et al.), which the driver executes via
node-driver helpers — the same idiom the existing DML wire commands use.
It does not lower to raw `{create: …}` server documents; the wire union
is ours, the driver owns transport.
- **The driver's DDL arms are lazily-started** `AsyncIterable`s via a
hand-rolled thunk (`lazyDdlIterable`) rather than `async function*` — a
yield-less generator trips Biome's `useYield`, and we don't suppress
lints. Two tests pin the laziness contract (no DB action until iterated;
iterating twice doesn't re-execute).
- **The codec-dedup commit (`refactor(codecs): …`) is deliberately
unrelated to the Mongo work** — it's a small cleanup deferred from prisma#813,
carried here as its own commit. Reviewable in isolation.
- **Drop/CollMod/DropIndex factories intentionally keep hand-written
filters** and the old construction style — their construction migration
is Phase 2; only their *execution* unifies in this PR. Likewise
`validatedCollection()` keeps the `createCollection()`/`createIndex()`
factories alive (they now construct via the builder internally).
- **Largest commit** is the first (`feat(mongo): lower migration DDL
through the adapter…`): the five lowering arms + wire types + oracle.
The option-field mapping there is a verbatim port of the deleted
executor's mapping — the oracle and the rewritten behavioral suite pin
it field-by-field.

## Decision

This PR ships four things:

1. **`MongoAdapter.lower()` accepts migration DDL.** The five DDL
command kinds (`createCollection`, `createIndex`, `dropCollection`,
`dropIndex`, `collMod`) lower to typed wire commands, mirroring the SQL
family's `Lowerer.lower(ast: AnyQueryAst | DdlNode, ctx)` — one lowering
entry for queries and DDL alike.
2. **The runner's DDL dispatch unifies and `MongoCommandExecutor` is
deleted.** Every DDL step executes via `adapter.lower → driver.execute`,
the path marker DML and data-transforms already use.
`MongoInspectionExecutor` (prechecks/postchecks) survives unchanged in
its own module.
3. **The contract-free builder gains DDL terminals.**
`collection(name).createCollection(options)` / `.createIndex(keys,
options)` produce the canonical frozen command nodes; the
`CreateCollection`/`CreateIndex` op factories construct through them,
and their check filters through the contract-free field accessor
(including a new `.and()` combinator on filter expressions, added beside
the existing `.not()`).
4. **A codec-resolution dedup deferred from prisma#813**: the duplicated "find
descriptor → throw `CODEC_DESCRIPTOR_MISSING` → materialize" logic in
the framework's `extractCodecLookup` and the SQL runtime's
`createAstCodecResolver` collapses onto one shared
`resolveCodecDescriptorOrThrow` helper.

Design rationale is recorded in the project design notes
(`projects/migrate-marker-ledger-to-typed-query-ast-commands/design-notes.md`,
§ "Slice 6").

## How it fits together

1. **Wire types**
([wire-commands.ts](packages/2-mongo-family/6-transport/mongo-wire/src/wire-commands.ts)):
the `AnyMongoWireCommand` union grows five typed DDL members, carrying
exactly the option fields the planner sets.
2. **Lowering**
([mongo-adapter.ts](packages/3-mongo-target/2-mongo-adapter/src/mongo-adapter.ts)):
`structuralLower` gains one arm per DDL kind; the option mapping is the
retired executor's mapping, moved. DDL lowering is structural — no codec
routing.
3. **Transport**
([mongo-driver.ts](packages/3-mongo-target/3-mongo-driver/src/mongo-driver.ts)):
the driver executes DDL wire commands via the node driver's helpers
(`db.createCollection`, `collection.createIndex`, …), lazily on first
iteration.
4. **Runner**
([mongo-runner.ts](packages/3-mongo-target/1-mongo-target/src/core/mongo-runner.ts)):
the DDL loop converges onto lower→execute; the executor, its
`runner-deps` slot, and its exports are deleted.
5. **Construction**
([collection.ts](packages/2-mongo-family/5-query-builders/query-builder/src/contract-free/collection.ts),
[migration-factories.ts](packages/3-mongo-target/1-mongo-target/src/core/migration-factories.ts)):
the builder terminals return the real frozen nodes (no parallel option
shapes, no second AST layer), and the pioneer pair's factories construct
through them.

A deliberate asymmetry with the Postgres adoption (prisma#813): lowering
happens **execute-time at the runner boundary**, not plan-time inside
`toOp(lowerer)`. Postgres serializes the lowered `sql` into `ops.json`;
Mongo serializes the **typed command node itself**, so plan-time
lowering would degrade the serialized artifact to opaque wire documents.
`toOp()` stays sync; `ops.json` is byte-identical to before.

## Behavior changes & evidence

- **No user-observable behavior change.** Wire-level parity is pinned by
an exact-match lowering oracle covering every option field per kind
([ddl-lowering-oracle.test.ts](packages/3-mongo-target/2-mongo-adapter/test/ddl-lowering-oracle.test.ts)),
and the behavioral suite re-asserts real database outcomes for all five
kinds through the new path against mongodb-memory-server, including
server-error fidelity negatives
([command-executor.test.ts](packages/3-mongo-target/2-mongo-adapter/test/command-executor.test.ts)).
- **`driver.execute()` on a DDL wire command is now lazy** — no database
action until the iterable is consumed, consistent with the DML arms
([mongo-driver.ts](packages/3-mongo-target/3-mongo-driver/src/mongo-driver.ts);
evidence: the laziness tests in [mongo-driver
test](packages/3-mongo-target/3-mongo-driver/test)).
- **`renderTypeScript()` output, op ids, and `ops.json` serialization
are unchanged** — the serializer is untouched; existing round-trip and
op-factory suites pass unmodified
([mongo-ops-serializer.ts](packages/3-mongo-target/1-mongo-target/src/core/mongo-ops-serializer.ts)).
- **Filter expressions gain `.and(other)`** beside `.not()`
([filter-expressions.ts](packages/2-mongo-family/4-query/query-ast/src/filter-expressions.ts);
evidence: builder/factory tests exercising the unique-postcheck fold).
- **Codec descriptor resolution is single-sourced**
([resolve-codec.ts](packages/1-framework/1-core/framework-components/src/shared/resolve-codec.ts),
call sites
[control-stack.ts](packages/1-framework/1-core/framework-components/src/control/control-stack.ts)
and
[ast-codec-resolver.ts](packages/2-sql/5-runtime/src/codecs/ast-codec-resolver.ts);
evidence:
[control-stack.test.ts](packages/1-framework/1-core/framework-components/test/control-stack.test.ts)
`forCodecRef` cases + the existing resolver suite).

## Summary

The Mongo migration planner's DDL now reaches the database the same way
every other operation does — built through the contract-free builder,
lowered by the adapter, executed by the driver — completing "the planner
adopts the typed AST across all three targets" (Phase 1 of the
marker/ledger typed-query-AST project).

## Testing performed

- `pnpm build` (66 tasks), `pnpm typecheck` (138 tasks)
- `pnpm test:packages` (815 files / 10k+ tests; one CLI parallel-load
flake reproduced and ruled pre-existing — clean on rerun)
- `pnpm test:integration` (188 files, 1082 tests)
- `pnpm lint:code`, `pnpm lint:packages`, `pnpm lint:deps`, `pnpm
lint:casts` (delta 0), `pnpm fixtures:check`
- Targeted: adapter-mongo (317), target-mongo (403), mongo-query-builder
(422), framework-components (403), driver-mongo (22)

## Skill update

n/a — internal only. No CLI, public API, config, or error-code surface
changes; migration authoring (`migration.ts`) is untouched.

## Follow-ups

- Phase 2 (tracked in the project plan): migrate Drop/CollMod
construction + `validatedCollection()` onto the builder; the
`typed-migration-verification-queries` slice moves prechecks/postchecks
off `MongoInspectionExecutor`.
- The two codec descriptor *indexes* (framework `descriptorsById` vs SQL
`CodecDescriptorRegistry`) remain separate across the plane split —
deliberate; recorded in the D3 dispatch artifact.

## Alternatives considered

- **Declare Mongo already adopted** (its planner already built typed
frozen-class nodes dispatched by a visitor). Rejected: typed nodes were
never the whole ask — DDL still bypassed the adapter's lowering seam,
and the ops were hand-authored rather than builder-constructed.
- **Keep helper-based execution behind an adapter method**
(`adapter.execDdl(node)`). Rejected: preserves a second execution
mechanism and diverges from the SQL family's one-lowering-entry
interface.
- **Thread a thin `MongoMigrationLowerer` wrapper into
`toOp(lowerer)`.** Rejected: plumbing without unification — two dispatch
paths would survive in the runner.
- **Plan-time lowering inside `toOp(lowerer)`** (the literal Postgres
mirror). Rejected: Mongo serializes the typed node into `ops.json`;
lowering at plan time would serialize opaque wire documents instead —
the wrong artifact.

## Checklist

- [x] All commits are signed off (`git commit -s`) per the
[DCO](../CONTRIBUTING.md#developer-certificate-of-origin-dco). The DCO
status check will block merge if any commit is missing a
`Signed-off-by:` trailer.
- [x] I read [CONTRIBUTING.md](../CONTRIBUTING.md) and the change is
scoped to one logical concern (plus one explicitly-flagged carried
cleanup commit).
- [x] Tests are updated.
- [x] The PR title is in `TML-NNNN: <sentence-case title>` form (Linear
ticket prefix + concise title naming the concrete deliverable). See
`.claude/skills/create-pr/SKILL.md` for the full convention.
- [x] The **Skill update** section above is filled in.


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

* **New Features**
* Full Mongo DDL support: create/drop collections & indexes, collMod and
schema ops flow adapter→driver; query builder gains
collection().createCollection()/createIndex(); control surface exposes
executeDdl.
  * Utility: added helper to remove undefined properties from objects.

* **Bug Fixes / Improvements**
* Centralized codec descriptor resolution with consistent error
handling.
* Migration tooling updated to use query-builder APIs; DDL command
shapes now surface options under a single options object.

* **Tests**
* Extensive new and updated tests covering DDL lowering, driver
execution, adapter/runner and command shapes.
<!-- 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 Fable 5 <[email protected]>
paulwer pushed a commit to paulwer/prisma-next that referenced this pull request Jun 21, 2026
prisma#837)

## Linked issue

Refs [TML-2918](https://linear.app/prisma-company/issue/TML-2918) —
Phase-2 follow-up of [Marker/ledger via typed query
AST](https://linear.app/prisma-company/project/markerledger-via-typed-query-ast-dc62ab25d151).
Two correctness gaps deferred from Slice 7
([prisma#813](prisma#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`](packages/3-targets/3-targets/postgres/src/core/migrations/op-factory-call.ts):

```ts
// 1. AddColumn op id includes schema — was `column.${tableName}.${columnName}`
id: `column.${schemaName}.${tableName}.${columnName}`,
```

```ts
// 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](projects/migrate-marker-ledger-to-typed-query-ast-commands/slices/pg-addcolumn-opid-and-codecref-roundtrip/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](packages/3-targets/3-targets/postgres/src/core/migrations/op-factory-call.ts)
(`AddColumnCall.toOp`). Evidence: cross-schema-uniqueness test in
[op-factory-call.construction.test.ts](packages/3-targets/3-targets/postgres/test/migrations/op-factory-call.construction.test.ts);
existing op-id literal assertions in
[op-factory-call.lowering.test.ts](packages/3-targets/3-targets/postgres/test/migrations/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](packages/3-targets/3-targets/postgres/src/core/migrations/op-factory-call.ts)
(`renderDdlColumnAsTsCall`). Evidence: three new round-trip tests in
[op-factory-call.rendering.test.ts](packages/3-targets/3-targets/postgres/test/migrations/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

- [x] All commits are signed off (`git commit -s`) per the
[DCO](../CONTRIBUTING.md#developer-certificate-of-origin-dco). The DCO
status check will block merge if any commit is missing a
`Signed-off-by:` trailer.
- [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.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## 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.
<!-- 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
…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