Repository navigation
TML-2253: SQL DDL query-AST + contract-free builder + control-table bootstrap through the adapter - #661
TML-2253: SQL DDL query-AST + contract-free builder + control-table bootstrap through the adapter#661wmadden-electric wants to merge 10 commits into
Conversation
…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]>
…rom README exports 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]>
📝 WalkthroughWalkthroughThis 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. ChangesDDL AST to Control Table Bootstrapping
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Suggested reviewers
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
@prisma-next/extension-author-tools
@prisma-next/mongo-runtime
@prisma-next/family-mongo
@prisma-next/sql-runtime
@prisma-next/family-sql
@prisma-next/extension-arktype-json
@prisma-next/middleware-cache
@prisma-next/mongo
@prisma-next/extension-paradedb
@prisma-next/extension-pgvector
@prisma-next/extension-postgis
@prisma-next/postgres
@prisma-next/sql-orm-client
@prisma-next/sqlite
@prisma-next/target-mongo
@prisma-next/adapter-mongo
@prisma-next/driver-mongo
@prisma-next/contract
@prisma-next/utils
@prisma-next/config
@prisma-next/errors
@prisma-next/framework-components
@prisma-next/operations
@prisma-next/ts-render
@prisma-next/contract-authoring
@prisma-next/ids
@prisma-next/psl-parser
@prisma-next/psl-printer
@prisma-next/cli
@prisma-next/cli-telemetry
@prisma-next/emitter
@prisma-next/migration-tools
prisma-next
@prisma-next/vite-plugin-contract-emit
@prisma-next/mongo-codec
@prisma-next/mongo-contract
@prisma-next/mongo-value
@prisma-next/mongo-contract-psl
@prisma-next/mongo-contract-ts
@prisma-next/mongo-emitter
@prisma-next/mongo-schema-ir
@prisma-next/mongo-query-ast
@prisma-next/mongo-orm
@prisma-next/mongo-query-builder
@prisma-next/mongo-lowering
@prisma-next/mongo-wire
@prisma-next/sql-contract
@prisma-next/sql-errors
@prisma-next/sql-operations
@prisma-next/sql-schema-ir
@prisma-next/sql-contract-psl
@prisma-next/sql-contract-ts
@prisma-next/sql-contract-emitter
@prisma-next/sql-lane-query-builder
@prisma-next/sql-relational-core
@prisma-next/sql-builder
@prisma-next/target-postgres
@prisma-next/target-sqlite
@prisma-next/adapter-postgres
@prisma-next/adapter-sqlite
@prisma-next/driver-postgres
@prisma-next/driver-sqlite
commit: |
size-limit report 📦
|
There was a problem hiding this comment.
Actionable comments posted: 5
🧹 Nitpick comments (1)
packages/2-sql/9-family/src/core/control-instance.ts (1)
268-270: ⚡ Quick winUse the cast helper in the new adapter-guard branch.
This adds another bare
asin production code. Please route theensureControlTableAstsprobe throughcastAs/blindCast(or a small helper) instead of extending the manual-cast pattern here.As per coding guidelines, "No bare
asin production code. UseblindCast<T, "Reason">orcastAs<T>from@prisma-next/utils/casts; see theno-bare-castsskill 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
⛔ Files ignored due to path filters (7)
projects/migrate-marker-ledger-to-typed-query-ast-commands/design-notes.mdis excluded by!projects/**projects/migrate-marker-ledger-to-typed-query-ast-commands/learnings.mdis excluded by!projects/**projects/migrate-marker-ledger-to-typed-query-ast-commands/plan.mdis excluded by!projects/**projects/migrate-marker-ledger-to-typed-query-ast-commands/slices/sql-marker-ops-through-adapter/plan.mdis excluded by!projects/**projects/migrate-marker-ledger-to-typed-query-ast-commands/slices/sql-marker-ops-through-adapter/spec.mdis excluded by!projects/**projects/migrate-marker-ledger-to-typed-query-ast-commands/spec.mdis excluded by!projects/**projects/migrate-marker-ledger-to-typed-query-ast-commands/subagent-registry.mdis excluded by!projects/**
📒 Files selected for processing (39)
packages/2-sql/4-lanes/relational-core/package.jsonpackages/2-sql/4-lanes/relational-core/src/ast/types.tspackages/2-sql/4-lanes/relational-core/src/contract-free/ddl.tspackages/2-sql/4-lanes/relational-core/src/exports/contract-free.tspackages/2-sql/4-lanes/relational-core/test/ast/ddl.test.tspackages/2-sql/4-lanes/relational-core/test/contract-free/ddl-builder.test.tspackages/2-sql/4-lanes/relational-core/tsdown.config.tspackages/2-sql/5-runtime/README.mdpackages/2-sql/5-runtime/src/codecs/decoding.tspackages/2-sql/5-runtime/src/exports/index.tspackages/2-sql/5-runtime/src/middleware/lints.tspackages/2-sql/5-runtime/src/sql-marker.tspackages/2-sql/5-runtime/test/codec-decode-ctx.test.tspackages/2-sql/5-runtime/test/lints.test.tspackages/2-sql/5-runtime/test/utils.tspackages/2-sql/9-family/src/core/control-adapter.tspackages/2-sql/9-family/src/core/control-instance.tspackages/2-sql/9-family/src/core/control-tables.tspackages/2-sql/9-family/src/exports/control-adapter.tspackages/3-targets/3-targets/postgres/src/core/migrations/runner.tspackages/3-targets/3-targets/postgres/src/core/migrations/statement-builders.tspackages/3-targets/3-targets/postgres/src/exports/statement-builders.tspackages/3-targets/3-targets/postgres/test/migrations/statement-builders.test.tspackages/3-targets/3-targets/sqlite/src/core/migrations/runner.tspackages/3-targets/3-targets/sqlite/src/core/migrations/statement-builders.tspackages/3-targets/3-targets/sqlite/src/exports/statement-builders.tspackages/3-targets/6-adapters/postgres/src/core/control-adapter.tspackages/3-targets/6-adapters/postgres/src/core/sql-renderer.tspackages/3-targets/6-adapters/postgres/test/migrations/ddl-lowering.test.tspackages/3-targets/6-adapters/postgres/test/migrations/runner.errors.integration.test.tspackages/3-targets/6-adapters/sqlite/src/core/adapter.tspackages/3-targets/6-adapters/sqlite/src/core/control-adapter.tspackages/3-targets/6-adapters/sqlite/test/migrations/ddl-lowering.test.tspackages/3-targets/6-adapters/sqlite/test/migrations/runner.errors.test.tstest/integration/test/cli.db-verify.aggregate-schema.test.tstest/integration/test/cli.db-verify.e2e.test.tstest/integration/test/family.sign-database.test.tstest/integration/test/family.verify-database.basic.test.tstest/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
| 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' }, | ||
| }, | ||
| ], |
There was a problem hiding this comment.
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.
| 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([]); |
There was a problem hiding this comment.
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.
| 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).
| 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(' '); | ||
| } |
There was a problem hiding this comment.
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.
| 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.
| 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(' '); | ||
| } |
There was a problem hiding this comment.
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.
| 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'; | ||
| } | ||
| } |
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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'; |
There was a problem hiding this comment.
I don't think the AST should be encoding possible column types. Those are dialect/target-specific
There was a problem hiding this comment.
We should not add to this bloated file, especially since we're defining a whole new subset of the AST. Split it out.
| export type ColumnDefault = | ||
| | { readonly kind: 'literal'; readonly value: string } | ||
| | { readonly kind: 'now' } | ||
| | { readonly kind: 'empty-collection' }; |
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
Is this generic, or dialect-specific?
| table: { schema?: string; name: string }, | ||
| columns: readonly CreateTableColumn[], |
There was a problem hiding this comment.
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[]; |
There was a problem hiding this comment.
Don't call this "Asts". It's a query. ensureControlTableQuery() eg
| typeof (value as { lower: unknown }).lower === 'function' | ||
| typeof (value as { lower: unknown }).lower === 'function' && | ||
| 'ensureControlTableAsts' in value && | ||
| typeof (value as { ensureControlTableAsts: unknown }).ensureControlTableAsts === 'function' |
There was a problem hiding this comment.
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[] { | |||
There was a problem hiding this comment.
Again, don't name query methods "asts"
| } from '@prisma-next/sql-relational-core/contract-free'; | ||
|
|
||
| /** | ||
| * Builds the canonical contract-marker table AST. |
| 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'; | ||
| } | ||
| } |
| function renderColumnDefault(def: ColumnDefault): string { | ||
| switch (def.kind) { | ||
| case 'literal': | ||
| return def.value; | ||
| case 'now': | ||
| return 'now()'; | ||
| case 'empty-collection': | ||
| return "'{}'"; | ||
| } | ||
| } |
|
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 The project has been respec'd around "DDL in the SQL query AST" with marker/ledger as the first consumer. Slice 1 ( |
…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]>
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
AnyQueryAstkind. New frozenCreateSchemaAst/CreateTableAstnodes in@prisma-next/sql-relational-core, members ofAnyQueryAst/queryAstKinds, with virtualcollectParamRefs()/rewrite/toQueryAst. No runtime throw on DDL anywhere — every exhaustiveAnyQueryAstconsumer handles it (renderers render it;lints/decodingopt it out likeraw-sql). This anticipates runtime DDL as a valid capability; only the user-facing authoring surface is deferred.@prisma-next/sql-relational-core/contract-free):createSchema/createTable/col/lit/now/emptyCollectionconstruct DDL from plain identifiers + dialect-neutral descriptors, with no contract/codec/branding — the construction layer the control plane needs (the contract-boundsql()builder is unusable there).text[]/jsonb/timestamptz/now()/'{}'vsTEXT/INTEGER PRIMARY KEY AUTOINCREMENT/datetime('now')/'[]'). Lowered output is pinned byte-equal to the previous bootstrap constants.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 thefamily-sqlsign path route uniformly viaensureControlTableAsts()→lower()→driver.query, with no target branching.target-postgres,target-sqlite, andsql-runtime.Bugs fixed in passing
family-sqlsignpath ran PG-flavored DDL unconditionally — broken for SQLite. Routing through the target's control adapter corrects it. (Postgressignnow also ensures theledgertable — accepted, idempotentIF NOT EXISTS, consistent with the runners.)sql-runtimelints.tswould have thrown on a DDL AST (latent), anddecoding.tsaccessed a non-existent.returning— both fixed to handle DDL without throwing.Test plan
pnpm typecheck— 135/135pnpm lint:deps— cleanpnpm fixtures:check— clean (byte-identical routing, no golden drift)lints/decodingruntime pathssrctree@prisma/dev"Connection terminated" flakiness under parallel load — every bootstrap/sign file passes in isolation)Summary by CodeRabbit
New Features
createSchema(),createTable(), and column helpers (col(),lit(),now(),emptyCollection()) for constructing schema and table AST nodes.Refactor