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

TML-2889: typed migration verification checks via the contract-free builder - #825

Merged
wmadden-electric merged 35 commits into
mainfrom
tml-2889-typed-migration-verification-queries
Jun 15, 2026
Merged

wmadden-electric merged 35 commits into
mainfrom
tml-2889-typed-migration-verification-queries

Conversation

@wmadden-electric

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

Copy link
Copy Markdown
Contributor

Linked issue

Refs TML-2889. The carved-out typed-migration-verification-queries slice of the Marker/ledger via typed query AST 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:

// 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

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 TML-2754: Postgres migration planner builds CREATE TABLE / CREATE SCHEMA as typed DDL through the adapter #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

  • All commits are signed off (git commit -s) per the DCO.
  • I read CONTRIBUTING.md and the change is scoped to one logical concern.
  • Tests are updated.
  • The PR title is in TML-NNNN: <sentence-case title> form.
  • The Skill update section above is filled in.

Summary by CodeRabbit

  • 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.

wmadden-electric and others added 21 commits June 11, 2026 20:33
Carved-out slice picked up as one PR (operator decision). Grounding
corrections recorded in the project plan: SQL-only (Mongo checks already
typed), wider builder substrate than the original carve-out sketch, two
deferred residuals (buildRecreatePostchecks, data-transform wrapper).

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Add FunctionSource (table-valued function FROM source), make
SelectAst.from optional for FROM-less SELECTs, and extend the
contract-free builder with expression projection (CfExprSelectQuery,
cfExpr helpers, exprSelect factory).

Sweep all exhaustive AnyFromSource consumers: both adapter renderers
gain a function-source arm and tolerate a missing FROM clause; lint,
budget, and ORM where-binding middleware guard the optional from.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
tableExistsAst (PG, to_regclass with bound qualified name) and
columnExistsAst (SQLite, pragma_table_info with bound table/column
names) produce parameterized SelectAsts instead of hand-glued SQL.
AST-shape tests live in the target packages; rendered-SQL lowering
tests live in the adapter packages to respect layering.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
PG CreateTableCall.toOp and SQLite AddColumnCall/DropColumnCall toOps
lower tableExistsAst/columnExistsAst through the control adapter and
bind names as parameters; step() gains an optional params slot on both
targets. The SQLite column toOps go async + lowerer-required, mirroring
CreateTableCall.

The sync, lowerer-less authored-migration factories (PG dropTable,
SQLite addColumn/dropColumn) stay on clearly-marked legacy raw-string
copies; their conversion is deferred to D3.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
SelectAst.from is now optional (FROM-less verification SELECTs); the
beforeCompile middleware in these tests narrows it with ?. before
reading .name.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Regenerated example migrations (fixtures:check) now carry parameterized
to_regclass pre/postchecks from the converted planner path. The SQLite
render-typescript roundtrip test compares the addColumn checks per-path
until D3 converts the authored-migration facade: the rendered scaffold
still calls the legacy raw-string factory, while renderOps lowers typed
parameterized checks.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
R1-01: tableExistsAst hand-assembled new OperationExpr({...}) with an
inline lowering template at the check-builder site. The assembly now
lives in a generic cfExpr.fn helper in relational-core (function
strategy, template + codec-bound operands), and the Postgres target
exposes a thin toRegclass(qualifiedName) vocabulary wrapper that
tableExistsAst calls. Rendered SQL unchanged; D2-D4 catalog functions
(format_type, LOWER, ...) reuse the same helper.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
CfExprSelectQuery gains .join(source, on) (inner joins only — all
catalog EXISTS bodies need); cfTable(name, alias) supplies aliased
catalog table sources. cfExpr gains exists/notExists (accepting the
buildable CfExprSelectQuery and building internally — OQ4), columnRef
for alias-qualified refs, allOf for flat AND chains, and raw for
zero-operand catalog expressions (current_schema()). CfExpr.eqExpr
compares two expressions for join ON clauses.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Builds SELECT [NOT ]EXISTS (SELECT 1 FROM pg_constraint c JOIN
pg_namespace n ON n.oid = c.connamespace WHERE ...) via the contract-free
join + EXISTS surface, binding constraint name, schema name, and
to_regclass table coordinate as text parameters. PostgresSchema gains a
polymorphic schemaFilterExpression(): named schemas bind nspname as a
parameter; the unbound singleton compares against current_schema() —
the unbound branch stays in the override, not the call site.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
All five constraint-op families (addPrimaryKey, addUnique,
addForeignKey, addCheckConstraint, dropConstraint/dropCheckConstraint)
lower constraintExistsAst through the control adapter; the raw-string
constraintExistsCheck is deleted, not wrapped. The factories and their
*Call.toOp()s go async + lowerer-required with loud errors, following
the CreateTableCall pattern.

The authored-migration surface moves to PostgresMigration instance
methods (this.addPrimaryKey({...}) etc., mirroring this.createTable);
renderTypeScript emits the method form with no facade import, the bare
factory exports are removed from @prisma-next/postgres/migration, and
the committed example migrations are updated and regenerated.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
D2-R1-01: two D3 catalog-check shapes were not mechanically
expressible — tableHasPrimaryKeyCheck needs a LEFT JOIN and
tableIsEmptyCheck needs LIMIT 1. leftJoin(source, on) rides
JoinAst.left, limit(n) rides SelectAst.withLimit; construction pins in
relational-core and one lowering pin per method in adapter-postgres.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Ten new vocabulary builders in target-postgres contract-free checks:
columnExistsAst, columnNullabilityAst, columnTypeAst (format_type via
cfExpr.fn), columnDefaultAst (present/absent/noDefault),
tablePrimaryKeyAst (LEFT JOIN constraint scope), tableIsEmptyAst
(LIMIT 1), noNullValuesAst, enumTypeExistsAst, extensionExistsAst, and
indexExistsAst (to_regclass vocabulary). PostgresSchema gains the
polymorphic tableSource() counterpart of qualifyTable so user-table FROM
sources stay unbranched on the namespace sentinel. Construction pins in
target-postgres, exact-SQL lowering pins in adapter-postgres.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…uilder

