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

TML-2253: SQL DDL query-AST + contract-free builder + control-table bootstrap through the adapter - #661

Closed
wmadden-electric wants to merge 10 commits into
mainfrom
tml-2253-migrate-marker-ledger-to-typed-query-ast-commands
Closed

wmadden-electric wants to merge 10 commits into
mainfrom
tml-2253-migrate-marker-ledger-to-typed-query-ast-commands

Conversation

@wmadden-electric

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

Copy link
Copy Markdown
Contributor

Summary

Foundation slice of the migrate marker ledger to typed query-AST commands project. Makes DDL a first-class part of the SQL query AST, gives it an ergonomic contract-free construction surface, and routes the control-table bootstrap through the adapter's lower() — eliminating the hand-written, silently-divergent bootstrap SQL by construction.

The sibling marker-write SPI slice (DML: updateMarker/read dedup/invariant convergence) is intentionally separate and not in this PR.

What changed

  • DDL is a first-class AnyQueryAst kind. New frozen CreateSchemaAst / CreateTableAst nodes in @prisma-next/sql-relational-core, members of AnyQueryAst / queryAstKinds, with virtual collectParamRefs() / rewrite / toQueryAst. No runtime throw on DDL anywhere — every exhaustive AnyQueryAst consumer handles it (renderers render it; lints/decoding opt it out like raw-sql). This anticipates runtime DDL as a valid capability; only the user-facing authoring surface is deferred.
  • Contract-free builder (@prisma-next/sql-relational-core/contract-free): createSchema/createTable/col/lit/now/emptyCollection construct DDL from plain identifiers + dialect-neutral descriptors, with no contract/codec/branding — the construction layer the control plane needs (the contract-bound sql() builder is unusable there).
  • Dialect-neutral descriptor, per-adapter resolution. Column types/defaults are neutral; the Postgres and SQLite renderers map them to native SQL (text[]/jsonb/timestamptz/now()/'{}' vs TEXT/INTEGER PRIMARY KEY AUTOINCREMENT/datetime('now')/'[]'). Lowered output is pinned byte-equal to the previous bootstrap constants.
  • Bootstrap routed through the adapter. New SqlControlAdapter.ensureControlTableAsts() SPI, owned per target (Postgres includes the schema; SQLite doesn't). The marker/ledger column shape is defined exactly once in @prisma-next/family-sql — the anti-divergence linchpin. Both migration runners and the family-sql sign path route uniformly via ensureControlTableAsts() → lower() → driver.query, with no target branching.
  • Retired the seven superseded raw control-table DDL constants across target-postgres, target-sqlite, and sql-runtime.

Bugs fixed in passing

  • The family-sql sign path ran PG-flavored DDL unconditionally — broken for SQLite. Routing through the target's control adapter corrects it. (Postgres sign now also ensures the ledger table — accepted, idempotent IF NOT EXISTS, consistent with the runners.)
  • sql-runtime lints.ts would have thrown on a DDL AST (latent), and decoding.ts accessed a non-existent .returning — both fixed to handle DDL without throwing.

Test plan

  • pnpm typecheck — 135/135
  • pnpm lint:deps — clean
  • pnpm fixtures:check — clean (byte-identical routing, no golden drift)
  • Per-adapter byte-equality tests (Postgres + SQLite) pin lowered DDL == the bootstrap shapes
  • No-throw regression tests for DDL through the lints/decoding runtime paths
  • Grep gate: no raw control-table bootstrap DDL remains in any src tree
  • CI integration suite (note: local runs show pre-existing environmental @prisma/dev "Connection terminated" flakiness under parallel load — every bootstrap/sign file passes in isolation)

Summary by CodeRabbit

  • New Features

    • Added contract-free DDL builder API with createSchema(), createTable(), and column helpers (col(), lit(), now(), emptyCollection()) for constructing schema and table AST nodes.
    • Extended control table bootstrap to use dynamic DDL AST generation via adapter interface instead of pre-built statements.
  • Refactor

    • Restructured control table initialization to support dialect-specific DDL rendering and improved flexibility in table bootstrap.

wmadden added 10 commits May 31, 2026 17:00
…odes

Add two frozen query-AST node classes beside the existing DML nodes:
- CreateSchemaAst (kind: create-schema): name + ifNotExists flag
- CreateTableAst (kind: create-table): table ref + column descriptors + ifNotExists

Column descriptor shape (CreateTableColumn) carries a dialect-neutral
ColumnType (text | text-array | jsonb | int | bigserial | timestamptz)
and ColumnDefault (literal | now) — exactly enough to express the
marker + ledger table column shapes across both Postgres and SQLite.

Both kinds are added to AnyQueryAst and queryAstKinds.
collectParamRefs() returns [] (bootstrap DDL is param-free).
rewrite() is identity (no sub-expressions to rewrite).
toQueryAst() returns self.

Tests cover: node construction, frozen-ness, collectParamRefs, rewrite
identity, and all four marker/ledger table column shapes.

Signed-off-by: Will Madden <[email protected]>
New module (src/contract-free/ddl.ts) exported at ./contract-free:
- createSchema(name, opts) -> CreateSchemaAst
- createTable(table, columns, opts) -> CreateTableAst
- col(name, type, opts) -> CreateTableColumn descriptor
- lit(value) -> literal ColumnDefault
- now() -> now ColumnDefault

The module accepts a dotted table-name string ("schema.name") or a
descriptor object; no contract, codec, or storage-hash dependency.

Tests cover: createSchema/createTable construction, dotted-name parsing,
descriptor-object form, col/lit/now helpers, and the four marker+ledger
table shapes for both Postgres and SQLite dialects.

Signed-off-by: Will Madden <[email protected]>
Drop the CreateTableAst bare cast via an explicit map return type, keep AST
symbols off contract-free/ddl re-exports, add empty-collection defaults with
emptyCollection(), and consolidate marker/ledger tests to one neutral AST
per table.

Signed-off-by: Will Madden <[email protected]>
Render create-schema / create-table as first-class query kinds in the shared
Postgres renderer, resolving the neutral column type/default descriptors to
Postgres idioms (text[] / jsonb / timestamptz / now() / '{}'). Pins the lowered
output byte-equal to the existing bootstrap constants via both lower entrypoints.

Signed-off-by: Will Madden <[email protected]>
Render create-table as a first-class query kind in the SQLite renderer,
resolving neutral column type/default descriptors to SQLite idioms (TEXT /
INTEGER / INTEGER PRIMARY KEY AUTOINCREMENT / (datetime('now')) / '[]'), with
no schema qualifier. create-schema lowers to a no-op empty statement (SQLite
has no schema namespace). Pins lowered output byte-equal to the existing
SQLite bootstrap constants.

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

Add buildMarkerTableAst/buildLedgerTableAst helpers in family-sql so the
marker/ledger column shape is defined exactly once, and a new
SqlControlAdapter.ensureControlTableAsts() SPI method that each target
implements with its own bootstrap sequence (Postgres prepends a
prisma_contract schema node; SQLite returns the two unqualified tables).

The two migration runners and the family sign path now route the bootstrap
uniformly over ensureControlTableAsts() + lower(), skipping empty SQL so
SQLite 's no-op schema node drops out without any target branch. The lowered
SQL is byte-identical to the existing ensure*Statement constants, which stay
in place (their removal is a follow-up).

The Postgres sign path now also ensures the ledger table (previously only the
schema + marker were created unconditionally), so the family sign-database
test drops the schema with CASCADE to clear the now-present ledger.

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

The marker/ledger/schema bootstrap DDL is now produced by the control
adapter (ensureControlTableAsts() lowered through the adapter), so the
hand-written ensure*Statement constants are fully dead. Delete the seven
constants and their re-exports across target-postgres, target-sqlite, and
sql-runtime.

Repoint the surviving importers, all tests:
- adapter byte-equality tests inline the exact SQL the constants held, so
  they remain regression pins on the lowered DDL.
- runner.errors setup tests define the same literals locally to seed an
  already-initialised database.
- the widely-used Postgres marker/schema literals move into the shared
  sql-runtime test/utils module (test-only), and the verify/db-verify/sign
  integration tests import them from there.

No production source retains any raw control-table DDL string; the
spec grep gate and fixtures:check are clean.

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

create-schema / create-table are first-class AnyQueryAst kinds but two
exhaustive consumers in sql-runtime were unaware of them: projectionListFromAst
fell through to ast.returning (which DDL lacks) and the lints switch routed
DDL into its satisfies-never default throw. Both now opt DDL out the same way
raw-sql already does — undefined projection and a no-op lint arm — so DDL
typechecks everywhere and never triggers a runtime throw. Adds regression
tests pinning no-throw decode-context and lints handling for DDL ASTs.

Signed-off-by: Will Madden <[email protected]>
…-query-ast-commands

Project spec/plan/design-notes, the sql-marker-ops-through-adapter slice
spec/plan, the code-review log, learnings, and subagent registry for the
SQL DDL query-AST foundation slice.

Signed-off-by: Will Madden <[email protected]>
@wmadden-electric
wmadden-electric requested a review from a team as a code owner June 1, 2026 05:35
@coderabbitai

coderabbitai Bot commented Jun 1, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR introduces a dialect-neutral DDL AST API and refactors control table bootstrap to use target-specific AST rendering instead of hardcoded SQL statements. It spans relational-core AST definitions, contract-free builders, runtime integration, adapter implementations for Postgres and SQLite, and comprehensive test coverage.

Changes

DDL AST to Control Table Bootstrapping

Layer / File(s) Summary
DDL AST types and contracts
packages/2-sql/4-lanes/relational-core/src/ast/types.ts, test/ast/ddl.test.ts
Introduces CreateSchemaAst, CreateTableAst, and supporting types (ColumnType, ColumnDefault, CreateTableColumn). AST nodes implement QueryAst interface with identity rewrite semantics and zero param collection. Tests validate immutability and interface compliance.
Contract-free DDL builders
packages/2-sql/4-lanes/relational-core/src/contract-free/ddl.ts, src/exports/contract-free.ts, test/contract-free/ddl-builder.test.ts
Implements createSchema(), createTable(), col() and column-default helpers (lit, now, emptyCollection). Builders construct DDL ASTs without requiring a contract; table-name parsing supports dotted schema.table notation. Tests cover builder behavior, optional field handling, and composed table ASTs.
Package exports and build configuration
packages/2-sql/4-lanes/relational-core/package.json, tsdown.config.ts
Exposes contract-free builders via new ./contract-free subpath export and adds corresponding build entry.
Runtime DDL support
packages/2-sql/5-runtime/src/codecs/decoding.ts, src/middleware/lints.ts, src/sql-marker.ts, src/exports/index.ts, README.md
Updates decoder to treat DDL as having no projection list, updates lints middleware to opt DDL out of inspection, removes DDL statement exports from sql-marker, and adjusts re-exports to include APP_SPACE_ID.
Test utilities and codec/lints tests
packages/2-sql/5-runtime/test/utils.ts, test/codec-decode-ctx.test.ts, test/lints.test.ts
Migrates hardcoded DDL statements to test-local definitions, adds tests validating DDL handling in decode contexts and lints middleware.
Control adapter interface and family sign
packages/2-sql/9-family/src/core/control-adapter.ts, src/core/control-instance.ts
Introduces ensureControlTableAsts() method on SqlControlAdapter and integrates DDL execution into SqlControlFamilyInstance.sign(). Family now iterates adapter-provided ASTs, lowers each via the contract, and executes resulting SQL.
Canonical control table builders
packages/2-sql/9-family/src/core/control-tables.ts, src/exports/control-adapter.ts
Implements buildMarkerTableAst and buildLedgerTableAst with dialect-stable defaults (literal empty JSON for meta, empty collections for invariants). Exports builders from control-adapter public API.
Postgres target migration
packages/3-targets/3-targets/postgres/src/core/migrations/runner.ts, src/core/migrations/statement-builders.ts, src/exports/statement-builders.ts, test/migrations/statement-builders.test.ts
Updates runner to call family.ensureControlTableAsts() and lower each AST. Removes exported DDL statement builders and updates test imports and re-exports.
Postgres adapter DDL rendering
packages/3-targets/6-adapters/postgres/src/core/control-adapter.ts, src/core/sql-renderer.ts
Implements ensureControlTableAsts() composing schema + marker/ledger tables. Extends SQL renderer to handle create-schema and create-table, generating CREATE SCHEMA and CREATE TABLE SQL with column definitions and defaults.
Postgres adapter tests
packages/3-targets/6-adapters/postgres/test/migrations/ddl-lowering.test.ts, test/migrations/runner.errors.integration.test.ts
Adds byte-for-byte equality tests for DDL rendering and validates ensureControlTableAsts() routing. Defines local DDL statements instead of importing from statement-builders.
SQLite target migration
packages/3-targets/3-targets/sqlite/src/core/migrations/runner.ts, src/core/migrations/statement-builders.ts, src/exports/statement-builders.ts
Updates runner to call family.ensureControlTableAsts() and lower each AST. Removes exported DDL statement builders.
SQLite adapter DDL rendering
packages/3-targets/6-adapters/sqlite/src/core/control-adapter.ts, src/core/adapter.ts
Implements ensureControlTableAsts() providing marker/ledger tables (no schema step). Extends SQL renderer to handle create-schema (no-op) and create-table, mapping types and defaults to SQLite syntax.
SQLite adapter tests
packages/3-targets/6-adapters/sqlite/test/migrations/ddl-lowering.test.ts, test/migrations/runner.errors.test.ts
Adds byte-for-byte equality tests for DDL rendering and validates ensureControlTableAsts() routing. Defines local DDL statements instead of importing from statement-builders.
Integration test migration
test/integration/test/cli.db-verify.*.test.ts, test/integration/test/family.*.test.ts
Updates test imports to source DDL helpers from @prisma-next/sql-runtime/test/utils. Updates schema cleanup to use DROP SCHEMA ... CASCADE.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Suggested reviewers

  • wmadden
  • aqrln

🐰 From contract-free dreams to schema-free themes,
DDL builders paint SQL in moonbeams,
Tables bootstrap with grace and speed,
Each dialect renders what it needs! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 32.26% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically describes the main change: introducing SQL DDL as query-AST, providing a contract-free builder, and implementing control-table bootstrap through adapters.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch tml-2253-migrate-marker-ledger-to-typed-query-ast-commands

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@pkg-pr-new

pkg-pr-new Bot commented Jun 1, 2026

Copy link
Copy Markdown

Open in StackBlitz

@prisma-next/extension-author-tools

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

@prisma-next/mongo-runtime

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

@prisma-next/family-mongo

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

@prisma-next/sql-runtime

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

@prisma-next/family-sql

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

@prisma-next/extension-arktype-json

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

@prisma-next/middleware-cache

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

@prisma-next/mongo

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

@prisma-next/extension-paradedb

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

@prisma-next/extension-pgvector

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

@prisma-next/extension-postgis

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

@prisma-next/postgres

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

@prisma-next/sql-orm-client

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

@prisma-next/sqlite

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

@prisma-next/target-mongo

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

@prisma-next/adapter-mongo

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

@prisma-next/driver-mongo

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

@prisma-next/contract

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

@prisma-next/utils

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

@prisma-next/config

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

@prisma-next/errors

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

@prisma-next/framework-components

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

@prisma-next/operations

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

@prisma-next/ts-render

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

@prisma-next/contract-authoring

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

@prisma-next/ids

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

@prisma-next/psl-parser

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

@prisma-next/psl-printer

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

@prisma-next/cli

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

@prisma-next/cli-telemetry

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

@prisma-next/emitter

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

@prisma-next/migration-tools

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

prisma-next

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

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

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

@prisma-next/mongo-codec

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

@prisma-next/mongo-contract

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

@prisma-next/mongo-value

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

@prisma-next/mongo-contract-psl

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

@prisma-next/mongo-contract-ts

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

@prisma-next/mongo-emitter

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

@prisma-next/mongo-schema-ir

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

@prisma-next/mongo-query-ast

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

@prisma-next/mongo-orm

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

@prisma-next/mongo-query-builder

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

@prisma-next/mongo-lowering

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

@prisma-next/mongo-wire

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

@prisma-next/sql-contract

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

@prisma-next/sql-errors

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

@prisma-next/sql-operations

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

@prisma-next/sql-schema-ir

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

@prisma-next/sql-contract-psl

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

@prisma-next/sql-contract-ts

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

@prisma-next/sql-contract-emitter

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

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

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

@prisma-next/sql-relational-core

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

@prisma-next/sql-builder

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

@prisma-next/target-postgres

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

@prisma-next/target-sqlite

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

@prisma-next/adapter-postgres

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

@prisma-next/adapter-sqlite

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

@prisma-next/driver-postgres

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

@prisma-next/driver-sqlite

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

commit: 3198914

@github-actions

github-actions Bot commented Jun 1, 2026

Copy link
Copy Markdown

size-limit report 📦

Path Size
postgres / no-emit 136.07 KB (+0.15% 🔺)
postgres / emit 125.82 KB (+0.19% 🔺)
mongo / no-emit 75.69 KB (0%)
mongo / emit 70.68 KB (0%)

@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: 5

🧹 Nitpick comments (1)
packages/2-sql/9-family/src/core/control-instance.ts (1)

268-270: ⚡ Quick win

Use the cast helper in the new adapter-guard branch.

This adds another bare as in production code. Please route the ensureControlTableAsts probe through castAs/blindCast (or a small helper) instead of extending the manual-cast pattern here.

As per coding guidelines, "No bare as in production code. Use blindCast<T, "Reason"> or castAs<T> from @prisma-next/utils/casts; see the no-bare-casts skill for the decision tree."

🤖 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/9-family/src/core/control-instance.ts` around lines 268 - 270,
Replace the bare TypeScript cast used to probe for ensureControlTableAsts with
the project's cast helper: instead of using (value as { ensureControlTableAsts:
unknown }).ensureControlTableAsts, call castAs or blindCast to assert a helper
type and then test the property; e.g., use castAs<{ ensureControlTableAsts?:
unknown }>(value) or blindCast<typeof value,
"probe-ensureControlTableAsts">(value) and then check typeof
casted.ensureControlTableAsts === 'function' alongside the existing lower check
— update the predicate that references ensureControlTableAsts so there are no
bare `as` casts and the probe flows through castAs/blindCast.
🤖 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/test/ast/ddl.test.ts`:
- Around line 131-159: Update the CreateTableAst.of fixture so column defaults
match the canonical bootstrap: change the "space" column default from { kind:
'literal', value: APP_SPACE_ID } to an SQL literal containing the quoted value
(i.e. literal "'${APP_SPACE_ID}'"), change the "meta" column default from {
kind: 'empty-collection' } to an SQL literal "'{}'", and keep "invariants" as {
kind: 'empty-collection' }; locate these in the CreateTableAst.of call for the
marker table and replace the default kinds/values accordingly.

In
`@packages/2-sql/4-lanes/relational-core/test/contract-free/ddl-builder.test.ts`:
- Around line 145-193: The test fixture should mirror the production canonical
marker defaults: update the createTable call so the 'space' column uses a quoted
literal default for the app id (instead of using APP_SPACE_ID unquoted) and the
'meta' column uses a literal '{}' default (not emptyCollection()), while leaving
'invariants' using emptyCollection(); adjust the col(...) entries for 'space'
and 'meta' in the createTable call accordingly so assertions reflect the
quoted-literal for space and literal '{}' for meta (keep collectParamRefs
expectation).

In `@packages/3-targets/6-adapters/postgres/src/core/sql-renderer.ts`:
- Around line 848-865: renderCreateSchema, renderCreateTable, and
renderColumnDef interpolate raw identifiers and must call quoteIdentifier before
emitting DDL; update renderCreateSchema to wrap ast.name with quoteIdentifier,
update renderCreateTable to quote ast.table.schema and ast.table.name when
building qualified, and update renderColumnDef to quote column.name (leaving
types and literal defaults unchanged); reuse the existing quoteIdentifier helper
so reserved words and mixed-case names are safely quoted in all created SQL
identifiers.

In `@packages/3-targets/6-adapters/sqlite/src/core/adapter.ts`:
- Around line 592-603: renderCreateTable and renderColumnDef currently emit raw
identifiers which can produce invalid SQLite DDL for reserved words or
hyphenated names; update both functions to call quoteIdentifier(...) for table
and column names (use quoteIdentifier(ast.table.name) in renderCreateTable and
quoteIdentifier(column.name) in renderColumnDef) so all DDL identifiers are
properly quoted, and ensure any places that concatenate the name into the CREATE
TABLE or column definition strings use the quoted value.
- Around line 597-617: renderColumnType currently emits "INTEGER PRIMARY KEY
AUTOINCREMENT" for 'bigserial', which makes every bigserial a PK; change the
logic so renderColumnType('bigserial') returns only the base type (e.g.,
'INTEGER') and move the PK/autoincrement emission into renderColumnDef: when
column.primaryKey is true and column.type === 'bigserial' push both 'PRIMARY
KEY' and 'AUTOINCREMENT' (for non-bigserial keep the existing PRIMARY KEY
behavior), ensuring non-PK bigserial columns remain plain INTEGER. Update
renderColumnType and renderColumnDef accordingly (referencing the functions
renderColumnType, renderColumnDef and the column.primaryKey/column.type
properties).

---

Nitpick comments:
In `@packages/2-sql/9-family/src/core/control-instance.ts`:
- Around line 268-270: Replace the bare TypeScript cast used to probe for
ensureControlTableAsts with the project's cast helper: instead of using (value
as { ensureControlTableAsts: unknown }).ensureControlTableAsts, call castAs or
blindCast to assert a helper type and then test the property; e.g., use castAs<{
ensureControlTableAsts?: unknown }>(value) or blindCast<typeof value,
"probe-ensureControlTableAsts">(value) and then check typeof
casted.ensureControlTableAsts === 'function' alongside the existing lower check
— update the predicate that references ensureControlTableAsts so there are no
bare `as` casts and the probe flows through castAs/blindCast.
🪄 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: f39d6ebd-758c-4ec0-b284-a433e61e36b4

📥 Commits

Reviewing files that changed from the base of the PR and between 7ac37dd and 3198914.

⛔ Files ignored due to path filters (7)
  • 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/sql-marker-ops-through-adapter/plan.md is excluded by !projects/**
  • projects/migrate-marker-ledger-to-typed-query-ast-commands/slices/sql-marker-ops-through-adapter/spec.md is excluded by !projects/**
  • projects/migrate-marker-ledger-to-typed-query-ast-commands/spec.md is excluded by !projects/**
  • projects/migrate-marker-ledger-to-typed-query-ast-commands/subagent-registry.md is excluded by !projects/**
📒 Files selected for processing (39)
  • packages/2-sql/4-lanes/relational-core/package.json
  • packages/2-sql/4-lanes/relational-core/src/ast/types.ts
  • packages/2-sql/4-lanes/relational-core/src/contract-free/ddl.ts
  • packages/2-sql/4-lanes/relational-core/src/exports/contract-free.ts
  • packages/2-sql/4-lanes/relational-core/test/ast/ddl.test.ts
  • packages/2-sql/4-lanes/relational-core/test/contract-free/ddl-builder.test.ts
  • packages/2-sql/4-lanes/relational-core/tsdown.config.ts
  • packages/2-sql/5-runtime/README.md
  • packages/2-sql/5-runtime/src/codecs/decoding.ts
  • packages/2-sql/5-runtime/src/exports/index.ts
  • packages/2-sql/5-runtime/src/middleware/lints.ts
  • packages/2-sql/5-runtime/src/sql-marker.ts
  • packages/2-sql/5-runtime/test/codec-decode-ctx.test.ts
  • packages/2-sql/5-runtime/test/lints.test.ts
  • packages/2-sql/5-runtime/test/utils.ts
  • packages/2-sql/9-family/src/core/control-adapter.ts
  • packages/2-sql/9-family/src/core/control-instance.ts
  • packages/2-sql/9-family/src/core/control-tables.ts
  • packages/2-sql/9-family/src/exports/control-adapter.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/runner.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/statement-builders.ts
  • packages/3-targets/3-targets/postgres/src/exports/statement-builders.ts
  • packages/3-targets/3-targets/postgres/test/migrations/statement-builders.test.ts
  • packages/3-targets/3-targets/sqlite/src/core/migrations/runner.ts
  • packages/3-targets/3-targets/sqlite/src/core/migrations/statement-builders.ts
  • packages/3-targets/3-targets/sqlite/src/exports/statement-builders.ts
  • packages/3-targets/6-adapters/postgres/src/core/control-adapter.ts
  • packages/3-targets/6-adapters/postgres/src/core/sql-renderer.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/ddl-lowering.test.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/runner.errors.integration.test.ts
  • packages/3-targets/6-adapters/sqlite/src/core/adapter.ts
  • packages/3-targets/6-adapters/sqlite/src/core/control-adapter.ts
  • packages/3-targets/6-adapters/sqlite/test/migrations/ddl-lowering.test.ts
  • packages/3-targets/6-adapters/sqlite/test/migrations/runner.errors.test.ts
  • test/integration/test/cli.db-verify.aggregate-schema.test.ts
  • test/integration/test/cli.db-verify.e2e.test.ts
  • test/integration/test/family.sign-database.test.ts
  • test/integration/test/family.verify-database.basic.test.ts
  • test/integration/test/family.verify-database.errors.test.ts
💤 Files with no reviewable changes (7)
  • packages/3-targets/3-targets/postgres/src/exports/statement-builders.ts
  • packages/2-sql/5-runtime/src/sql-marker.ts
  • packages/2-sql/5-runtime/src/exports/index.ts
  • packages/2-sql/5-runtime/README.md
  • packages/3-targets/3-targets/sqlite/src/exports/statement-builders.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/statement-builders.ts
  • packages/3-targets/3-targets/sqlite/src/core/migrations/statement-builders.ts

Comment on lines +131 to +159
const ast = CreateTableAst.of(
{ schema: 'prisma_contract', name: 'marker' },
[
{
name: 'space',
type: 'text',
notNull: true,
primaryKey: true,
default: { kind: 'literal', value: APP_SPACE_ID },
},
{ name: 'core_hash', type: 'text', notNull: true },
{ name: 'profile_hash', type: 'text', notNull: true },
{ name: 'contract_json', type: 'jsonb' },
{ name: 'canonical_version', type: 'int' },
{ name: 'updated_at', type: 'timestamptz', notNull: true, default: { kind: 'now' } },
{ name: 'app_tag', type: 'text' },
{
name: 'meta',
type: 'jsonb',
notNull: true,
default: { kind: 'empty-collection' },
},
{
name: 'invariants',
type: 'text-array',
notNull: true,
default: { kind: 'empty-collection' },
},
],

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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Align this marker-table fixture with the canonical bootstrap defaults.

space is modeled here as an unquoted literal and meta as empty-collection, but the canonical builder uses SQL literals for both (lit(\'${APP_SPACE_ID}'`)andlit("'{}'")) and only uses emptyCollection()forinvariants. As written, this test can still pass if metaregresses from{}to[]` on SQLite.

Suggested test fix
         {
           name: 'space',
           type: 'text',
           notNull: true,
           primaryKey: true,
-          default: { kind: 'literal', value: APP_SPACE_ID },
+          default: { kind: 'literal', value: `'${APP_SPACE_ID}'` },
         },
@@
         {
           name: 'meta',
           type: 'jsonb',
           notNull: true,
-          default: { kind: 'empty-collection' },
+          default: { kind: 'literal', value: "'{}'" },
         },
🤖 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/test/ast/ddl.test.ts` around lines 131
- 159, Update the CreateTableAst.of fixture so column defaults match the
canonical bootstrap: change the "space" column default from { kind: 'literal',
value: APP_SPACE_ID } to an SQL literal containing the quoted value (i.e.
literal "'${APP_SPACE_ID}'"), change the "meta" column default from { kind:
'empty-collection' } to an SQL literal "'{}'", and keep "invariants" as { kind:
'empty-collection' }; locate these in the CreateTableAst.of call for the marker
table and replace the default kinds/values accordingly.

Comment on lines +145 to +193
const ast = createTable(
'prisma_contract.marker',
[
col('space', 'text', {
notNull: true,
primaryKey: true,
default: lit(APP_SPACE_ID),
}),
col('core_hash', 'text', { notNull: true }),
col('profile_hash', 'text', { notNull: true }),
col('contract_json', 'jsonb'),
col('canonical_version', 'int'),
col('updated_at', 'timestamptz', { notNull: true, default: now() }),
col('app_tag', 'text'),
col('meta', 'jsonb', { notNull: true, default: emptyCollection() }),
col('invariants', 'text-array', { notNull: true, default: emptyCollection() }),
],
{ ifNotExists: true },
);

expect(ast.table).toEqual({ schema: 'prisma_contract', name: 'marker' });
expect(ast.ifNotExists).toBe(true);
expect(ast.columns).toHaveLength(9);
expect(ast.columns[0]).toMatchObject({
name: 'space',
type: 'text',
notNull: true,
primaryKey: true,
default: { kind: 'literal', value: 'app' },
});
expect(ast.columns[5]).toMatchObject({
name: 'updated_at',
type: 'timestamptz',
notNull: true,
default: { kind: 'now' },
});
expect(ast.columns[7]).toMatchObject({
name: 'meta',
type: 'jsonb',
notNull: true,
default: { kind: 'empty-collection' },
});
expect(ast.columns[8]).toMatchObject({
name: 'invariants',
type: 'text-array',
notNull: true,
default: { kind: 'empty-collection' },
});
expect(ast.collectParamRefs()).toEqual([]);

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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Mirror the canonical marker defaults in this builder test.

The production control-table builder uses a quoted literal for space and a literal '{}' for meta; only invariants uses emptyCollection(). Keeping this fixture divergent means this test won't catch the exact default-shape regression the adapter bootstrap path is supposed to pin.

Suggested test fix
         col('space', 'text', {
           notNull: true,
           primaryKey: true,
-          default: lit(APP_SPACE_ID),
+          default: lit(`'${APP_SPACE_ID}'`),
         }),
@@
-        col('meta', 'jsonb', { notNull: true, default: emptyCollection() }),
+        col('meta', 'jsonb', { notNull: true, default: lit("'{}'") }),
@@
     expect(ast.columns[0]).toMatchObject({
       name: 'space',
       type: 'text',
       notNull: true,
       primaryKey: true,
-      default: { kind: 'literal', value: 'app' },
+      default: { kind: 'literal', value: `'${APP_SPACE_ID}'` },
     });
@@
     expect(ast.columns[7]).toMatchObject({
       name: 'meta',
       type: 'jsonb',
       notNull: true,
-      default: { kind: 'empty-collection' },
+      default: { kind: 'literal', value: "'{}'" },
     });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const ast = createTable(
'prisma_contract.marker',
[
col('space', 'text', {
notNull: true,
primaryKey: true,
default: lit(APP_SPACE_ID),
}),
col('core_hash', 'text', { notNull: true }),
col('profile_hash', 'text', { notNull: true }),
col('contract_json', 'jsonb'),
col('canonical_version', 'int'),
col('updated_at', 'timestamptz', { notNull: true, default: now() }),
col('app_tag', 'text'),
col('meta', 'jsonb', { notNull: true, default: emptyCollection() }),
col('invariants', 'text-array', { notNull: true, default: emptyCollection() }),
],
{ ifNotExists: true },
);
expect(ast.table).toEqual({ schema: 'prisma_contract', name: 'marker' });
expect(ast.ifNotExists).toBe(true);
expect(ast.columns).toHaveLength(9);
expect(ast.columns[0]).toMatchObject({
name: 'space',
type: 'text',
notNull: true,
primaryKey: true,
default: { kind: 'literal', value: 'app' },
});
expect(ast.columns[5]).toMatchObject({
name: 'updated_at',
type: 'timestamptz',
notNull: true,
default: { kind: 'now' },
});
expect(ast.columns[7]).toMatchObject({
name: 'meta',
type: 'jsonb',
notNull: true,
default: { kind: 'empty-collection' },
});
expect(ast.columns[8]).toMatchObject({
name: 'invariants',
type: 'text-array',
notNull: true,
default: { kind: 'empty-collection' },
});
expect(ast.collectParamRefs()).toEqual([]);
const ast = createTable(
'prisma_contract.marker',
[
col('space', 'text', {
notNull: true,
primaryKey: true,
default: lit(`'${APP_SPACE_ID}'`),
}),
col('core_hash', 'text', { notNull: true }),
col('profile_hash', 'text', { notNull: true }),
col('contract_json', 'jsonb'),
col('canonical_version', 'int'),
col('updated_at', 'timestamptz', { notNull: true, default: now() }),
col('app_tag', 'text'),
col('meta', 'jsonb', { notNull: true, default: lit("'{}'") }),
col('invariants', 'text-array', { notNull: true, default: emptyCollection() }),
],
{ ifNotExists: true },
);
expect(ast.table).toEqual({ schema: 'prisma_contract', name: 'marker' });
expect(ast.ifNotExists).toBe(true);
expect(ast.columns).toHaveLength(9);
expect(ast.columns[0]).toMatchObject({
name: 'space',
type: 'text',
notNull: true,
primaryKey: true,
default: { kind: 'literal', value: `'${APP_SPACE_ID}'` },
});
expect(ast.columns[5]).toMatchObject({
name: 'updated_at',
type: 'timestamptz',
notNull: true,
default: { kind: 'now' },
});
expect(ast.columns[7]).toMatchObject({
name: 'meta',
type: 'jsonb',
notNull: true,
default: { kind: 'literal', value: "'{}'" },
});
expect(ast.columns[8]).toMatchObject({
name: 'invariants',
type: 'text-array',
notNull: true,
default: { kind: 'empty-collection' },
});
expect(ast.collectParamRefs()).toEqual([]);
🤖 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/test/contract-free/ddl-builder.test.ts`
around lines 145 - 193, The test fixture should mirror the production canonical
marker defaults: update the createTable call so the 'space' column uses a quoted
literal default for the app id (instead of using APP_SPACE_ID unquoted) and the
'meta' column uses a literal '{}' default (not emptyCollection()), while leaving
'invariants' using emptyCollection(); adjust the col(...) entries for 'space'
and 'meta' in the createTable call accordingly so assertions reflect the
quoted-literal for space and literal '{}' for meta (keep collectParamRefs
expectation).

Comment on lines +848 to +865
function renderCreateSchema(ast: CreateSchemaAst): string {
return `create schema${ast.ifNotExists ? ' if not exists' : ''} ${ast.name}`;
}

function renderCreateTable(ast: CreateTableAst): string {
const qualified =
ast.table.schema !== undefined ? `${ast.table.schema}.${ast.table.name}` : ast.table.name;
const columns = ast.columns.map((column) => ` ${renderColumnDef(column)}`).join(',\n');
return `create table${ast.ifNotExists ? ' if not exists' : ''} ${qualified} (\n${columns}\n )`;
}

function renderColumnDef(column: CreateTableColumn): string {
const parts: string[] = [column.name, renderColumnType(column.type)];
if (column.notNull) parts.push('not null');
if (column.primaryKey) parts.push('primary key');
if (column.default !== undefined) parts.push(`default ${renderColumnDefault(column.default)}`);
return parts.join(' ');
}

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Quote DDL identifiers before interpolating them.

renderCreateSchema, renderCreateTable, and renderColumnDef currently emit raw schema/table/column names. That breaks on reserved words or mixed-case identifiers and opens the door to malformed SQL if a caller passes an untrusted name. The DML paths in this renderer already use quoteIdentifier; DDL should do the same.

Proposed fix
 function renderCreateSchema(ast: CreateSchemaAst): string {
-  return `create schema${ast.ifNotExists ? ' if not exists' : ''} ${ast.name}`;
+  return `create schema${ast.ifNotExists ? ' if not exists' : ''} ${quoteIdentifier(ast.name)}`;
 }
 
 function renderCreateTable(ast: CreateTableAst): string {
   const qualified =
-    ast.table.schema !== undefined ? `${ast.table.schema}.${ast.table.name}` : ast.table.name;
+    ast.table.schema !== undefined
+      ? `${quoteIdentifier(ast.table.schema)}.${quoteIdentifier(ast.table.name)}`
+      : quoteIdentifier(ast.table.name);
   const columns = ast.columns.map((column) => `    ${renderColumnDef(column)}`).join(',\n');
   return `create table${ast.ifNotExists ? ' if not exists' : ''} ${qualified} (\n${columns}\n  )`;
 }
 
 function renderColumnDef(column: CreateTableColumn): string {
-  const parts: string[] = [column.name, renderColumnType(column.type)];
+  const parts: string[] = [quoteIdentifier(column.name), renderColumnType(column.type)];
   if (column.notNull) parts.push('not null');
   if (column.primaryKey) parts.push('primary key');
   if (column.default !== undefined) parts.push(`default ${renderColumnDefault(column.default)}`);
   return parts.join(' ');
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
function renderCreateSchema(ast: CreateSchemaAst): string {
return `create schema${ast.ifNotExists ? ' if not exists' : ''} ${ast.name}`;
}
function renderCreateTable(ast: CreateTableAst): string {
const qualified =
ast.table.schema !== undefined ? `${ast.table.schema}.${ast.table.name}` : ast.table.name;
const columns = ast.columns.map((column) => ` ${renderColumnDef(column)}`).join(',\n');
return `create table${ast.ifNotExists ? ' if not exists' : ''} ${qualified} (\n${columns}\n )`;
}
function renderColumnDef(column: CreateTableColumn): string {
const parts: string[] = [column.name, renderColumnType(column.type)];
if (column.notNull) parts.push('not null');
if (column.primaryKey) parts.push('primary key');
if (column.default !== undefined) parts.push(`default ${renderColumnDefault(column.default)}`);
return parts.join(' ');
}
function renderCreateSchema(ast: CreateSchemaAst): string {
return `create schema${ast.ifNotExists ? ' if not exists' : ''} ${quoteIdentifier(ast.name)}`;
}
function renderCreateTable(ast: CreateTableAst): string {
const qualified =
ast.table.schema !== undefined
? `${quoteIdentifier(ast.table.schema)}.${quoteIdentifier(ast.table.name)}`
: quoteIdentifier(ast.table.name);
const columns = ast.columns.map((column) => ` ${renderColumnDef(column)}`).join(',\n');
return `create table${ast.ifNotExists ? ' if not exists' : ''} ${qualified} (\n${columns}\n )`;
}
function renderColumnDef(column: CreateTableColumn): string {
const parts: string[] = [quoteIdentifier(column.name), renderColumnType(column.type)];
if (column.notNull) parts.push('not null');
if (column.primaryKey) parts.push('primary key');
if (column.default !== undefined) parts.push(`default ${renderColumnDefault(column.default)}`);
return parts.join(' ');
}
🤖 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
848 - 865, renderCreateSchema, renderCreateTable, and renderColumnDef
interpolate raw identifiers and must call quoteIdentifier before emitting DDL;
update renderCreateSchema to wrap ast.name with quoteIdentifier, update
renderCreateTable to quote ast.table.schema and ast.table.name when building
qualified, and update renderColumnDef to quote column.name (leaving types and
literal defaults unchanged); reuse the existing quoteIdentifier helper so
reserved words and mixed-case names are safely quoted in all created SQL
identifiers.

Comment on lines +592 to +603
function renderCreateTable(ast: CreateTableAst): string {
const columns = ast.columns.map((column) => ` ${renderColumnDef(column)}`).join(',\n');
return `CREATE TABLE${ast.ifNotExists ? ' IF NOT EXISTS' : ''} ${ast.table.name} (\n${columns}\n )`;
}

function renderColumnDef(column: CreateTableColumn): string {
const parts: string[] = [column.name, renderColumnType(column.type)];
if (column.notNull) parts.push('NOT NULL');
if (column.primaryKey && column.type !== 'bigserial') parts.push('PRIMARY KEY');
if (column.default !== undefined) parts.push(`DEFAULT ${renderColumnDefault(column.default)}`);
return parts.join(' ');
}

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Quote DDL identifiers before lowering.

renderCreateTable() and renderColumnDef() emit raw table/column names, so identifiers like order, group, or user-id lower to invalid SQLite DDL. The rest of this renderer already goes through quoteIdentifier(...); DDL should do the same.

💡 Suggested fix
 function renderCreateTable(ast: CreateTableAst): string {
   const columns = ast.columns.map((column) => `    ${renderColumnDef(column)}`).join(',\n');
-  return `CREATE TABLE${ast.ifNotExists ? ' IF NOT EXISTS' : ''} ${ast.table.name} (\n${columns}\n  )`;
+  return `CREATE TABLE${ast.ifNotExists ? ' IF NOT EXISTS' : ''} ${quoteIdentifier(ast.table.name)} (\n${columns}\n  )`;
 }
 
 function renderColumnDef(column: CreateTableColumn): string {
-  const parts: string[] = [column.name, renderColumnType(column.type)];
+  const parts: string[] = [quoteIdentifier(column.name), renderColumnType(column.type)];
   if (column.notNull) parts.push('NOT NULL');
   if (column.primaryKey && column.type !== 'bigserial') parts.push('PRIMARY KEY');
   if (column.default !== undefined) parts.push(`DEFAULT ${renderColumnDefault(column.default)}`);
   return parts.join(' ');
 }
🤖 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/sqlite/src/core/adapter.ts` around lines 592 -
603, renderCreateTable and renderColumnDef currently emit raw identifiers which
can produce invalid SQLite DDL for reserved words or hyphenated names; update
both functions to call quoteIdentifier(...) for table and column names (use
quoteIdentifier(ast.table.name) in renderCreateTable and
quoteIdentifier(column.name) in renderColumnDef) so all DDL identifiers are
properly quoted, and ensure any places that concatenate the name into the CREATE
TABLE or column definition strings use the quoted value.

Comment on lines +597 to +617
function renderColumnDef(column: CreateTableColumn): string {
const parts: string[] = [column.name, renderColumnType(column.type)];
if (column.notNull) parts.push('NOT NULL');
if (column.primaryKey && column.type !== 'bigserial') parts.push('PRIMARY KEY');
if (column.default !== undefined) parts.push(`DEFAULT ${renderColumnDefault(column.default)}`);
return parts.join(' ');
}

function renderColumnType(type: ColumnType): string {
switch (type) {
case 'text':
case 'text-array':
case 'jsonb':
case 'timestamptz':
return 'TEXT';
case 'int':
return 'INTEGER';
case 'bigserial':
return 'INTEGER PRIMARY KEY AUTOINCREMENT';
}
}

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Don't make every bigserial column a primary key.

renderColumnType('bigserial') always lowers to INTEGER PRIMARY KEY AUTOINCREMENT, even when column.primaryKey is false. That silently changes the AST's schema semantics for any non-PK bigserial column.

💡 Suggested fix
 function renderColumnDef(column: CreateTableColumn): string {
-  const parts: string[] = [column.name, renderColumnType(column.type)];
+  if (column.type === 'bigserial' && !column.primaryKey) {
+    throw new Error('SQLite only supports bigserial for PRIMARY KEY columns');
+  }
+
+  const parts: string[] = [
+    quoteIdentifier(column.name),
+    column.type === 'bigserial'
+      ? 'INTEGER PRIMARY KEY AUTOINCREMENT'
+      : renderColumnType(column.type),
+  ];
   if (column.notNull) parts.push('NOT NULL');
-  if (column.primaryKey && column.type !== 'bigserial') parts.push('PRIMARY KEY');
+  if (column.primaryKey && column.type !== 'bigserial') parts.push('PRIMARY KEY');
   if (column.default !== undefined) parts.push(`DEFAULT ${renderColumnDefault(column.default)}`);
   return parts.join(' ');
 }
 
 function renderColumnType(type: ColumnType): string {
   switch (type) {
@@
     case 'bigserial':
-      return 'INTEGER PRIMARY KEY AUTOINCREMENT';
+      return 'INTEGER';
   }
 }
🤖 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/sqlite/src/core/adapter.ts` around lines 597 -
617, renderColumnType currently emits "INTEGER PRIMARY KEY AUTOINCREMENT" for
'bigserial', which makes every bigserial a PK; change the logic so
renderColumnType('bigserial') returns only the base type (e.g., 'INTEGER') and
move the PK/autoincrement emission into renderColumnDef: when column.primaryKey
is true and column.type === 'bigserial' push both 'PRIMARY KEY' and
'AUTOINCREMENT' (for non-bigserial keep the existing PRIMARY KEY behavior),
ensuring non-PK bigserial columns remain plain INTEGER. Update renderColumnType
and renderColumnDef accordingly (referencing the functions renderColumnType,
renderColumnDef and the column.primaryKey/column.type properties).

@wmadden wmadden left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Notes:

  • a method which returns a query AST is still returning a query. Don't name those methods "buildXAst()"
  • the AST nodes you added look highly postgres-specific but they live in the relational core. let's discuss
  • column types don't belong in the AST
  • default values are SQL literals, not the nonsense AST node you created so far

* adapter renderer (e.g. Postgres `text[]` / `jsonb` / `timestamptz` /
* `bigserial`, SQLite `TEXT` / `INTEGER` with AUTOINCREMENT).
*/
export type ColumnType = 'text' | 'text-array' | 'jsonb' | 'int' | 'bigserial' | 'timestamptz';

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.

I don't think the AST should be encoding possible column types. Those are dialect/target-specific

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.

We should not add to this bloated file, especially since we're defining a whole new subset of the AST. Split it out.

Comment on lines +1840 to +1843
export type ColumnDefault =
| { readonly kind: 'literal'; readonly value: string }
| { readonly kind: 'now' }
| { readonly kind: 'empty-collection' };

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.

These aren't valid AST abstractions. now() is Postgres-specific. Empty collection sounds general but isn't really

We have abstractions for column defaults somewhere else, in the contract authoring code I think. This should be a SQL literal expression, shouldn't it?

export class CreateSchemaAst extends QueryAst {
readonly kind = 'create-schema' as const;
readonly name: string;
readonly ifNotExists: boolean;

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.

Is this generic, or dialect-specific?

Comment on lines +1908 to +1909
table: { schema?: string; name: string },
columns: readonly CreateTableColumn[],

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.

Why is table not an AST node with its own freeze logic?

* node uniformly (the empty-`sql` result of SQLite's no-op schema node is
* skipped by the caller).
*/
ensureControlTableAsts(): readonly AnyQueryAst[];

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.

Don't call this "Asts". It's a query. ensureControlTableQuery() eg

Comment on lines -258 to +270
typeof (value as { lower: unknown }).lower === 'function'
typeof (value as { lower: unknown }).lower === 'function' &&
'ensureControlTableAsts' in value &&
typeof (value as { ensureControlTableAsts: unknown }).ensureControlTableAsts === 'function'

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.

This is a lot of conditions. Why not just slap an identifier method or property on the interface if we genuinely need this level of granularity in our type predicate? eg isSqlControlAdapter(): true

@@ -666,6 +675,10 @@ export function createSqlFamilyInstance<TTargetId extends string>(
return getControlAdapter().lower(ast, context);
},

ensureControlTableAsts(): readonly AnyQueryAst[] {

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.

Again, don't name query methods "asts"

} from '@prisma-next/sql-relational-core/contract-free';

/**
* Builds the canonical contract-marker table AST.

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.

Builds the QUERY

Comment on lines +867 to +882
function renderColumnType(type: ColumnType): string {
switch (type) {
case 'text':
return 'text';
case 'text-array':
return 'text[]';
case 'jsonb':
return 'jsonb';
case 'int':
return 'int';
case 'bigserial':
return 'bigserial';
case 'timestamptz':
return 'timestamptz';
}
}

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.

This is a terrible smell

Comment on lines +884 to +893
function renderColumnDefault(def: ColumnDefault): string {
switch (def.kind) {
case 'literal':
return def.value;
case 'now':
return 'now()';
case 'empty-collection':
return "'{}'";
}
}

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.

This is a bad smell too

@wmadden-electric

Copy link
Copy Markdown
Contributor Author

Closing in favour of a re-scoped approach.

Design review surfaced that DDL should be a target-contributed part of the SQL query AST — three-layer polymorphic IR (framework interface → family base → target concrete) + an adapter-owned visitor for lowering, where the target owns the node shape and the adapter owns the SQL — not the generic-core AnyQueryAst DDL nodes (closed ColumnType enum, CreateSchema core node) and shared family-sql control-tables surface this PR built.

The project has been respec'd around "DDL in the SQL query AST" with marker/ledger as the first consumer. Slice 1 (ddl-in-query-ast) starts fresh off main. This branch/diff is retained for reference (dialect SQL rendering specifics: identifier quoting, native-type strings).

wmadden-electric added a commit that referenced this pull request Jun 2, 2026
…adapter (#672)

## Linked issue

Refs [TML-2761](https://linear.app/prisma-company/issue/TML-2761) —
foundational slice for marker/ledger via typed query AST commands
(related: TML-2753, TML-2754, TML-2253).

## At a glance

```ts
import { col, fn, lit } from '@prisma-next/sql-relational-core/contract-free';
import { buildControlTableBootstrapAsts } from '@prisma-next/target-postgres/contract-free';

// Migration runner / sign() — no raw CREATE TABLE strings in the execution path
for (const ast of family.bootstrapControlTableAsts()) {
  const { sql, params } = family.lowerAst(ast, { contract });
  await driver.query(sql, params);
}
```

Before this PR, marker/ledger bootstrap executed pre-built SQL strings
from `statement-builders` / `sql-marker`. After it, each target builds
frozen DDL nodes and the control adapter lowers them through the same
visitor path as the runtime adapter.

## Decision

This PR ships a **target-contributed DDL surface** in the SQL query AST
— separate from DML `AnyQueryAst` — with per-target visitors in the
Postgres and SQLite adapters, contract-free constructors, and
**marker/ledger bootstrap** as the first real consumer.

Deliverables:

1. Family `DdlNode` base + `isAnyDdlNode` guard; Postgres
`CreateTable`/`CreateSchema`, SQLite `CreateTable` only.
2. Adapter-owned DDL lowering (`renderLoweredDdl` + per-target
visitors); DML renderer switch untouched.
3. Contract-free builders (`col`/`lit`/`fn`,
`createTable`/`createSchema`) and per-target bootstrap AST factories.
4. Migration runners and `sign()` route bootstrap through
`family.lowerAst()` — no `ensure*Statement` in those paths.

## Reviewer notes

- **Largest diff:** adapter DDL visitors + `control-bootstrap.ts` column
shapes. Byte-equality against `statement-builders` constants is the pin
— see
`packages/3-targets/6-adapters/*/test/migrations/ddl-lowering.test.ts`.
- **PG lowercase/unquoted bootstrap SQL is intentional** — matches
existing `ensure*Statement` output for idempotent bootstrap, not
contract-derived DDL.
- **`ensure*Statement` constants remain** in `statement-builders.ts` /
`sql-marker.ts` for tests and golden pins; only the *execution* paths
were rerouted.
- **Rejected PR #661 surface** (generic-core `ColumnType`, shared
`control-tables.ts`) is absent; grep gate included in verification.
- **Out of scope:** marker DML/SPI consolidation (next slice), planner
adoption, Mongo.

## How it fits together

1. **Separate hierarchy** — `relational-core/src/ast/ddl-types.ts`
defines the family DDL base; targets own concrete node classes in their
packages.
2. **Double-dispatch lowering** — adapters widen `lower()` to
`AnyQueryAst | TargetDdlNode`, routing DDL through `renderLoweredDdl`
and DML through the existing renderer.
3. **Contract-free construction** —
`@prisma-next/sql-relational-core/contract-free` plus
`@prisma-next/target-{postgres,sqlite}/contract-free` build nodes
without a contract.
4. **Bootstrap factories** — `buildControlTableBootstrapAsts()` /
`buildSignMarkerBootstrapAsts()` on each target; exposed on
`SqlControlAdapter` and the family instance.
5. **First consumer** — PG/SQLite migration runners and family `sign()`
lower bootstrap ASTs and execute the result.

## Behavior changes & evidence

- **DDL lowers through per-target visitors, not the DML switch** —
[`packages/3-targets/6-adapters/postgres/src/core/ddl-renderer.ts`](packages/3-targets/6-adapters/postgres/src/core/ddl-renderer.ts),
[`packages/3-targets/6-adapters/sqlite/src/core/ddl-renderer.ts`](packages/3-targets/6-adapters/sqlite/src/core/ddl-renderer.ts).
Evidence:
[`packages/3-targets/6-adapters/postgres/test/migrations/ddl-lowering.test.ts`](packages/3-targets/6-adapters/postgres/test/migrations/ddl-lowering.test.ts),
sqlite sibling.
- **Contract-free column/table builders** —
[`packages/2-sql/4-lanes/relational-core/src/contract-free/column.ts`](packages/2-sql/4-lanes/relational-core/src/contract-free/column.ts),
target `contract-free/ddl.ts`. Evidence: `test/contract-free/` in
relational-core and target packages.
- **Bootstrap execution path uses adapter lowering** —
[`packages/3-targets/3-targets/postgres/src/core/migrations/runner.ts`](packages/3-targets/3-targets/postgres/src/core/migrations/runner.ts),
[`packages/2-sql/9-family/src/core/control-instance.ts`](packages/2-sql/9-family/src/core/control-instance.ts).
Evidence: runner error integration tests, family-sql test suite.
- **`sign()` is target-correct for SQLite** — no longer calls
PG-flavored `ensureSchemaStatement` / `ensureTableStatement` from
`sql-marker.ts`.

## Testing performed

- `pnpm --filter @prisma-next/target-postgres --filter
@prisma-next/target-sqlite --filter @prisma-next/adapter-postgres
--filter @prisma-next/adapter-sqlite --filter @prisma-next/family-sql
typecheck`
- Package tests for the five packages above (DDL lowering,
contract-free, runner errors, family-sql)
- `pnpm fixtures:check` (DML lowering byte-identical)
- Slice grep gates: no `ColumnType`/`CreateSchemaAst` in
relational-core; no `ensure*Statement` in runner/sign bootstrap paths

## Follow-ups

- Marker/ledger DML through adapter (TML-2753 slice)
- Migration planner DDL adoption (TML-2754 slice)
- Mongo marker/ledger (separate slice)

## Alternatives considered

- **Generic-core DDL in `AnyQueryAst` (PR #661)** — rejected; SQLite
would stub `CreateSchema`, and a neutral `ColumnType` enum obscures
dialect-native types.
- **Shared `family-sql` control-tables surface** — rejected; PG and
SQLite marker DDL legitimately differ; each target owns its bootstrap
shape.
- **Single global `DdlVisitor` with SQLite no-ops** — rejected;
per-target visitor interfaces keep SQLite from stubbing schema
operations it doesn't have.

## Skill update

n/a — internal only (framework/target adapter surface; no user-facing
CLI or config change).

## 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 (foundational DDL-in-AST slice).
- [x] Tests are updated.
- [x] The PR title is in `TML-2761: …` form.
- [x] Skill update section filled in.


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

* **New Features**
* Contract-free DDL helpers: createTable/createSchema plus column
builders (col, lit, fn) for portable table/schema definitions.
* Bootstrap query generation exposed for control tables and sign-marker
initialization across Postgres and SQLite.
* Adapters and migration runners now accept and lower DDL nodes so
bootstrapping uses generated DDL instead of fixed statements.

* **Tests**
* Added tests validating DDL builders and lowering for Postgres and
SQLite.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

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