Convert the remaining Postgres migration precheck/postcheck verification
SELECTs from hand-built raw SQL to typed query-AST nodes lowered through the
control adapter. Covers the planner-sql-checks helpers (column existence,
nullability, type via format_type, default presence, primary-key, table-empty),
the enum and extension inline checks, and the planner-strategies consumer
(including the not-null temporary-default recipe postcheck). The temp-default
execute-step SQL stays slice-7-deferred. Regenerates example/extension
migration fixtures to the parameterized check form.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Replace `instanceof PostgresTableSource` with a structural `hasExplicitSchema`
predicate in `qualifyTableFromNamespaceCoordinate`. When the render-typescript
round-trip test runs the rendered scaffold as a tsx subprocess, the source-file
PostgresTableSource (imported via file:// URL) and the compiled dist copy
(imported via the @prisma-next/target-postgres/contract-free package specifier)
are distinct class objects, so instanceof fails and the information_schema
schema qualifier is silently dropped. The duck-type check on the `schema`
string property is stable across module identity boundaries.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Converts all SQLite migration pre/postcheck verification SELECTs from
hand-built raw SQL strings to typed query-AST nodes built via the
contract-free builder and lowered through the SqliteControlAdapter.

- `checks.ts`: adds `tableExistsAst` (sqlite_master TableSource) and
  `indexExistsAst` for typed table/index existence verification
- `operations/tables.ts`, `indexes.ts`, `columns.ts`: ops become
  async+lowerer-required, removing all raw SELECT check strings
- `op-factory-call.ts`: `*Call.toOp()` async, `renderTypeScript()`
  emits `this.methodName({...})` calls on SqliteMigration
- `sqlite-migration.ts`: protected methods for every op
- `descriptor-meta.ts` (adapter): adds `codecDescriptors` from
  `sqliteCodecRegistry` so typed check params resolve correctly when
  lowered through the stack
- Fixture: `prisma-next-demo-sqlite` contract.d.ts updated — `sql/char@1`
  now renders as `Char<36>` (proper typed output from registered codec)
- Example migration ops.json fixtures regenerated

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
columnExistsCheck, columnNullabilityCheck, tableIsEmptyCheck,
columnHasNoDefaultCheck, tableHasPrimaryKeyCheck, and toRegclassLiteral
were converted to typed AST builders in 6da8760 and have no remaining
call sites. Delete them along with their re-exports and update JSDoc
prose that referenced the deleted toRegclassLiteral symbol.

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

The codecDescriptors line added in D4 caused the SQLite emitter to resolve
sql/char@1 fields as Char<36> (a Postgres-only type) instead of the correct
CodecTypes['sql/char@1']['output'] indexed-access form. Lowering tests pass
without it — the codec is available to the runtime resolver independently.

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

The prior revert (5d0df9d) removed `codecDescriptors` from
`sqliteAdapterDescriptorMeta`. `extractCodecLookup` builds `stack.codecLookup`
from that descriptor, so without it the lookup has no SQLite codec entries.

`SqliteControlAdapter.lowerToExecuteRequest` passes `this.codecRegistry`
(the stack codec lookup) to `encodeControlQueryParams`, overriding the
`CONTROL_CODECS` default. When verification checks bind `sqlite/text@1`
params, `forCodecRef('sqlite/text@1')` throws
`RUNTIME.CODEC_DESCRIPTOR_MISSING` because the codec isn't registered.

The previous attempt to restore all descriptors via
`Array.from(sqliteCodecRegistry.values())` broke emit: `sqliteCodecRegistry`
includes `sqlCharDescriptor` (a shared SQL base codec whose `renderOutputType`
emits `Char<N>`), but the SQLite adapter descriptor lists no `typeImports` for
`Char`, so `Char<36>` in the emitted contract.d.ts is unresolvable.

This fix restores `codecDescriptors` with only the SQLite-native codecs
(those with `codecId.startsWith('sqlite/')`). None of the SQLite-native
descriptors define `renderOutputType`, so they contribute no named type
renderers to the emit lookup. Shared SQL base codecs with `renderOutputType`
remain absent from the adapter descriptor, so emit falls back to the
indexed-access form (`CodecTypes['sql/char@1']['output']`) which is correct.

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

Replace startsWith('sqlite/') with renderOutputType === undefined: the intent is
to exclude codecs that emit named TypeScript types (Char<N>, Varchar<N>), not to
exclude by id prefix. The new predicate keeps sql/int@1 and sql/float@1 (identity
encoders with no renderOutputType) and correctly drops sql/char@1, sql/varchar@1,
and any future codec that carries renderOutputType.

Add a test in verification-checks-lowering.test.ts that builds the control adapter
from extractCodecLookup([sqliteAdapterDescriptorMeta]) — the production path — and
asserts that columnExistsAst lowers without CODEC_DESCRIPTOR_MISSING and that a
SqliteCreateTable with a sql/char@1 column falls through to raw-literal encoding
without throwing.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Adds a migration-op-factories-to-methods entry to both the user-skill and
extension-author-skill 0.13-to-0.14 instructions. Covers the removal of
bare factory functions from @prisma-next/postgres/migration and
@prisma-next/target-postgres/migration. Includes a colocated codemod that
handles multi-line imports and all eight removed factories (dropColumn,
setNotNull, setDefault, addPrimaryKey, addForeignKey, addCheckConstraint,
createIndex, installExtension), copied independently into both skill
directories.

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

coderabbitai Bot commented Jun 15, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

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

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This PR adds function-source and FROM-less SQL AST support, adds Postgres and SQLite contract-free verification builders, refactors migration operations and op-factory calls to use lowerers, and updates example migrations, exports, tests, docs, and codemods for the new migration method style.

Changes

SQL AST and migration lowering

Layer / File(s) Summary
AST and contract-free select support
packages/2-sql/4-lanes/relational-core/src/ast/types.ts, packages/2-sql/4-lanes/relational-core/src/contract-free/*, packages/2-sql/5-runtime/src/middleware/*, packages/3-extensions/sql-orm-client/src/where-binding.ts, packages/3-targets/6-adapters/*/src/core/*, test/integration/test/*
Adds FunctionSource, allows SelectAst without from, introduces cfExpr/cfTable/exprSelect, and updates runtime, ORM binding, renderers, and middleware guards to tolerate missing from and render function sources.
Postgres typed verification checks
packages/3-targets/3-targets/postgres/src/contract-free/checks.ts, packages/3-targets/3-targets/postgres/src/core/postgres-schema.ts, packages/3-targets/3-targets/postgres/src/exports/contract-free.ts, packages/3-targets/3-targets/postgres/test/migrations/verification-checks.test.ts, packages/3-targets/6-adapters/postgres/test/verification-checks-lowering.test.ts
Adds Postgres AST builders for table, column, constraint, default, type, PK, emptiness, enum, extension, and index checks, plus schema helpers and tests for AST structure and lowered SQL.
Postgres migration lowering and helper methods
packages/3-targets/3-targets/postgres/src/core/migrations/*, packages/3-targets/3-targets/postgres/src/exports/{migration,planner-sql-checks}.ts, packages/3-targets/3-targets/postgres/test/migrations/*, packages/3-targets/6-adapters/postgres/test/migrations/*, packages/3-extensions/pgvector/test/migrations/planner.behavior.test.ts
Converts Postgres migration operations and op-factory calls to async lowerer-backed verification, replaces raw planner SQL helpers, adds protected PostgresMigration methods, switches rendered TypeScript to this.*({...}), and updates planner and rendering tests.
SQLite checks and async migration lowering
packages/3-targets/3-targets/sqlite/src/contract-free/checks.ts, packages/3-targets/3-targets/sqlite/src/core/migrations/*, packages/3-targets/3-targets/sqlite/src/exports/*, packages/3-targets/6-adapters/sqlite/src/core/*, packages/3-targets/3-targets/sqlite/test/migrations/*, packages/3-targets/6-adapters/sqlite/test/*
Adds SQLite AST existence checks, moves table/column/index/recreate operations to async lowerer-backed verification, narrows migration exports, adjusts adapter codec descriptors, and updates lowering and op-factory tests.
Migration consumers, fixtures, and upgrade tooling
apps/telemetry-backend/migrations/..., examples/prisma-next-demo/..., examples/prisma-next-postgis-demo/..., packages/3-extensions/*/migrations/..., skills/.../0.13-to-0.14/*
Updates repository migrations and fixture migrations to use protected instance helpers like this.dropColumn, this.setNotNull, this.createIndex, and this.installExtension, refreshes ops JSON and migration hashes, and adds upgrade docs plus codemods for the factory-to-method rewrite.

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Poem

🐇 I hopped through checks of typed SQL,
where FROM may vanish, calm and cool.
The migrations learned new methods neat,
with lowered steps and params complete.
I thumped the docs, then zipped away—
carrots for a cleaner upgrade day.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch tml-2889-typed-migration-verification-queries

Resolved 4 conflicts:
- skills/upgrade/.../0.13-to-0.14/instructions.md: union changes[] entries
  (kept migration-op-factories-to-methods + main's postgres-contract-serializer)
- skills/extension-author/.../0.13-to-0.14/instructions.md: union changes[] entries
  (kept migration-op-factories-to-methods + main's namespace-entries-open-dict and postgres-contract-serializer)
- packages/3-targets/3-targets/postgres/src/core/postgres-schema.ts: merged imports
  (our CfExpr/cfExpr/PostgresTableSource/PG_TEXT_CODEC_ID + main's blindCast/ifDefined)
- examples/prisma-next-demo/migrations/app/20260422T0748_migration/migration.ts:
  kept our method-form this.setNotNull() + main's PostgresContractSerializer import
  (dropped bare setNotNull import and SqlContractSerializer)

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
@github-actions

github-actions Bot commented Jun 15, 2026 •

Copy link
Copy Markdown

size-limit report 📦

Path Size
postgres / no-emit 153.29 KB (+0.37% 🔺)
postgres / emit 121.55 KB (+0.42% 🔺)
mongo / no-emit 78 KB (0%)
mongo / emit 72.09 KB (0%)
cf-worker / no-emit 181.7 KB (+0.28% 🔺)
cf-worker / emit 146.74 KB (+0.38% 🔺)

@pkg-pr-new

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

Copy link
Copy Markdown

Open in StackBlitz

@prisma-next/extension-author-tools

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

@prisma-next/mongo-runtime

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

@prisma-next/family-mongo

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

@prisma-next/sql-runtime

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

@prisma-next/family-sql

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

@prisma-next/extension-arktype-json

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

@prisma-next/middleware-cache

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

@prisma-next/mongo

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

@prisma-next/extension-paradedb

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

@prisma-next/extension-pgvector

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

@prisma-next/extension-postgis

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

@prisma-next/postgres

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

@prisma-next/sql-orm-client

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

@prisma-next/sqlite

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

@prisma-next/extension-supabase

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

@prisma-next/target-mongo

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

@prisma-next/adapter-mongo

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

@prisma-next/driver-mongo

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

@prisma-next/contract

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

@prisma-next/utils

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

@prisma-next/config

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

@prisma-next/errors

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

@prisma-next/framework-components

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

@prisma-next/operations

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

@prisma-next/ts-render

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

@prisma-next/contract-authoring

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

@prisma-next/ids

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

@prisma-next/psl-parser

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

@prisma-next/psl-printer

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

@prisma-next/cli

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

@prisma-next/cli-telemetry

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

@prisma-next/emitter

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

@prisma-next/migration-tools

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

prisma-next

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

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

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

@prisma-next/mongo-codec

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

@prisma-next/mongo-contract

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

@prisma-next/mongo-value

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

@prisma-next/mongo-contract-psl

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

@prisma-next/mongo-contract-ts

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

@prisma-next/mongo-emitter

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

@prisma-next/mongo-schema-ir

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

@prisma-next/mongo-query-ast

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

@prisma-next/mongo-orm

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

@prisma-next/mongo-query-builder

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

@prisma-next/mongo-lowering

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

@prisma-next/mongo-wire

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

@prisma-next/sql-contract

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

@prisma-next/sql-errors

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

@prisma-next/sql-operations

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

@prisma-next/sql-schema-ir

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

@prisma-next/sql-contract-psl

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

@prisma-next/sql-contract-ts

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

@prisma-next/sql-contract-emitter

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

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

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

@prisma-next/sql-relational-core

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

@prisma-next/sql-builder

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

@prisma-next/target-postgres

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

@prisma-next/target-sqlite

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

@prisma-next/adapter-postgres

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

@prisma-next/adapter-sqlite

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

@prisma-next/driver-postgres

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

@prisma-next/driver-sqlite

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

commit: 53c6d94

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/2-sql/4-lanes/relational-core/src/contract-free/dml.ts (1)

4-17: 🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Keep the new re-exports in the exports/ surface.

These new symbols are being added to a non-exports/ re-export module. Prefer exporting them directly from src/exports/contract-free.ts instead of expanding this internal barrel. As per coding guidelines, "Don't reexport from one file in another, except in exports/ folders."

🤖 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/2-sql/4-lanes/relational-core/src/contract-free/dml.ts` around lines
4 - 17, Remove the new symbol re-exports (CfExprSelectQuery, CfFnOptions,
CfInsertQuery, CfSelectQuery, CfUpdateQuery, CfUpsertBuilder, CfUpsertQuery,
ColumnDescriptor, ColumnProxy, ColumnSchema, cfExpr, cfTable, ExcludedProxy,
exprSelect) from the dml.ts file and instead add them to the
src/exports/contract-free.ts file. According to the coding guidelines,
re-exports should only be expanded in exports/ folders, not in internal barrel
files like dml.ts.

Source: Coding guidelines

🧹 Nitpick comments (2)
packages/3-targets/3-targets/postgres/src/core/postgres-schema.ts (2)

165-171: ⚡ Quick win

Prefer ifDefined for conditional object spreads.

The inline ternary ...(alias !== undefined ? { alias } : {}) should use the ifDefined helper for consistency with the codebase's conditional-spread pattern.

♻️ Suggested refactor

Import ifDefined:

+import { ifDefined } from '`@prisma-next/utils/defined`';

Then apply:

   tableSource(tableName: string, alias?: string): PostgresTableSource {
     return new PostgresTableSource({
       name: tableName,
       schema: this.id,
-      ...(alias !== undefined ? { alias } : {}),
+      ...ifDefined('alias', alias),
     });
   }

As per coding guidelines, prefer ifDefined from prisma-next/utils/defined for 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/postgres-schema.ts` around
lines 165 - 171, The tableSource method uses an inline ternary operator for the
conditional object spread with alias, which should be replaced with the
ifDefined helper for consistency with the codebase's conditional-spread pattern.
Import ifDefined from prisma-next/utils/defined at the top of the
postgres-schema.ts file, then replace the ternary expression in the tableSource
method's return statement with the ifDefined helper to conditionally spread the
alias property.

Source: Coding guidelines


231-236: ⚡ Quick win

Prefer ifDefined for conditional object spreads (unbound schema override).

Same pattern as the base class: use ifDefined('alias', alias) instead of the inline ternary.

♻️ Suggested refactor
   override tableSource(tableName: string, alias?: string): PostgresTableSource {
     return new PostgresTableSource({
       name: tableName,
-      ...(alias !== undefined ? { alias } : {}),
+      ...ifDefined('alias', alias),
     });
   }

As per coding guidelines, prefer ifDefined from prisma-next/utils/defined for 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/postgres-schema.ts` around
lines 231 - 236, In the tableSource method of the PostgresTableSource class,
replace the inline ternary conditional spread for the alias property with a call
to ifDefined. Change the spread operator expression from the ternary pattern
(alias !== undefined ? { alias } : {}) to use ifDefined('alias', alias) instead.
Ensure that ifDefined is imported from prisma-next/utils/defined at the top of
the file if it is not already imported.

Source: Coding guidelines

🤖 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/2-sql/4-lanes/relational-core/src/ast/types.ts`:
- Around line 1540-1542: The issue is that `collectParamRefs()` and
`collectColumnRefs()` methods handle source traversal inconsistently for joined
sources, where only derived-table-source is processed but FunctionSource
arguments are ignored. This causes ParamRef arguments in joined FunctionSource
to not be included in the ordered param map, leading to lowering errors. Create
a helper method that uniformly handles traversal of both derived-table-source
and function-source types, then apply this helper consistently in both
`collectParamRefs()` and `collectColumnRefs()` methods for both the top-level
source (this.from) and for each source in the joins array (by iterating through
this.joins and processing each join.source). Ensure the helper captures and
returns the appropriate refs (params or columns) from either source type so they
are properly collected in both methods.

In `@packages/2-sql/4-lanes/relational-core/src/contract-free/table.ts`:
- Around line 219-224: The build() method in the SelectBuilder class currently
allows joins to be added to a FROM-less expression select, which produces
invalid SQL. Add a validation guard at the beginning of the build() method that
throws an error if this.joinItems.length is greater than zero AND this.src is
undefined. This ensures that joins cannot be applied to expression selects that
have no FROM clause, preventing invalid SQL from being generated downstream.

In
`@skills/upgrade/prisma-next-upgrade/upgrades/0.13-to-0.14/migration-op-factories-to-methods.ts`:
- Around line 19-20: The migration factory codemods currently only handle
Postgres migration imports but need to support SQLite as well since the removed
bare factories affect both database types. In
skills/upgrade/prisma-next-upgrade/upgrades/0.13-to-0.14/migration-op-factories-to-methods.ts:
(1) at lines 19-20, update the comment to mention both Postgres and SQLite
modules; (2) at lines 50-51, expand the regex pattern used for import stripping
to include 'sqlite' and 'target-sqlite' alongside 'postgres' and
'target-postgres'; (3) at lines 247-248, expand the regex pattern used for
migration-import detection to include 'sqlite' and 'target-sqlite'; (4) at lines
275-277, add the SQLite migration import path strings
('`@prisma-next/sqlite/migration`' and '`@prisma-next/target-sqlite/migration`') to
the relevance check. Apply the identical changes to the parallel file in
skills/extension-author/prisma-next-extension-upgrade/upgrades/0.13-to-0.14/migration-op-factories-to-methods.ts
at the corresponding line ranges (lines 19-20, 50-51, 247-248, and 275-277).

---

Outside diff comments:
In `@packages/2-sql/4-lanes/relational-core/src/contract-free/dml.ts`:
- Around line 4-17: Remove the new symbol re-exports (CfExprSelectQuery,
CfFnOptions, CfInsertQuery, CfSelectQuery, CfUpdateQuery, CfUpsertBuilder,
CfUpsertQuery, ColumnDescriptor, ColumnProxy, ColumnSchema, cfExpr, cfTable,
ExcludedProxy, exprSelect) from the dml.ts file and instead add them to the
src/exports/contract-free.ts file. According to the coding guidelines,
re-exports should only be expanded in exports/ folders, not in internal barrel
files like dml.ts.

---

Nitpick comments:
In `@packages/3-targets/3-targets/postgres/src/core/postgres-schema.ts`:
- Around line 165-171: The tableSource method uses an inline ternary operator
for the conditional object spread with alias, which should be replaced with the
ifDefined helper for consistency with the codebase's conditional-spread pattern.
Import ifDefined from prisma-next/utils/defined at the top of the
postgres-schema.ts file, then replace the ternary expression in the tableSource
method's return statement with the ifDefined helper to conditionally spread the
alias property.
- Around line 231-236: In the tableSource method of the PostgresTableSource
class, replace the inline ternary conditional spread for the alias property with
a call to ifDefined. Change the spread operator expression from the ternary
pattern (alias !== undefined ? { alias } : {}) to use ifDefined('alias', alias)
instead. Ensure that ifDefined is imported from prisma-next/utils/defined at the
top of the file if it is not already imported.
🪄 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: 7a46788d-118c-4a8e-9b10-e3bc0b7bc62e

📥 Commits

Reviewing files that changed from the base of the PR and between 3c96875 and e51f05f.

⛔ Files ignored due to path filters (10)
  • projects/migrate-marker-ledger-to-typed-query-ast-commands/design-notes.md is excluded by !projects/**
  • projects/migrate-marker-ledger-to-typed-query-ast-commands/learnings.md is excluded by !projects/**
  • projects/migrate-marker-ledger-to-typed-query-ast-commands/plan.md is excluded by !projects/**
  • projects/migrate-marker-ledger-to-typed-query-ast-commands/slices/typed-migration-verification-queries/dispatches/01-substrate-and-first-consumers.md is excluded by !projects/**
  • projects/migrate-marker-ledger-to-typed-query-ast-commands/slices/typed-migration-verification-queries/dispatches/02-joins-exists-constraint-check.md is excluded by !projects/**
  • projects/migrate-marker-ledger-to-typed-query-ast-commands/slices/typed-migration-verification-queries/dispatches/03-pg-sweep.md is excluded by !projects/**
  • projects/migrate-marker-ledger-to-typed-query-ast-commands/slices/typed-migration-verification-queries/dispatches/04-sqlite-sweep.md is excluded by !projects/**
  • projects/migrate-marker-ledger-to-typed-query-ast-commands/slices/typed-migration-verification-queries/plan.md is excluded by !projects/**
  • projects/migrate-marker-ledger-to-typed-query-ast-commands/slices/typed-migration-verification-queries/spec.md is excluded by !projects/**
  • projects/migrate-marker-ledger-to-typed-query-ast-commands/trace.jsonl is excluded by !projects/**
📒 Files selected for processing (91)
  • apps/telemetry-backend/migrations/app/20260520T1317_migration/migration.ts
  • examples/prisma-next-demo/fixtures/showcase/migrations/app/20260601T0727_rollback_alice/migration.ts
  • examples/prisma-next-demo/fixtures/showcase/migrations/app/20260601T0727_rollback_locale/migration.ts
  • examples/prisma-next-demo/fixtures/showcase/migrations/app/20260601T0727_rollback_users/migration.ts
  • examples/prisma-next-demo/fixtures/showcase/migrations/app/20260601T0730_revert_experiment/migration.ts
  • examples/prisma-next-demo/fixtures/showcase/migrations/app/20260602T1624_rollback_to_users_from_tip/migration.ts
  • examples/prisma-next-demo/fixtures/showcase/migrations/app/20260602T1626_rollback_to_users_from_bio/migration.ts
  • examples/prisma-next-demo/fixtures/skip-rollback/migrations/app/20260305T1000_rollback_to_phone/migration.ts
  • examples/prisma-next-demo/fixtures/skip-rollback/migrations/app/20260306T1000_rollback_to_init/migration.ts
  • examples/prisma-next-demo/migrations/app/20260422T0720_initial/migration.json
  • examples/prisma-next-demo/migrations/app/20260422T0720_initial/migration.ts
  • examples/prisma-next-demo/migrations/app/20260422T0720_initial/ops.json
  • examples/prisma-next-demo/migrations/app/20260422T0742_migration/migration.json
  • examples/prisma-next-demo/migrations/app/20260422T0742_migration/ops.json
  • examples/prisma-next-demo/migrations/app/20260422T0748_migration/migration.json
  • examples/prisma-next-demo/migrations/app/20260422T0748_migration/migration.ts
  • examples/prisma-next-demo/migrations/app/20260422T0748_migration/ops.json
  • examples/prisma-next-demo/migrations/app/20260605T1145_mti_variant_link_columns/migration.json
  • examples/prisma-next-demo/migrations/app/20260605T1145_mti_variant_link_columns/migration.ts
  • examples/prisma-next-demo/migrations/app/20260605T1145_mti_variant_link_columns/ops.json
  • examples/prisma-next-demo/migrations/app/20260610T0000_add_priority_enum/migration.json
  • examples/prisma-next-demo/migrations/app/20260610T0000_add_priority_enum/migration.ts
  • examples/prisma-next-demo/migrations/app/20260610T0000_add_priority_enum/ops.json
  • examples/prisma-next-demo/migrations/app/20260610T2216_set_priority_default/migration.json
  • examples/prisma-next-demo/migrations/app/20260610T2216_set_priority_default/migration.ts
  • examples/prisma-next-demo/migrations/app/20260610T2216_set_priority_default/ops.json
  • examples/prisma-next-postgis-demo/migrations/app/20260512T1309_migration/migration.json
  • examples/prisma-next-postgis-demo/migrations/app/20260512T1309_migration/ops.json
  • packages/2-sql/4-lanes/relational-core/src/ast/types.ts
  • packages/2-sql/4-lanes/relational-core/src/contract-free/dml.ts
  • packages/2-sql/4-lanes/relational-core/src/contract-free/table.ts
  • packages/2-sql/4-lanes/relational-core/src/exports/contract-free.ts
  • packages/2-sql/4-lanes/relational-core/test/contract-free/expr-select.test.ts
  • packages/2-sql/5-runtime/src/middleware/budgets.ts
  • packages/2-sql/5-runtime/src/middleware/lints.ts
  • packages/3-extensions/paradedb/migrations/20260601T0000_install_pg_search_extension/migration.ts
  • packages/3-extensions/pgvector/migrations/20260601T0000_install_vector_extension/migration.ts
  • packages/3-extensions/pgvector/test/migrations/planner.behavior.test.ts
  • packages/3-extensions/postgis/migrations/20260601T0000_install_postgis_extension/migration.ts
  • packages/3-extensions/sql-orm-client/src/where-binding.ts
  • packages/3-extensions/sql-orm-client/test/rich-filters-and-where.test.ts
  • packages/3-extensions/sql-orm-client/test/rich-query-plans.test.ts
  • packages/3-targets/3-targets/postgres/src/contract-free/checks.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/op-factory-call.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/operations/columns.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/operations/constraints.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/operations/dependencies.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/operations/enums.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/operations/indexes.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/operations/shared.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/operations/tables.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/planner-recipes.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/planner-sql-checks.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/planner-strategies.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/postgres-migration.ts
  • packages/3-targets/3-targets/postgres/src/core/postgres-schema.ts
  • packages/3-targets/3-targets/postgres/src/exports/contract-free.ts
  • packages/3-targets/3-targets/postgres/src/exports/migration.ts
  • packages/3-targets/3-targets/postgres/src/exports/planner-sql-checks.ts
  • packages/3-targets/3-targets/postgres/test/migrations/index-ddl.test.ts
  • packages/3-targets/3-targets/postgres/test/migrations/op-factory-call.test.ts
  • packages/3-targets/3-targets/postgres/test/migrations/verification-checks.test.ts
  • packages/3-targets/3-targets/sqlite/src/contract-free/checks.ts
  • packages/3-targets/3-targets/sqlite/src/core/migrations/op-factory-call.ts
  • packages/3-targets/3-targets/sqlite/src/core/migrations/operations/columns.ts
  • packages/3-targets/3-targets/sqlite/src/core/migrations/operations/indexes.ts
  • packages/3-targets/3-targets/sqlite/src/core/migrations/operations/shared.ts
  • packages/3-targets/3-targets/sqlite/src/core/migrations/operations/tables.ts
  • packages/3-targets/3-targets/sqlite/src/core/migrations/sqlite-migration.ts
  • packages/3-targets/3-targets/sqlite/src/exports/contract-free.ts
  • packages/3-targets/3-targets/sqlite/src/exports/migration.ts
  • packages/3-targets/3-targets/sqlite/test/migrations/op-factory-call.test.ts
  • packages/3-targets/3-targets/sqlite/test/migrations/verification-checks.test.ts
  • packages/3-targets/6-adapters/postgres/src/core/sql-renderer.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/op-factory-call.lowering.test.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/op-factory-call.rendering.test.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/planner-sql-checks.test.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/planner.integration.test.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/planner.reconciliation.test.ts
  • packages/3-targets/6-adapters/postgres/test/verification-checks-lowering.test.ts
  • packages/3-targets/6-adapters/sqlite/src/core/adapter.ts
  • packages/3-targets/6-adapters/sqlite/src/core/descriptor-meta.ts
  • packages/3-targets/6-adapters/sqlite/test/migrations/create-table-call-lowering.test.ts
  • packages/3-targets/6-adapters/sqlite/test/migrations/render-typescript.roundtrip.test.ts
  • packages/3-targets/6-adapters/sqlite/test/verification-checks-lowering.test.ts
  • skills/extension-author/prisma-next-extension-upgrade/upgrades/0.13-to-0.14/instructions.md
  • skills/extension-author/prisma-next-extension-upgrade/upgrades/0.13-to-0.14/migration-op-factories-to-methods.ts
  • skills/upgrade/prisma-next-upgrade/upgrades/0.13-to-0.14/instructions.md
  • skills/upgrade/prisma-next-upgrade/upgrades/0.13-to-0.14/migration-op-factories-to-methods.ts
  • test/integration/test/cross-package/middleware-cache.test.ts
  • test/integration/test/rewriting-middleware.integration.test.ts
💤 Files with no reviewable changes (2)
  • packages/3-targets/3-targets/sqlite/src/exports/migration.ts
  • packages/3-targets/3-targets/postgres/src/exports/planner-sql-checks.ts

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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/6-adapters/postgres/src/core/sql-renderer.ts (1)

448-451: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Quote or validate function-source names before rendering.

node.fn is interpolated directly into FROM, but the upstream FunctionSource contract stores it as a plain string. That makes this typed AST path behave like raw SQL for function names; quote schema-qualified identifier segments or model the name structurally before lowering.

🛡️ Proposed fix
+function renderQualifiedFunctionName(fn: string): string {
+  const parts = fn.split('.');
+  if (parts.some((part) => part.length === 0)) {
+    throw new Error(`Invalid Postgres function source name: ${fn}`);
+  }
+  return parts.map((part) => quoteIdentifier(part)).join('.');
+}
+
 function renderSource(
   source: AnyFromSource,
   contract: PostgresContract,
   pim: ParamIndexMap,
 ): string {
@@
     case 'function-source': {
       const args = node.args.map((arg) => renderExpr(arg, contract, pim)).join(', ');
-      const call = `${node.fn}(${args})`;
+      const call = `${renderQualifiedFunctionName(node.fn)}(${args})`;
       return node.alias !== undefined ? `${call} AS ${quoteIdentifier(node.alias)}` : call;
     }
🤖 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/src/core/sql-renderer.ts` around lines
448 - 451, The 'function-source' case in the switch statement directly
interpolates node.fn into the SQL string without quoting it, which creates a
security vulnerability and may cause issues with schema-qualified identifiers.
Quote the function name using the quoteIdentifier function before interpolating
it into the call expression, similar to how the alias is quoted. This ensures
that node.fn is properly escaped and safe to use in the generated SQL regardless
of its content.
🤖 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/6-adapters/postgres/src/core/sql-renderer.ts`:
- Around line 448-451: The 'function-source' case in the switch statement
directly interpolates node.fn into the SQL string without quoting it, which
creates a security vulnerability and may cause issues with schema-qualified
identifiers. Quote the function name using the quoteIdentifier function before
interpolating it into the call expression, similar to how the alias is quoted.
This ensures that node.fn is properly escaped and safe to use in the generated
SQL regardless of its content.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: d7be0f71-e937-4e97-94fb-ef54930df9c7

📥 Commits

Reviewing files that changed from the base of the PR and between e51f05f and 8d38116.

📒 Files selected for processing (8)
  • examples/prisma-next-demo/migrations/app/20260422T0748_migration/migration.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/planner-strategies.ts
  • packages/3-targets/3-targets/postgres/src/core/postgres-schema.ts
  • packages/3-targets/6-adapters/postgres/src/core/sql-renderer.ts
  • skills/extension-author/prisma-next-extension-upgrade/upgrades/0.13-to-0.14/instructions.md
  • skills/upgrade/prisma-next-upgrade/upgrades/0.13-to-0.14/instructions.md
  • test/integration/test/cross-package/middleware-cache.test.ts
  • test/integration/test/rewriting-middleware.integration.test.ts
✅ Files skipped from review due to trivial changes (2)
  • skills/upgrade/prisma-next-upgrade/upgrades/0.13-to-0.14/instructions.md
  • skills/extension-author/prisma-next-extension-upgrade/upgrades/0.13-to-0.14/instructions.md
🚧 Files skipped from review as they are similar to previous changes (5)
  • test/integration/test/cross-package/middleware-cache.test.ts
  • test/integration/test/rewriting-middleware.integration.test.ts
  • examples/prisma-next-demo/migrations/app/20260422T0748_migration/migration.ts
  • packages/3-targets/3-targets/postgres/src/core/postgres-schema.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/planner-strategies.ts

wmadden-electric and others added 2 commits June 15, 2026 13:02
…tColumnRefs

Both methods now handle `function-source` in joins (not just
`derived-table-source`). `collectColumnRefs()` also gains the top-level
`from` case that `collectParamRefs()` already had. Tests pin both paths.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Throws when joinItems.length > 0 and src is undefined, preventing
silent production of invalid SQL. FROM-less no-join queries (e.g.
exprSelect().project(...)) are unaffected. Tests added for both paths.

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

Both codemod copies now recognize '@prisma-next/sqlite/migration' and
'@prisma-next/target-sqlite/migration' in the import-stripping regex,
the migration-import detection regex, and the relevance string checks.
Header comment updated to mention SQLite targets. Both files kept
identical.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
@wmadden-electric

Copy link
Copy Markdown
Contributor Author

A04a — dml.ts re-export (wont_address) 👎

The dml.ts file re-exports from ./table and exports/contract-free.ts re-exports from ../contract-free/dml. This technically brushes the no-barrel-files rule, but dml.ts is an intra-module aggregator for the contract-free subpackage — not a public-facing barrel. Restructuring exports/contract-free.ts to point directly at the individual source files is a separate pre-existing refactor that predates this PR. No correctness issue was introduced here, so out of scope.

Replaces inline ternary spreads with the ifDefined helper in both
PostgresSchema.tableSource() and PostgresUnboundSchema.tableSource().
No behavior change.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
@wmadden-electric

Copy link
Copy Markdown
Contributor Author

A04b+A04c — ifDefined alias spread (Done)

Replaced both inline ternary spreads in PostgresSchema.tableSource() and PostgresUnboundSchema.tableSource() with ifDefined('alias', alias). ifDefined was already imported from @prisma-next/utils/defined.

@wmadden-electric

Copy link
Copy Markdown
Contributor Author

A05a — FunctionSource quoting (wont_address) 👎

CodeRabbit suggested quoting node.fn segments via quoteIdentifier. I investigated this and cannot safely apply it.

The FunctionSource.fn field holds SQL function names — specifically pragma_table_info (SQLite) and to_regclass (Postgres). These are bare function call targets, not schema-qualified identifiers. Wrapping the function name in double-quotes produces "pragma_table_info"(?) instead of pragma_table_info(?), which is wrong SQL.

The lowering tests in packages/3-targets/6-adapters/sqlite/test/verification-checks-lowering.test.ts assert the rendered SQL is FROM pragma_table_info(?) — quoting would make those tests fail. There are currently no schema-qualified function sources in the codebase (e.g. public.my_func), so there is nothing to protect against injection in the current usage.

If schema-qualified function sources are added in the future, the quoting decision should be made at FunctionSource.of() construction time (store schema + name separately), not at render time by splitting on .. Leaving as-is.

Removes setNotNull from the import and converts the bare factory call
to this.setNotNull({ schema, table, column }) — the instance-method form
that replaced it when bare op-factory exports were removed.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
wmadden-electric and others added 2 commits June 15, 2026 13:53
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
… (F2)

The descriptor-meta.test.ts property tests make the disjointness invariant
explicit: every codec in the execution set has renderOutputType === undefined,
every excluded codec carries renderOutputType, and the excluded set is exactly
{sql/char@1, sql/varchar@1}.

Choosing option (b) over (a) — the explicit split would require touching the
shared CodecDescriptor interface for a filter that only one adapter file uses;
the property test is the cheapest durable closure and turns a silent re-break
into a red test at the moment the invariant is violated.

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 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/6-adapters/sqlite/test/descriptor-meta.test.ts`:
- Line 12: The comment on line 12 of descriptor-meta.test.ts contains a
transient path reference to `projects/.../code-review.md` which becomes stale
over time. Remove this transient artifact path reference and either replace it
with a stable reference such as a TML-* identifier or ADR id that provides
lasting context, or simply remove the path pointer while retaining the
meaningful description of what the saga motivates if that context is still
valuable.
🪄 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: b87c069a-6cb8-42dc-bcf1-9487e454b58e

📥 Commits

Reviewing files that changed from the base of the PR and between c820c49 and 93b921b.

⛔ Files ignored due to path filters (2)
  • projects/migrate-marker-ledger-to-typed-query-ast-commands/design-notes.md is excluded by !projects/**
  • projects/migrate-marker-ledger-to-typed-query-ast-commands/learnings.md is excluded by !projects/**
📒 Files selected for processing (2)
  • packages/3-targets/6-adapters/sqlite/test/descriptor-meta.test.ts
  • test/integration/test/cli-journeys/migration-round-trip.e2e.test.ts

wmadden-electric and others added 5 commits June 15, 2026 16:07
Postgres migrations must name their schema deliberately. Make `schema`
non-optional on all 21 PostgresMigration methods and remove the
`options.schema ?? UNBOUND_NAMESPACE_ID` fallback — there is no default and no
search_path-relative (unbound) option on Postgres, because an unspecified
schema resolves against whatever search_path the connection carries, and that
ambiguity in a migration is an antipattern. The unbound/unspecified namespace
concept remains only for SQLite (no schemas) and Mongo (connection db).

The planner constructs *Call nodes directly (not via these methods), so it is
unaffected; test:integration is green. The planner's separate un-namespaced-PG
-> unbound resolution is a pre-existing bug tracked under its own ticket and is
deliberately untouched here.

A negative type test pins that calling a method without `schema` is a compile
error (@ts-expect-error), so the required-schema contract cannot silently
regress to optional.

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

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>

# Conflicts:
#	examples/prisma-next-demo/migrations/app/20260422T0720_initial/migration.json
#	examples/prisma-next-demo/migrations/app/20260422T0742_migration/migration.json
#	examples/prisma-next-demo/migrations/app/20260422T0748_migration/migration.json
#	examples/prisma-next-demo/migrations/app/20260605T1145_mti_variant_link_columns/migration.json
#	examples/prisma-next-demo/migrations/app/20260610T0000_add_priority_enum/migration.json
#	examples/prisma-next-demo/migrations/app/20260610T2216_set_priority_default/migration.json
#	packages/3-targets/3-targets/postgres/src/core/migrations/op-factory-call.ts
#	packages/3-targets/3-targets/postgres/src/core/migrations/operations/enums.ts
#	packages/3-targets/3-targets/postgres/src/core/migrations/planner-recipes.ts
#	packages/3-targets/3-targets/postgres/src/core/migrations/planner-strategies.ts
#	packages/3-targets/3-targets/postgres/src/core/postgres-schema.ts
#	packages/3-targets/3-targets/postgres/src/exports/migration.ts
#	packages/3-targets/6-adapters/postgres/test/migrations/op-factory-call.rendering.test.ts
#	skills/upgrade/prisma-next-upgrade/upgrades/0.13-to-0.14/instructions.md
…ion-verification-queries

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>

# Conflicts:
#	examples/prisma-next-demo/migrations/app/20260422T0720_initial/migration.json
#	examples/prisma-next-demo/migrations/app/20260422T0720_initial/migration.ts
#	examples/prisma-next-demo/migrations/app/20260611T1856_convert_user_type_to_value_set/migration.json
#	examples/prisma-next-demo/migrations/app/20260611T1856_convert_user_type_to_value_set/migration.ts
#	examples/prisma-next-demo/migrations/app/20260611T1856_convert_user_type_to_value_set/ops.json
#	projects/migrate-marker-ledger-to-typed-query-ast-commands/design-notes.md
…letion

The merge of main's TML-2853 (native Postgres enum deletion) removed
operations/enums.ts — the only consumer of enumTypeExistsAst. The builder and
its EnumTypeExistsCheckBuilder interface were left as dead production code still
advertised on the target's contract-free export surface. Removed the builder,
its interface, the re-export, and the test coverage that only exercised it.

The sibling extensionExistsAst stays live (its coverage is preserved); no other
check builder is touched.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
The comment referenced a transient project path (projects/.../code-review.md),
violating no-transient-project-ids-in-code. Replaced with the substantive
rationale — the codec-lookup re-break history that motivated the property tests
— without the transient reference.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…ion-verification-queries

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>

# Conflicts:
#	packages/3-targets/3-targets/postgres/src/core/postgres-schema.ts
@wmadden-electric
wmadden-electric added this pull request to the merge queue Jun 15, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Jun 15, 2026
@wmadden-electric
wmadden-electric added this pull request to the merge queue Jun 15, 2026
Merged via the queue into main with commit 10d8b60 Jun 15, 2026
28 of 29 checks passed
@wmadden-electric
wmadden-electric deleted the tml-2889-typed-migration-verification-queries branch June 15, 2026 17:43
github-merge-queue Bot pushed a commit that referenced this pull request Jun 16, 2026
… 223 (#838)

## At a glance

```diff
- "namespaces": {
-   "__unbound__": { ... empty ... },
-   "public": { "user": {...} }
- }
+ "namespaces": {
+   "public": { "user": {...} }
+ }
```

Postgres contracts were emitting an empty `__unbound__` storage
namespace slot alongside `public` on every contract — in violation of
[ADR 223 — Target-owned default
namespace](../blob/main/docs/architecture%20docs/adrs/ADR%20223%20-%20Target-owned%20default%20namespace.md),
which makes `target.defaultNamespaceId` (= `"public"` for Postgres) the
static, target-owned default. Surfaced during the
[#825](#825) (TML-2889)
review.

## The decision

Two sites in the authoring/emit pipeline injected the spurious slot.
Both are now gated on `defaultNamespaceId === UNBOUND_NAMESPACE_ID` —
descriptor-driven, no `targetId === 'postgres'` branch anywhere (per ADR
223). Only SQLite and Mongo (whose default IS unbound) keep the slot.

| Site | Where | Fix |
|---|---|---|
| 1 | `packages/2-sql/2-authoring/contract-ts/src/build-contract.ts:748`
— end of `buildSqlContractFromDefinition`, the path both the PSL
interpreter and the TS DSL converge on | Guard the
`ensureUnboundNamespaceSlot` call on `defaultNamespaceId ===
UNBOUND_NAMESPACE_ID`. |
| 2 |
`packages/2-sql/9-family/src/core/ir/sql-contract-serializer-base.ts` —
`hydrateSqlStorage` re-injected the slot on every deserialize
round-trip, defeating site 1 during emit | Added `protected abstract get
defaultNamespaceId(): string` to `SqlContractSerializerBase`;
implemented in PG, SQLite, and the `SqlContractSerializer` family-level
fallback (which preserves legacy behaviour for callers without a target
descriptor). Mongo uses its own base class and is unaffected. |

## Why two sites

D1 (diagnosis dispatch) identified site 1 only; the in-memory contract
built via the TS DSL was already clean (only `public`). D2's emit traced
through `executeContractEmit` →
`familyInstance.deserializeContract(enrichedIR)` → `hydrateSqlStorage`,
where the round-trip re-introduced the slot. Sites 1 and 2 are
independent; both need the gate.

## What's regenerated

- **Baked extension-pack contracts** (pgvector, paradedb, postgis,
supabase) — `src/contract.json` + `.d.ts` lose the `__unbound__` slot;
their migration `head.json` refs and `migration.ts` hashes are rewritten
by `migrations:regen`.
- **multi-extension-monorepo** sub-extensions (audit, feature-flags) —
same shape; `scripts/regen-extension-migrations.mjs` was extended to
walk these (they live under
`examples/multi-extension-monorepo/packages/*`, outside the script's
original `packages/3-extensions/` walk).
- **`apps/telemetry-backend`, `examples/{bundle-size, paradedb-demo,
prisma-next-cloudflare-worker, multi-extension-monorepo/app,
prisma-next-demo, prisma-next-postgis-demo}`** — emitted contracts +
migration chains lose the slot; migration hashes update.
- **Test fixtures** under
`packages/2-sql/4-lanes/sql-builder/test/fixtures/generated/`,
`packages/3-extensions/sql-orm-client/test/fixtures/generated/`,
`test/e2e/framework/test/fixtures/generated/`,
`test/integration/test/{fixtures,namespaced-accessors/fixtures/generated}/`
— same.

## What was NOT regenerated

The diamond + 6 sibling fixture chains under
`examples/prisma-next-demo/fixtures/*/migrations/app/`. The regen script
(`regen-example-migrations.mjs`) requires a per-step `contract.prisma`
for each migration directory to recompute the end-state contract; these
chains store only `migration.ts` per step plus a single root
`contract.prisma` for the final state. A `grep -rln "fixtures/diamond"`
(excluding `node_modules`, `dist`, `.json`, `.d.ts`) returns **zero
hits** outside the slice's own docs — no test or script reads these
fixtures. Left stale on this branch; follow-up to add a regen mechanism
or rewrite them.

## Tests

- **New IR-level invariant pin**:
`packages/2-sql/2-authoring/contract-psl/test/interpreter.namespaces.test.ts`
— a bare `model user { id String @id }` interpreted against the PG
target produces `domain.namespaces.public.models.user` +
`storage.namespaces.public`, with no `__unbound__` namespace. Goes red
on `main` without the fix at site 1.
- **Updated bug-encoding tests**: 6 cases in
`packages/2-sql/2-authoring/contract-ts/test/contract-builder.namespaces.test.ts`
that asserted `__unbound__` was present in PG storage — flipped to
assert post-fix shape with a `// TML-2916` marker.
- **Collateral test update**:
`packages/3-extensions/pgvector/test/descriptor.test.ts:100` asserted
the install-vector pre/postcheck SQL contained literal `extname =
'vector'`. The regen produces parameterised SQL (`"extname" = \$1` +
`params: ["vector"]`), a downstream effect of TML-2889's typed-AST
routing of verification queries. Test updated to assert both the
parameter placeholder and the params array.

## ADR-223 grep gate

```
git grep -nE "targetId === 'postgres'|=== \"postgres\"" packages/1-framework packages/2-sql
```

Returns the same 3 hits as before — all input validation guards
rejecting reserved namespace names. No new namespace-defaulting
branches.

## Related

- Surfaced by [#825](#825)
([TML-2889](https://linear.app/prisma-company/issue/TML-2889)) — the
authoring-half fix (hand-authored `Migration` PG methods require
explicit `schema`). This PR is the planner/interpreter half.
- Part of the [Marker/ledger via typed query
AST](https://linear.app/prisma-company/project/markerledger-via-typed-query-ast-dc62ab25d151)
project (pre-Phase-2 prerequisite cleanup).

Closes [TML-2916](https://linear.app/prisma-company/issue/TML-2916).

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

## Release Notes

* **Refactor**
* Generated contract schemas and typings now omit the previously
included “unbound” storage namespace, leaving only the `public`
namespace where applicable.
* Regenerated contract artifacts reflect updated content hashes tied to
the revised storage schema.

* **Chores**
* Updated contract serialization/namespace handling to align with target
configuration.
* Extension-migration regeneration now supports additional extension
roots.

* **Tests**
* Added/updated assertions to confirm unbound namespaces are not
produced.

* **Documentation**
* Updated upgrade guidance to note the regenerated contracts and hash
changes.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

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

## Linked issue

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

## At a glance

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

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

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

## Decision

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

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

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

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

## Slices merged in this project

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

## What follows in the successor project

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

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

## Reviewer notes

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

## Testing performed

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

## Skill update

n/a — internal project workspace removal.

## Checklist

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

---------

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Co-authored-by: Claude Sonnet 4.6 <[email protected]>
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants