Repository navigation
feat(sqlite): support migrations - #386
Conversation
|
Warning Rate limit exceeded
To keep reviews running without waiting, you can enable usage-based add-on for your organization. This allows additional reviews beyond the hourly cap. Account admins can enable it under billing. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (20)
📝 WalkthroughWalkthroughIntroduces a full SQLite target implementation and demo: target/adapter/runtime/migrations/planner/runner, refactors marker-reading into the SqlControlAdapter API, adds a Prisma Next SQLite example app, and adds extensive unit and E2E tests for migrations and adapter behavior. Changes
Sequence Diagram(s)sequenceDiagram
actor User
participant Planner as Migration Planner
participant Verifier as Schema Verifier
participant Strategy as Strategy Engine
participant CallFactory as Call Factory
participant Renderer as TypeScript Renderer
User->>Planner: plan(contract, schema, policy)
Planner->>Verifier: verifySqlSchema(contract, schema)
Verifier-->>Planner: SchemaIssue[]
Planner->>Strategy: apply strategies to issues
Strategy->>CallFactory: map issues -> SqliteOpFactoryCall[]
CallFactory-->>Strategy: calls
Strategy-->>Planner: aggregated calls
Planner->>Renderer: renderCallsToTypeScript(calls, meta)
Renderer-->>Planner: TypeScriptRenderableSqliteMigration
Planner-->>User: plan result
sequenceDiagram
actor Operator
participant Runner as Migration Runner
participant Tx as Transaction Manager
participant Driver as DB Driver
participant Verifier as Schema Verifier
participant Ctrl as Control Tables
Operator->>Runner: execute(migration)
Runner->>Tx: BEGIN EXCLUSIVE
loop ops
Runner->>Driver: precheck SQL
alt precheck fails
Driver-->>Runner: fail -> Runner aborts
else
Runner->>Driver: execute SQL
Runner->>Driver: postcheck SQL
alt postcheck fails
Driver-->>Runner: failure -> Runner aborts
end
end
end
alt all ops succeed
Runner->>Verifier: verifySqlSchema(database)
Verifier-->>Runner: verified
Runner->>Ctrl: upsert marker, insert ledger
Runner->>Tx: COMMIT
else any failure
Runner->>Tx: ROLLBACK
end
Runner-->>Operator: result (ok/failure)
Estimated code review effort🎯 5 (Critical) | ⏱️ ~120 minutes Possibly related PRs
Suggested reviewers
Poem
✨ Finishing Touches🧪 Generate unit tests (beta)
|
@prisma-next/mongo-runtime
@prisma-next/family-mongo
@prisma-next/sql-runtime
@prisma-next/family-sql
@prisma-next/middleware-telemetry
@prisma-next/mongo
@prisma-next/extension-paradedb
@prisma-next/extension-pgvector
@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/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: |
There was a problem hiding this comment.
Actionable comments posted: 18
🧹 Nitpick comments (28)
examples/prisma-next-demo-sqlite/test/contract-authoring.test.ts (2)
19-25: Consolidate capability checks into a singletoMatchObject.Four sequential
expect(...).toBe(...)calls on the samesqlCapsobject are exactly the case the guidelines call out for combining. A single matcher also fails more legibly when several flags drift at once. Bonus: the cast goes away if you pullcapabilities.sqlout and assert withtoMatchObject, sincetoMatchObjectdoesn’t require the source object to be narrowed.♻️ Proposed fix
- it('declares SQLite capabilities (returning, jsonAgg, no enums, no lateral)', () => { - const sqlCaps = contract.capabilities['sql'] as Record<string, boolean> | undefined; - expect(sqlCaps?.['returning']).toBe(true); - expect(sqlCaps?.['jsonAgg']).toBe(true); - expect(sqlCaps?.['lateral']).toBe(false); - expect(sqlCaps?.['enums']).toBe(false); - }); + it('declares SQLite capabilities (returning, jsonAgg, no enums, no lateral)', () => { + expect(contract.capabilities['sql']).toMatchObject({ + returning: true, + jsonAgg: true, + lateral: false, + enums: false, + }); + });As per coding guidelines: "Prefer object matchers (toMatchObject) over multiple individual expect().toBe() calls when checking 2 or more related values in tests".
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@examples/prisma-next-demo-sqlite/test/contract-authoring.test.ts` around lines 19 - 25, Replace the four individual assertions on sqlCaps with a single object matcher: pull the value into a local (e.g., const sqlCaps = contract.capabilities.sql) and assert with expect(sqlCaps).toMatchObject({ returning: true, jsonAgg: true, lateral: false, enums: false }); this removes the explicit cast and consolidates the related checks into one clearer, failing-legible assertion in the test that currently references sqlCaps and contract.capabilities['sql'].
5-12: ReplacetoHaveProperty+ individual checks with a single object matcher.The first test compares three related properties between two columns; per guidelines this should be one
toMatchObjectagainst an extracted subset of the target column.♻️ Proposed fix
- it('keeps Post.userId storage aligned with User.id', () => { - const userIdColumn = contract.storage.tables.post.columns.userId; - const userIdTargetColumn = contract.storage.tables.user.columns.id; - - expect(userIdColumn.codecId).toBe(userIdTargetColumn.codecId); - expect(userIdColumn.nativeType).toBe(userIdTargetColumn.nativeType); - expect(userIdColumn).toHaveProperty('typeParams', userIdTargetColumn['typeParams']); - }); + it('keeps Post.userId storage aligned with User.id', () => { + const userIdColumn = contract.storage.tables.post.columns.userId; + const { codecId, nativeType, typeParams } = contract.storage.tables.user.columns.id; + + expect(userIdColumn).toMatchObject({ codecId, nativeType, typeParams }); + });As per coding guidelines: "Prefer object comparison using toEqual or toMatchObject for assertions on objects, rather than property-by-property checks with toHaveProperty or individual property assertions".
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@examples/prisma-next-demo-sqlite/test/contract-authoring.test.ts` around lines 5 - 12, Replace the three separate assertions that compare properties on userIdColumn to userIdTargetColumn with a single object matcher: construct a small object using the three target values (codecId, nativeType, typeParams) from userIdTargetColumn and assert expect(userIdColumn).toMatchObject(...) so the test in the it block that references contract.storage.tables.post.columns.userId and contract.storage.tables.user.columns.id is a single, clearer assertion.examples/prisma-next-demo-sqlite/src/orm-client/delete-user.ts (1)
6-15: Optional: extract theUserIdtype andtoUserIdhelper to a shared module.This
type UserId = DefaultModelRow<Contract, 'User'>['id']plus thetoUserId(value: string): UserIdhelper are duplicated verbatim infind-user-by-id.ts(and likely elsewhere). Consider hoisting them into a shared module underorm-client/(e.g.,ids.ts) so the cast site is defined once.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@examples/prisma-next-demo-sqlite/src/orm-client/delete-user.ts` around lines 6 - 15, Extract the duplicated type alias and helper into a shared module: move "type UserId = DefaultModelRow<Contract, 'User'>['id']" and "function toUserId(value: string): UserId" into a new exported file (e.g., ids.ts) and export both UserId and toUserId; then replace the local declarations in ormClientDeleteUser (and find-user-by-id.ts) with imports of UserId and toUserId and adjust calls in ormClientDeleteUser to keep using toUserId(id) and the UserId type where needed.examples/prisma-next-demo-sqlite/scripts/drop-db.ts (1)
5-5: Optional: centralize the SQLite path default.The fallback
'./demo.db'is duplicated here and inprisma-next.config.ts. If the demo standardizes vialoadAppConfig()(used byscripts/seed.ts), consider sourcing the path from there to avoid drift if the default ever changes.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@examples/prisma-next-demo-sqlite/scripts/drop-db.ts` at line 5, The default SQLite path './demo.db' is duplicated; change the drop script to read the path from the shared config loader instead of hardcoding: replace use of process.env['SQLITE_PATH'] ?? './demo.db' in the drop-db script with the centralized value from loadAppConfig() (the same source used by scripts/seed.ts) or a single exported constant in prisma-next.config.ts so databasePath is derived from that shared source (refer to loadAppConfig and the existing SQLITE_PATH handling) to avoid drifting defaults.examples/prisma-next-demo-sqlite/src/main-no-emit.ts (1)
30-72:process.exit(1)inside thetryblock skips thefinallycleanup.The runtime is opened at line 32 before any argument validation, and the per-command usage checks call
process.exit(1)directly inside thetryblock.process.exitterminates synchronously, soawait runtime.close()in thefinallyblock will not run for usage errors (user/postsinvocations without arguments, and the unknown-command branch). For a SQLite demo this is cosmetic, but it leaves the DB connection un-closed.Consider validating the command/args first and only then connecting the runtime, or replacing the early
process.exitcalls with athrowso thecatch/finallychain handles cleanup uniformly.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@examples/prisma-next-demo-sqlite/src/main-no-emit.ts` around lines 30 - 72, The main issue is that process.exit(1) is called inside the try block which prevents the finally block from running and runtime.close() from executing; update main() to validate cmd and required args before calling getRuntime(databasePath) (i.e., move argument/command validation above the getRuntime call) OR replace the early process.exit(1) usages in the command branches with throwing an Error (e.g., throw new Error('Usage: ...')) so the catch/finally path runs and runtime.close() is always awaited; refer to the main function, the runtime variable, and the existing process.exit(1) calls to locate where to apply the change.examples/prisma-next-demo-sqlite/src/main.ts (1)
73-73: Numeric arg parsing silently passesNaNdownstream — inconsistent withmain-no-emit.ts.
Number.parseInt('abc', 10)returnsNaN, and there's noNumber.isFinite/positivity guard here, so any non-numeric[limit]/[postsPerUser]/[minUsers]argument silently becomesNaNand is forwarded to the ORM/query helpers.main-no-emit.tsalready validates withNumber.isFinite(parsedLimit) && parsedLimit > 0and falls back to a default — please align both CLIs to the same parsing helper so users get a deterministic default instead of an opaque downstream error.Proposed parsing helper
+function parsePositiveIntArg(raw: string | undefined, fallback: number): number { + if (!raw) return fallback; + const n = Number.parseInt(raw, 10); + return Number.isFinite(n) && n > 0 ? n : fallback; +} @@ - const limit = args[0] ? Number.parseInt(args[0], 10) : 10; + const limit = parsePositiveIntArg(args[0], 10);Also applies to: 96-96, 101-101, 120-120, 132-133, 149-149, 156-156, 161-161, 166-166, 212-212, 222-222
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@examples/prisma-next-demo-sqlite/src/main.ts` at line 73, The CLI currently assigns numeric args like limit, postsPerUser and minUsers using Number.parseInt which yields NaN for non-numeric input; create/introduce a small helper (e.g., parsePositiveInt or ensurePositiveInt) that does Number.parseInt(..., 10), then guards with Number.isFinite(parsed) && parsed > 0 and returns the parsed value or a supplied default, and replace all inline parses (the const limit = ..., and the other occurrences for postsPerUser/minUsers listed in the review) with calls to this helper so the CLIs behave like main-no-emit.ts and fall back to deterministic defaults instead of passing NaN downstream.examples/prisma-next-demo-sqlite/src/orm-client/get-dashboard-users.ts (1)
13-18: Replacenot(posts.none(...))withposts.some(...).The double negation expresses "user has at least one post whose title matches", which is exactly
posts.some(...)— and that form is already used byUserCollection.withPostTitleincollections.ts, so aligning here improves consistency and readability.♻️ Proposed simplification
return await db.User.where((user) => and( or(user.kind.eq('admin'), user.email.like(`%@${emailDomain}`)), - not(user.posts.none((post) => post.title.like(`%${postTitleTerm}%`))), + user.posts.some((post) => post.title.like(`%${postTitleTerm}%`)), ), )You can then drop
notfrom the imports on line 1 if it becomes unused.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@examples/prisma-next-demo-sqlite/src/orm-client/get-dashboard-users.ts` around lines 13 - 18, Replace the double-negation pattern not(user.posts.none(...)) used inside db.User.where with the direct positive form user.posts.some((post) => post.title.like(`%${postTitleTerm}%`)) to express "has at least one matching post" (this aligns with UserCollection.withPostTitle); after making that change, remove the now-unused not import from the module's imports.examples/prisma-next-demo-sqlite/src/orm-client/create-user-with-address.ts (1)
33-39: Consider extractingtoUserId/toUserCreatedAtto a shared module.These two helpers are duplicated verbatim in
upsert-user.ts. Pulling them into something likeorm-client/user-coercions.ts(or co-locating them with the row type) avoids drift if the branding/encoding ever changes.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@examples/prisma-next-demo-sqlite/src/orm-client/create-user-with-address.ts` around lines 33 - 39, Extract the duplicated helpers to a shared module: create a new module (e.g., orm-client/user-coercions.ts) that exports toUserId and toUserCreatedAt and update both create-user-with-address.ts and upsert-user.ts to import them; ensure the exported helpers keep the same signatures and use the UserRow type (or re-export the type alongside if needed) so branding/encoding logic is centralized and both files reference the single implementation.examples/prisma-next-demo-sqlite/test/repositories.integration.test.ts (1)
169-174: Optional: collapsetoMatchObject+expect(user!.id).toBe(...)into a single matcher.Per coding guidelines, prefer object matchers over multiple individual
expect().toBe()calls when checking 2+ related values. The same pattern repeats at lines 184 and elsewhere; consider folding the id check into the sametoMatchObject.♻️ Proposed simplification
- expect(user).toMatchObject({ - email: '[email protected]', - kind: 'user', - }); - expect(user!.id).toBe(seededUserIds.member); + expect(user).toMatchObject({ + id: seededUserIds.member, + email: '[email protected]', + kind: 'user', + });As per coding guidelines: "Prefer object matchers (toMatchObject) over multiple individual expect().toBe() calls when checking 2 or more related values in tests".
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@examples/prisma-next-demo-sqlite/test/repositories.integration.test.ts` around lines 169 - 174, The test currently uses expect(user).toMatchObject(...) and then a separate expect(user!.id).toBe(seededUserIds.member); collapse those into a single object matcher by adding the id property to the toMatchObject call (e.g., include id: seededUserIds.member alongside email and kind) and remove the separate expect(user!.id) assertion; apply the same change to the similar assertions referenced (the other occurrences around the user checks such as the one at line ~184) so related fields are asserted together via toMatchObject.packages/3-targets/3-targets/sqlite/src/exports/codec-types.ts (1)
1-6: Prefer direct type re-export over local alias.
export type CodecTypes = CoreCodecTypesintroduces an alias rather than a plain re-export. Per the guideline, files insrc/exports/should re-export from../core/...without adding logic. A direct re-export is simpler and avoids the indirection.♻️ Proposed simplification
-import type { CodecTypes as CoreCodecTypes, JsonValue } from '../core/codecs'; - -export type CodecTypes = CoreCodecTypes; - -export type { JsonValue }; -export { dataTypes } from '../core/codecs'; +export { dataTypes, type CodecTypes, type JsonValue } from '../core/codecs';As per coding guidelines: "Re-export files in
src/exports/(adapter.ts, codec-types.ts, types.ts) must re-export from core (../core/...) without adding additional logic".🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-targets/3-targets/sqlite/src/exports/codec-types.ts` around lines 1 - 6, Replace the local alias export "export type CodecTypes = CoreCodecTypes" with a direct re-export from the core module: remove the import alias and instead re-export the types directly (e.g., export type { CodecTypes, JsonValue } from '../core/codecs'), and keep the existing value re-export "export { dataTypes } from '../core/codecs'"; this removes the indirection and conforms to the src/exports/ re-export guideline.packages/2-sql/9-family/src/core/control-instance.ts (1)
302-310: Confirm intent:getControlAdapter()re-creates the adapter on every call.Each invocation calls
adapter.create(stack)and re-runs theisSqlControlAdapterguard. Within any single public method this happens once, but acrossverify/schemaVerify/sign/readMarker/introspectyou'll get a fresh adapter per call. Ifadapter.create()is intended to be cheap and stateless, this is fine; if it's expected to be created once per family instance (the AI summary phrases it as "instantiates/returns the adapter once"), consider memoizing inside the closure.♻️ Optional memoized variant
- const getControlAdapter = () => { - const controlAdapter = adapter.create(stack); - if (!isSqlControlAdapter(controlAdapter)) { - throw new Error( - 'Adapter does not implement SqlControlAdapter (missing introspect or readMarker)', - ); - } - return controlAdapter; - }; + let cachedControlAdapter: SqlControlAdapter<string> | undefined; + const getControlAdapter = (): SqlControlAdapter<string> => { + if (cachedControlAdapter) return cachedControlAdapter; + const controlAdapter = adapter.create(stack); + if (!isSqlControlAdapter(controlAdapter)) { + throw new Error( + 'Adapter does not implement SqlControlAdapter (missing introspect or readMarker)', + ); + } + cachedControlAdapter = controlAdapter; + return cachedControlAdapter; + };🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/2-sql/9-family/src/core/control-instance.ts` around lines 302 - 310, The getControlAdapter() helper currently calls adapter.create(stack) and runs isSqlControlAdapter(...) on every invocation, re-instantiating the adapter across calls like verify/schemaVerify/sign/readMarker/introspect; if adapter.create() should be created once per family instance, change getControlAdapter to memoize the created controlAdapter inside the closure (store a local variable like cachedControlAdapter), create it only if not set, run the isSqlControlAdapter guard once when creating, and return the cached instance thereafter; keep the same error behavior (throw if guard fails) and reference getControlAdapter, adapter.create, and isSqlControlAdapter when making the change.packages/3-targets/6-adapters/sqlite/test/migrations/runner.errors.test.ts (1)
301-306: Inconsistent failure handling pattern.Other tests in this file use
result.assertNotOk()(e.g., lines 51-52, 72-73, 114-115). For consistency and clearer assertion semantics, use the same pattern here instead of theif (!result.ok)guard.♻️ Proposed change
- expect(result.ok).toBe(false); - if (!result.ok) { - expect(result.failure.code).toBe('POLICY_VIOLATION'); - expect(result.failure.summary).toMatch(/destructive/i); - expect(result.failure.why).toMatch(/additive/i); - } + expect(result.ok).toBe(false); + const failure = result.assertNotOk(); + expect(failure.code).toBe('POLICY_VIOLATION'); + expect(failure.summary).toMatch(/destructive/i); + expect(failure.why).toMatch(/additive/i);🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-targets/6-adapters/sqlite/test/migrations/runner.errors.test.ts` around lines 301 - 306, Replace the manual truthy check and guarded assertions with the file's standard failure assertion: call result.assertNotOk() instead of expect(result.ok).toBe(false) and remove the surrounding if (!result.ok) guard, then follow immediately with the existing assertions on result.failure.code, result.failure.summary, and result.failure.why (e.g., result.assertNotOk(); expect(result.failure.code).toBe('POLICY_VIOLATION'); expect(result.failure.summary).toMatch(/destructive/i); expect(result.failure.why).toMatch(/additive/i);) so the test matches the other patterns in this file.packages/3-targets/6-adapters/sqlite/test/control-adapter.test.ts (1)
25-202: Move driverclose()intoafterEachso failed assertions don't leak the in-memory DB.Every test in this file ends with
await driver.close()after a series ofexpect(...)calls. If any earlier assertion throws, close is skipped — same anti-pattern asrunner-integration.test.ts. Lifting cleanup toafterEachalso lets you drop the explicit close from each test body and tightens the suite to match the structure already used inrunner.basic.test.ts.♻️ Proposed cleanup hook
-import { describe, expect, it } from 'vitest'; +import { afterEach, describe, expect, it } from 'vitest'; import { SqliteControlAdapter } from '../src/core/control-adapter'; @@ describe('SqliteControlAdapter.introspect', () => { + let activeDriver: ReturnType<typeof createMemoryDriver> | undefined; + + afterEach(async () => { + await activeDriver?.close(); + activeDriver = undefined; + }); + it('introspects empty database', async () => { - const driver = createMemoryDriver(); + const driver = createMemoryDriver(); + activeDriver = driver; ... - await driver.close(); });(Apply across each
itblock in the file.)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-targets/6-adapters/sqlite/test/control-adapter.test.ts` around lines 25 - 202, Tests currently call await driver.close() at the end of each it block which can leak the in-memory DB if an assertion fails; instead declare a mutable driver variable in the describe scope, call createMemoryDriver() inside each it (or in a beforeEach) and add an afterEach hook that awaits driver?.close(); remove the explicit await driver.close() calls from all tests (those creating driver via createMemoryDriver and using SqliteControlAdapter and parseSqliteDefault/normalizeSqliteNativeType) so cleanup always runs even on failed assertions.packages/3-targets/6-adapters/sqlite/test/migrations/runner-integration.test.ts (1)
183-352: UseafterEachfor driver cleanup so the DB is closed even on assertion failure.
await driver.close()is the last statement in each round-trip test. When any priorexpect(...)throws, the close call is skipped and the in-memoryDatabaseSynchandle leaks for the remainder of the test run. The siblingrunner.basic.test.tsalready uses anafterEach(() => testDb?.cleanup())pattern — applying the same here makes failures non-leaky and stops one bad assertion from masking later issues (e.g., file-handle exhaustion if this harness is later reused with file-backed SQLite).♻️ Proposed cleanup hook
+import { afterEach, describe, expect, it } from 'vitest'; -import { describe, expect, it } from 'vitest'; import { SqliteControlAdapter } from '../../src/exports/control'; @@ describe('SQLite planner + introspection round-trip', () => { + let activeDriver: ReturnType<typeof createMemoryDriver> | undefined; + + afterEach(async () => { + await activeDriver?.close(); + activeDriver = undefined; + }); + it('executes planned DDL and verifies via introspection', async () => { - const driver = createMemoryDriver(); + const driver = createMemoryDriver(); + activeDriver = driver; ... - await driver.close(); });(Apply the same to the AUTOINCREMENT and FK tests.)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-targets/6-adapters/sqlite/test/migrations/runner-integration.test.ts` around lines 183 - 352, Tests create a local in-memory driver (const driver = createMemoryDriver()) and call await driver.close() at the end of each test, but a thrown assertion will skip that cleanup; fix by promoting the per-test driver to a shared test-scoped variable (e.g. let testDriver: ReturnType<typeof createMemoryDriver> | undefined), assign testDriver = createMemoryDriver() at the start of each it block (replace local const driver), and add an afterEach(async () => { if (testDriver) { await testDriver.close(); testDriver = undefined; } }) so the DB is always closed even when an assertion fails; update uses of driver in the tests to reference testDriver.packages/3-targets/3-targets/sqlite/src/core/control-target.ts (1)
36-38: Avoid the type cast — fix the return type ofcreateSqliteMigrationRunnerinstead.
createRunner(family) { return createSqliteMigrationRunner(family) as MigrationRunner<'sql', 'sqlite'>; }masks a type-surface mismatch. Per coding guidelines, "Minimize type casts and prefer explicit types instead". IfcreateSqliteMigrationRunneris intended to produce aMigrationRunner<'sql', 'sqlite'>, declare its return type that way at the source so the cast becomes unnecessary. The samecreateRunnerdefined on line 56-58 doesn't need the cast — that asymmetry suggests the type can be tightened upstream and the cast removed here.As per coding guidelines: "Minimize type casts and prefer explicit types instead; use
as unknown as SomeOtherTypeonly as a last resort with accompanying comments explaining necessity".🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-targets/3-targets/sqlite/src/core/control-target.ts` around lines 36 - 38, The code is masking a type mismatch by casting the result of createSqliteMigrationRunner to MigrationRunner<'sql','sqlite'> inside createRunner; instead, update the signature of createSqliteMigrationRunner to explicitly return MigrationRunner<'sql','sqlite'> (or the correct generic) so the cast is unnecessary, then remove the "as MigrationRunner<'sql', 'sqlite'>" from createRunner to match the other createRunner implementation and eliminate the unsafe type assertion.packages/3-targets/3-targets/sqlite/src/core/migrations/operations/columns.ts (1)
15-15: Standardize operation ID prefixes across additive and destructive operations.The ID prefix scheme is inconsistent across all operation types:
addColumnandaddIndexuse noun prefixes (column.*,index.*) whiledropColumnanddropIndexuse verb prefixes (dropColumn.*,dropIndex.*). This pattern repeats for tables, indexes, and constraints. Since tests use.startsWith('table.')to filter operations by type, code attempting to group all column operations via.startsWith('column.')will miss drops. Adopt a consistent scheme across both targets—eithercolumn.add.*/column.drop.*, oraddColumn.*/dropColumn.*—and apply it uniformly to tables, indexes, and constraints.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-targets/3-targets/sqlite/src/core/migrations/operations/columns.ts` at line 15, Operation ID prefixes are inconsistent: some ops use noun prefixes like the id template in columns.ts (id: `column.${tableName}.${column.name}` used by addColumn/addIndex) while dropColumn/dropIndex use verb prefixes, which breaks filters that expect .startsWith('table.') etc.; pick one consistent prefix scheme (e.g., use noun-based grouping like column.add.*, column.drop.* or verb-based like addColumn.*, dropColumn.*) and update all operation id generators across addColumn, addIndex, dropColumn, dropIndex and the analogous table/index/constraint operation id templates so they follow the chosen pattern uniformly (locate and change the id templates such as the one in columns.ts and the corresponding id strings in table and constraint migration operation files).packages/3-targets/3-targets/sqlite/src/core/migrations/runner.ts (1)
271-274: Redundantif (!row)guard.After confirming
result.rows.length === 0returns null at Line 268-270,result.rows[0]cannot be undefined unlessnoUncheckedIndexedAccessis enabled. The guard at Line 272-274 is dead — thenullit returns also disagrees with the preceding length check (rows is non-empty here). If keeping it fornoUncheckedIndexedAccessstrictness, prefer a non-null assertion to make intent explicit. As per coding guidelines, prefer assertions over defensive checks when data is guaranteed to be valid.♻️ Proposed cleanup
if (result.rows.length === 0) { return null; } - const row = result.rows[0]; - if (!row) { - return null; - } + const row = result.rows[0]!;🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-targets/3-targets/sqlite/src/core/migrations/runner.ts` around lines 271 - 274, The guard "if (!row) return null" after assigning "const row = result.rows[0]" is redundant because you already return null when result.rows.length === 0; remove the dead defensive check or replace it with a non-null assertion to express intent; update the code in the migrations runner where "result.rows" is read (the assignment to "row" in runner.ts) so the code either omits the if-block entirely or uses a non-null assertion on "result.rows[0]" to satisfy noUncheckedIndexedAccess strictness.packages/3-targets/3-targets/sqlite/src/core/migrations/planner-ddl-builders.ts (2)
75-92:renderDefaultLiteralacceptsunknownbut assumesstring-coercible values.If
valueisundefined, it falls through toJSON.stringify(undefined)(returnsundefined), andescapeLiteralis called with a non-string. Number serialization forNaN/Infinityproduces invalid SQL ('NaN','Infinity'). These are unlikely from a normalized contract, but worth considering: either narrow the input type to literal-default's actual value type, or reject these explicitly. Defensive throws here aid debugging during contract authoring.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-targets/3-targets/sqlite/src/core/migrations/planner-ddl-builders.ts` around lines 75 - 92, renderDefaultLiteral currently accepts unknown and assumes string-coercible values; add explicit guards to reject unsupported inputs and avoid passing non-strings to escapeLiteral by (1) throwing if value === undefined, (2) for numbers/bigints use Number.isFinite(value) (or BigInt allowed) and throw for NaN/Infinity, (3) ensure only strings are passed to escapeLiteral (convert Date via toISOString but otherwise throw for non-string objects instead of JSON.stringify), and (4) keep NULL/boolean handling; implement these checks inside renderDefaultLiteral so errors surface early and reference this function and escapeLiteral when making the changes.
32-38: Default-expression safety check rejects legitimatenow()recursively only by exact match.The safety check rejects expressions containing semicolons,
--,/*, or aSELECTkeyword. Two corners worth noting:
- The
\bSELECT\bcheck is case-insensitive (good) but will also reject perfectly valid PSL function defaults whose names happen to containSELECT— none today, but worth aware of.- Common safe SQLite scalar functions like
current_timestamp,current_date, orrandom()flow through the bareassertSafeDefaultExpressionand then becomeDEFAULT (current_timestamp). SQLite parses this fine, but verify that the surrounding parentheses are intentional (some adapters are stricter and want bare keywords). Thenow()special case at Line 68 is already wrapped, so the patterns here are mainly forfunction-kind defaults beyondnow()/autoincrement().No fix required, but please confirm the supported function-default vocabulary is documented somewhere.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-targets/3-targets/sqlite/src/core/migrations/planner-ddl-builders.ts` around lines 32 - 38, The safety check in assertSafeDefaultExpression rejects expressions with semicolons, comment tokens, or a SELECT keyword and has a special-case handling for now() elsewhere; update the repo docs (or add a short note in the SQLite adapter README and/or the file containing assertSafeDefaultExpression and the now() special-case handler) to explicitly list supported safe function defaults (e.g., current_timestamp, current_date, random(), now() special-case, autoincrement() behavior) and mention that DEFAULT(...) parentheses are used by this builder; reference the assertSafeDefaultExpression function and the now() handling code when adding the documentation so reviewers can verify the supported vocabulary and parsing expectations.test/e2e/framework/test/sqlite/migrations/harness.ts (2)
1-4: Usepatheinstead ofnode:path.Per repo guideline “Use
patheinstead ofnode:pathfor path manipulation in TypeScript files” (and prior learnings from PRs#234and#191), preferpathefor cross-platform consistency, even in test harnesses that read fixtures from disk.♻️ Proposed fix
import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; -import { join } from 'node:path'; +import { join } from 'pathe'; import { DatabaseSync } from 'node:sqlite';As per coding guidelines: “Use
patheinstead ofnode:pathfor path manipulation in TypeScript files.patheprovides consistent behavior across Windows/macOS/Linux…”.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/e2e/framework/test/sqlite/migrations/harness.ts` around lines 1 - 4, Replace usage of node:path with pathe: update the import that currently pulls join from 'node:path' to import join from 'pathe' (keeping mkdtempSync, rmSync from 'node:fs', tmpdir from 'node:os', and DatabaseSync from 'node:sqlite' unchanged); ensure any other path manipulation in this file that uses join continues to work with pathe’s join function for cross-platform consistency (symbols to locate: join, mkdtempSync, rmSync, tmpdir, DatabaseSync).
54-81:createTestDbswallows close errors and may leak temp dirs.Two minor robustness concerns in the harness lifecycle:
- Line 73-77:
try { db.close() } catch { /* already closed */ }swallows real errors (e.g., busy connection during cleanup); a test could leave a corrupted DB and silently pass cleanup.- If
mkdtempSyncsucceeds but thenew DatabaseSync(...)constructor throws, the temp directory is never removed (no try/catch around the constructor). Wrap construction so cleanup runs unconditionally.♻️ Suggested hardening
function createTestDb() { const dir = mkdtempSync(join(tmpdir(), 'prisma-sqlite-mig-e2e-')); - const db = new DatabaseSync(join(dir, 'test.db')); - db.exec('PRAGMA foreign_keys = ON'); + let db: DatabaseSync; + try { + db = new DatabaseSync(join(dir, 'test.db')); + db.exec('PRAGMA foreign_keys = ON'); + } catch (err) { + rmSync(dir, { recursive: true, force: true }); + throw err; + }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/e2e/framework/test/sqlite/migrations/harness.ts` around lines 54 - 81, The cleanup in createTestDb is unsafe: currently mkdtempSync and new DatabaseSync(...) can leave the temp dir if the constructor throws, and the cleanup() swallows all errors from db.close() which can hide real problems; fix by creating the temp dir then wrapping DatabaseSync construction in a try/catch/finally so the directory is removed if construction fails, and in cleanup() call db.close() but let/propagate or at least log non-expected errors instead of silently swallowing them (e.g., catch only known "already closed" cases), updating the cleanup and driver.close implementations to surface or log close errors; refer to createTestDb, cleanup, driver.close, db.close, mkdtempSync and new DatabaseSync to locate and change the code.test/e2e/framework/test/sqlite/migrations/fk-preservation.test.ts (1)
70-76: Use a stricter rejection matcher for FK / unique violation assertions.
rejects.toThrow()with no argument passes for any rejection — including assertion errors from elsewhere or transient driver-level errors unrelated to constraint violation. Tighten to a regex matching SQLite's actual error message (e.g.,/FOREIGN KEY constraint failed/ior/UNIQUE constraint failed/i) so the test fails if the rejection comes from a different cause.♻️ Example
- ).rejects.toThrow(); + ).rejects.toThrow(/FOREIGN KEY constraint failed/i);Also applies to: 131-137, 270-276, 325-332, 334-341
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/e2e/framework/test/sqlite/migrations/fk-preservation.test.ts` around lines 70 - 76, The current assertion uses .rejects.toThrow() which matches any rejection; update the driver.query assertions (the calls to driver.query that insert into "Post" and similar FK/unique-constraint tests) to use a stricter matcher such as .rejects.toThrow(/FOREIGN KEY constraint failed/i) for FK violations or .rejects.toThrow(/UNIQUE constraint failed/i) for unique violations so only constraint errors pass; ensure you replace the generic .rejects.toThrow() on the driver.query(...) promises (and the analogous assertions at the other mentioned spots) with the appropriate regex-based .toThrow matcher matching SQLite's error text.packages/3-targets/3-targets/sqlite/test/migrations/op-factory-call.test.ts (2)
51-53: PrefertoMatchObjectfor grouped metadata assertions.Several
itblocks issue 2–3 individualtoBecalls on related fields of the same object (factoryName/operationClass/label, orid/operationClass/sql). Per coding guidelines, prefer object matchers when checking 2+ related values.♻️ Example
- expect(call.factoryName).toBe('createTable'); - expect(call.operationClass).toBe('additive'); - expect(call.label).toBe('Create table user'); + expect(call).toMatchObject({ + factoryName: 'createTable', + operationClass: 'additive', + label: 'Create table user', + });As per coding guidelines: “Prefer object matchers (toMatchObject) over multiple individual expect().toBe() calls when checking 2 or more related values in tests”.
Also applies to: 127-128, 156-158, 177-179
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-targets/3-targets/sqlite/test/migrations/op-factory-call.test.ts` around lines 51 - 53, The tests in op-factory-call.test.ts use multiple related expect(...).toBe(...) assertions (e.g., expect(call.factoryName).toBe(...); expect(call.operationClass).toBe(...); expect(call.label).toBe(...))—replace these grouped checks with a single object matcher, e.g. use expect(call).toMatchObject({ factoryName: 'createTable', operationClass: 'additive', label: 'Create table user' }); do the same for the other grouped assertions that check id/operationClass/sql (and similar blocks) so each related set of fields is asserted with one expect(...).toMatchObject({...}) call (locate the assertions referencing the local variable "call" or the variables asserting id/sql and update them accordingly).
254-273: HoistdataTransformto a static import at the top of the file. The dynamicawait import()is inconsistent with the rest of the test file's import pattern and obscures static analysis. Other tests in this file use static top-level imports, and the module is already imported statically elsewhere in the codebase without issues.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-targets/3-targets/sqlite/test/migrations/op-factory-call.test.ts` around lines 254 - 273, The test uses a dynamic import for dataTransform; replace the inline await import('../../src/core/migrations/operations/data-transform') with a static top-level import for dataTransform and remove the await import call inside the test (so the test references the already-imported dataTransform symbol directly), matching the file's other tests and keeping imports consistent.packages/3-targets/3-targets/sqlite/src/core/migrations/planner-produced-sqlite-migration.ts (1)
37-39:operationsgetter re-renders calls on every access.
renderOps(this.#calls)runs per access. If the runner or any inspector readsplan.operationsmultiple times (e.g., logging + execution + verification), each read pays the full render cost and produces fresh objects, breaking referential equality. Consider memoizing.♻️ Proposed memoization
readonly `#calls`: readonly SqliteOpFactoryCall[]; readonly `#meta`: MigrationMeta; readonly `#destination`: SqliteMigrationDestinationInfo; + `#operationsCache`: readonly Op[] | undefined; @@ override get operations(): readonly Op[] { - return renderOps(this.#calls); + this.#operationsCache ??= renderOps(this.#calls); + return this.#operationsCache; }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-targets/3-targets/sqlite/src/core/migrations/planner-produced-sqlite-migration.ts` around lines 37 - 39, The operations getter currently calls renderOps(this.#calls) on every access which recomputes and returns new objects, breaking referential equality; fix by memoizing the rendered ops: add a private cache field (e.g., `#renderedOpsCache`) and a version/dirty flag, have the operations getter return the cached value if present, otherwise call renderOps(this.#calls), store the result in `#renderedOpsCache` and return it, and ensure every method that mutates this.#calls (invalidate where calls are appended/modified) clears or updates the cache so the next access re-renders.packages/3-targets/3-targets/sqlite/src/core/migrations/planner.ts (1)
92-97: UseifDefined()for the optionalprofileHashspread.Per project convention (
@prisma-next/utils/defined), conditional object spreads should go throughifDefined()instead of the inline... ? {…} : {}pattern. The same helper is already used in the SQLite control adapter.♻️ Proposed change
+import { ifDefined } from '@prisma-next/utils/defined'; @@ - const destination: SqliteMigrationDestinationInfo = { - storageHash: options.contract.storage.storageHash, - ...(options.contract.profileHash !== undefined - ? { profileHash: options.contract.profileHash } - : {}), - }; + const destination: SqliteMigrationDestinationInfo = { + storageHash: options.contract.storage.storageHash, + ...ifDefined('profileHash', options.contract.profileHash), + };As per coding guidelines: "Use
ifDefined()from@prisma-next/utils/definedfor conditional object spreads instead of inline conditional spread patterns."🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-targets/3-targets/sqlite/src/core/migrations/planner.ts` around lines 92 - 97, The object construction for destination uses an inline conditional spread for profileHash; replace that with the ifDefined() helper from `@prisma-next/utils/defined` so the optional profileHash is added via ifDefined(options.contract.profileHash, () => ({ profileHash: options.contract.profileHash })); update the import to include ifDefined and modify the destination creation (symbol: destination, type: SqliteMigrationDestinationInfo) to use ifDefined for options.contract.profileHash instead of the ternary spread.packages/3-targets/3-targets/sqlite/src/core/migrations/issue-planner.ts (1)
115-167: AdoptifDefined()for the inline conditional spreads in this file.The repo standardizes on
ifDefined('key', value)from@prisma-next/utils/definedfor all...(x ? { key: x } : {})patterns. This file has several:
issueConflict(line 119):...(location ? { location } : {})conflictForDisallowedCall(line 166): same patterntoColumnSpec(line 221):inlineAutoincrementPrimaryKeytoTableSpec(lines 240, 246–248, 252):name,primaryKey,onDelete,onUpdateMechanical swap; keeps the new SQLite planner consistent with the rest of the codebase (the SQLite control adapter already uses it).
As per coding guidelines: "Use
ifDefined()from@prisma-next/utils/definedfor conditional object spreads instead of inline conditional spread patterns."Also applies to: 221-252
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-targets/3-targets/sqlite/src/core/migrations/issue-planner.ts` around lines 115 - 167, Replace the inline conditional object spreads with the repo-standard ifDefined helper and import it from '@prisma-next/utils/defined'; specifically, in the object returned by the function that builds issueConflict (the return that currently uses ...(location ? { location } : {})), change that spread to ifDefined('location', location); in conflictForDisallowedCall replace ...(location ? { location } : {}) with ifDefined('location', location); in toColumnSpec replace the inlineAutoincrementPrimaryKey spread with ifDefined('inlineAutoincrementPrimaryKey', inlineAutoincrementPrimaryKey); and in toTableSpec replace the conditional spreads for name, primaryKey, onDelete and onUpdate with ifDefined('name', name), ifDefined('primaryKey', primaryKey), ifDefined('onDelete', onDelete) and ifDefined('onUpdate', onUpdate) respectively, and add the ifDefined import at the top of the file.packages/3-targets/3-targets/sqlite/src/core/migrations/planner-strategies.ts (1)
92-106: Drop the redundantenum_values_changed/!issue.tablechecks.
classifyIssuealready returnsnullfor bothenum_values_changed(line 71) and any issue without atable(line 72), so by the time control reaches lines 95–96 theclsguard on line 94 has filtered them out. The two extracontinues are dead code.♻️ Proposed simplification
for (const issue of issues) { const cls = classifyIssue(issue); if (!cls) continue; - if (issue.kind === 'enum_values_changed') continue; - if (!issue.table) continue; - const table = issue.table; + const table = issue.table!; const entry = byTable.get(table);🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-targets/3-targets/sqlite/src/core/migrations/planner-strategies.ts` around lines 92 - 106, The loop over issues performs redundant guards: remove the dead checks "if (issue.kind === 'enum_values_changed') continue;" and "if (!issue.table) continue;" because classifyIssue(issue) already returns null for those cases; keep the existing cls null-check (const cls = classifyIssue(issue); if (!cls) continue;), then proceed to get const table = issue.table, update/insert into byTable (entry.issues and entry.hasDestructive) and consumed.add(issue) as before; this simplifies the loop while preserving behavior in the function that contains classifyIssue, byTable, and consumed.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: 7787d3fe-36dc-41f0-ac96-aaea72d84870
⛔ Files ignored due to path filters (2)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yamltest/integration/test/sql-builder/fixtures/generated/contract.d.tsis excluded by!**/generated/**
📒 Files selected for processing (129)
examples/prisma-next-demo-sqlite/.gitignoreexamples/prisma-next-demo-sqlite/README.mdexamples/prisma-next-demo-sqlite/biome.jsoncexamples/prisma-next-demo-sqlite/package.jsonexamples/prisma-next-demo-sqlite/prisma-next.config.tsexamples/prisma-next-demo-sqlite/prisma/contract.tsexamples/prisma-next-demo-sqlite/scripts/drop-db.tsexamples/prisma-next-demo-sqlite/scripts/seed.tsexamples/prisma-next-demo-sqlite/src/app-config.tsexamples/prisma-next-demo-sqlite/src/main-no-emit.tsexamples/prisma-next-demo-sqlite/src/main.tsexamples/prisma-next-demo-sqlite/src/orm-client/aggregate-users.tsexamples/prisma-next-demo-sqlite/src/orm-client/client.tsexamples/prisma-next-demo-sqlite/src/orm-client/collections.tsexamples/prisma-next-demo-sqlite/src/orm-client/create-user-with-address.tsexamples/prisma-next-demo-sqlite/src/orm-client/create-user.tsexamples/prisma-next-demo-sqlite/src/orm-client/delete-user.tsexamples/prisma-next-demo-sqlite/src/orm-client/find-user-by-email.tsexamples/prisma-next-demo-sqlite/src/orm-client/find-user-by-id.tsexamples/prisma-next-demo-sqlite/src/orm-client/get-admin-users.tsexamples/prisma-next-demo-sqlite/src/orm-client/get-dashboard-users.tsexamples/prisma-next-demo-sqlite/src/orm-client/get-post-feed.tsexamples/prisma-next-demo-sqlite/src/orm-client/get-user-insights.tsexamples/prisma-next-demo-sqlite/src/orm-client/get-user-kind-breakdown.tsexamples/prisma-next-demo-sqlite/src/orm-client/get-user-posts.tsexamples/prisma-next-demo-sqlite/src/orm-client/get-users-backward-cursor.tsexamples/prisma-next-demo-sqlite/src/orm-client/get-users-by-id-cursor.tsexamples/prisma-next-demo-sqlite/src/orm-client/get-users.tsexamples/prisma-next-demo-sqlite/src/orm-client/update-user-email.tsexamples/prisma-next-demo-sqlite/src/orm-client/upsert-user.tsexamples/prisma-next-demo-sqlite/src/prisma-no-emit/context.tsexamples/prisma-next-demo-sqlite/src/prisma-no-emit/runtime.tsexamples/prisma-next-demo-sqlite/src/prisma/contract.d.tsexamples/prisma-next-demo-sqlite/src/prisma/contract.jsonexamples/prisma-next-demo-sqlite/src/prisma/db.tsexamples/prisma-next-demo-sqlite/src/queries/dml-operations.tsexamples/prisma-next-demo-sqlite/src/queries/get-user-by-id-no-emit.tsexamples/prisma-next-demo-sqlite/src/queries/get-user-by-id.tsexamples/prisma-next-demo-sqlite/src/queries/get-user-posts-no-emit.tsexamples/prisma-next-demo-sqlite/src/queries/get-user-posts.tsexamples/prisma-next-demo-sqlite/src/queries/get-users-no-emit.tsexamples/prisma-next-demo-sqlite/src/queries/get-users-with-posts-no-emit.tsexamples/prisma-next-demo-sqlite/src/queries/get-users.tsexamples/prisma-next-demo-sqlite/src/result-utils.tsexamples/prisma-next-demo-sqlite/test/contract-authoring.test.tsexamples/prisma-next-demo-sqlite/test/repositories.integration.test.tsexamples/prisma-next-demo-sqlite/test/runtime.offline.integration.test.tsexamples/prisma-next-demo-sqlite/test/utils/control-client.tsexamples/prisma-next-demo-sqlite/test/utils/sqlite-runtime.tsexamples/prisma-next-demo-sqlite/tsconfig.jsonexamples/prisma-next-demo-sqlite/vitest.config.tspackages/2-sql/9-family/README.mdpackages/2-sql/9-family/src/core/control-adapter.tspackages/2-sql/9-family/src/core/control-instance.tspackages/2-sql/9-family/src/core/migrations/types.tspackages/2-sql/9-family/src/core/verify.tspackages/2-sql/9-family/src/exports/verify.tspackages/3-targets/3-targets/postgres/src/core/migrations/runner.tspackages/3-targets/3-targets/sqlite/package.jsonpackages/3-targets/3-targets/sqlite/src/core/codec-ids.tspackages/3-targets/3-targets/sqlite/src/core/codecs.tspackages/3-targets/3-targets/sqlite/src/core/control-target.tspackages/3-targets/3-targets/sqlite/src/core/default-normalizer.tspackages/3-targets/3-targets/sqlite/src/core/descriptor-meta.tspackages/3-targets/3-targets/sqlite/src/core/migrations/issue-planner.tspackages/3-targets/3-targets/sqlite/src/core/migrations/op-factory-call.tspackages/3-targets/3-targets/sqlite/src/core/migrations/operations/columns.tspackages/3-targets/3-targets/sqlite/src/core/migrations/operations/data-transform.tspackages/3-targets/3-targets/sqlite/src/core/migrations/operations/indexes.tspackages/3-targets/3-targets/sqlite/src/core/migrations/operations/shared.tspackages/3-targets/3-targets/sqlite/src/core/migrations/operations/tables.tspackages/3-targets/3-targets/sqlite/src/core/migrations/planner-ddl-builders.tspackages/3-targets/3-targets/sqlite/src/core/migrations/planner-produced-sqlite-migration.tspackages/3-targets/3-targets/sqlite/src/core/migrations/planner-strategies.tspackages/3-targets/3-targets/sqlite/src/core/migrations/planner-target-details.tspackages/3-targets/3-targets/sqlite/src/core/migrations/planner.tspackages/3-targets/3-targets/sqlite/src/core/migrations/render-ops.tspackages/3-targets/3-targets/sqlite/src/core/migrations/render-typescript.tspackages/3-targets/3-targets/sqlite/src/core/migrations/runner.tspackages/3-targets/3-targets/sqlite/src/core/migrations/sqlite-migration.tspackages/3-targets/3-targets/sqlite/src/core/migrations/statement-builders.tspackages/3-targets/3-targets/sqlite/src/core/native-type-normalizer.tspackages/3-targets/3-targets/sqlite/src/core/sql-utils.tspackages/3-targets/3-targets/sqlite/src/exports/codec-ids.tspackages/3-targets/3-targets/sqlite/src/exports/codec-types.tspackages/3-targets/3-targets/sqlite/src/exports/codecs.tspackages/3-targets/3-targets/sqlite/src/exports/control.tspackages/3-targets/3-targets/sqlite/src/exports/default-normalizer.tspackages/3-targets/3-targets/sqlite/src/exports/migration.tspackages/3-targets/3-targets/sqlite/src/exports/native-type-normalizer.tspackages/3-targets/3-targets/sqlite/src/exports/op-factory-call.tspackages/3-targets/3-targets/sqlite/src/exports/planner-produced-sqlite-migration.tspackages/3-targets/3-targets/sqlite/src/exports/planner-target-details.tspackages/3-targets/3-targets/sqlite/src/exports/planner.tspackages/3-targets/3-targets/sqlite/src/exports/render-ops.tspackages/3-targets/3-targets/sqlite/src/exports/sql-utils.tspackages/3-targets/3-targets/sqlite/src/exports/statement-builders.tspackages/3-targets/3-targets/sqlite/test/migrations/issue-planner.test.tspackages/3-targets/3-targets/sqlite/test/migrations/nullability-backfill.test.tspackages/3-targets/3-targets/sqlite/test/migrations/op-factory-call.test.tspackages/3-targets/3-targets/sqlite/test/migrations/planner-strategies.test.tspackages/3-targets/3-targets/sqlite/test/migrations/planner.authoring-surface.test.tspackages/3-targets/3-targets/sqlite/test/planner-ddl-builders.test.tspackages/3-targets/3-targets/sqlite/tsdown.config.tspackages/3-targets/3-targets/sqlite/vitest.config.tspackages/3-targets/6-adapters/postgres/src/core/control-adapter.tspackages/3-targets/6-adapters/sqlite/package.jsonpackages/3-targets/6-adapters/sqlite/src/core/adapter.tspackages/3-targets/6-adapters/sqlite/src/core/column-types.tspackages/3-targets/6-adapters/sqlite/src/core/control-adapter.tspackages/3-targets/6-adapters/sqlite/src/core/control-mutation-defaults.tspackages/3-targets/6-adapters/sqlite/src/core/runtime-adapter.tspackages/3-targets/6-adapters/sqlite/src/exports/codec-types.tspackages/3-targets/6-adapters/sqlite/src/exports/control.tspackages/3-targets/6-adapters/sqlite/test/codecs.test.tspackages/3-targets/6-adapters/sqlite/test/control-adapter.test.tspackages/3-targets/6-adapters/sqlite/test/migrations/fixtures/runner-fixtures.tspackages/3-targets/6-adapters/sqlite/test/migrations/render-typescript.roundtrip.test.tspackages/3-targets/6-adapters/sqlite/test/migrations/runner-integration.test.tspackages/3-targets/6-adapters/sqlite/test/migrations/runner.basic.test.tspackages/3-targets/6-adapters/sqlite/test/migrations/runner.errors.test.tspackages/3-targets/6-adapters/sqlite/test/migrations/runner.idempotency.test.tstest/e2e/framework/package.jsontest/e2e/framework/test/sqlite/migrations/additive.test.tstest/e2e/framework/test/sqlite/migrations/destructive.test.tstest/e2e/framework/test/sqlite/migrations/fk-preservation.test.tstest/e2e/framework/test/sqlite/migrations/harness.tstest/e2e/framework/test/sqlite/migrations/widening.test.tstest/integration/test/family.sign-database.test.ts
💤 Files with no reviewable changes (1)
- packages/2-sql/9-family/src/core/verify.ts
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (1)
test/e2e/framework/test/sqlite/migrations/fk-preservation.test.ts (1)
41-81:⚠️ Potential issue | 🟡 MinorAssert that recreate-table actually ran.
This case can still pass if the widening migration is accidentally downgraded to a no-op: the FK and data assertions would succeed on the unchanged table. Please assert the emitted operation id here — and in the other recreate-driven cases below — so the suite actually covers the rebuild path.
♻️ Suggested assertion
- async ({ driver, schema }) => { + async ({ driver, schema, plannedOperationIds }) => { + expect(plannedOperationIds).toContain('recreateTable.Post');🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/e2e/framework/test/sqlite/migrations/fk-preservation.test.ts` around lines 41 - 81, The test can pass without actually running a recreate-table migration, so within the applyMigration callback (the async ({ driver, schema }) => { ... }) assert that the migration plan emitted a recreate operation by checking the operations emitted by applyMigration and confirming an operation with id "recreate-table" exists; specifically, update the callback used in applyMigration to inspect the migration result (e.g., the operations/plan returned alongside schema or an operations array exposed by applyMigration) and add an expect(...) asserting that operations.some(op => op.id === 'recreate-table') is true so the test guarantees the rebuild path actually ran.
🧹 Nitpick comments (4)
packages/3-targets/6-adapters/sqlite/test/migrations/runner-integration.test.ts (1)
49-63: Keep the contract hash stable.
Date.now()makes the fixture change on every run, which adds noise and can hide caching/idempotency regressions. A fixed literal hash is enough here.♻️ Suggested fix
return { target: 'sqlite', targetFamily: 'sql', profileHash: profileHash('sha256:test'), storage: { tables, - storageHash: coreHash(`sha256:test-${Date.now()}`), + storageHash: coreHash('sha256:test-contract'), }, roots: {}, models: {}, capabilities: {},🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-targets/6-adapters/sqlite/test/migrations/runner-integration.test.ts` around lines 49 - 63, The storageHash generation in makeContract uses Date.now(), causing non-deterministic fixture changes; replace coreHash(`sha256:test-${Date.now()}`) with a stable literal (e.g. coreHash('sha256:test-fixed') or a constant) so makeContract returns a deterministic Contract<SqlStorage>; update the storageHash expression in the makeContract function accordingly and ensure profileHash('sha256:test') remains unchanged.test/e2e/framework/test/sqlite/utils.ts (1)
3-3: Usepathehere instead ofnode:path.As per coding guidelines, TypeScript test/helpers should use
pathefor path operations so behavior stays cross-platform.♻️ Suggested fix
-import { join } from 'node:path'; +import { join } from 'pathe';🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/e2e/framework/test/sqlite/utils.ts` at line 3, The test util currently imports join from 'node:path'; replace that with importing join (or joinPath if you prefer) from 'pathe' so path operations in test/e2e/framework/test/sqlite/utils.ts use the cross-platform pathe implementation; update any usages of join in that file accordingly (e.g., in helper functions that build file paths) to import join from 'pathe' instead of 'node:path'.test/e2e/framework/test/sqlite/migrations/harness.ts (1)
3-3: Usepathehere instead ofnode:path.As per coding guidelines, TypeScript test/helpers should use
pathefor path operations so behavior stays cross-platform.♻️ Suggested fix
-import { join } from 'node:path'; +import { join } from 'pathe';🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/e2e/framework/test/sqlite/migrations/harness.ts` at line 3, Replace the Node built-in import with the cross-platform pathe import: change the import statement that currently pulls join from 'node:path' to import join from 'pathe' (i.e., import { join } from 'pathe';) in harness.ts and keep all existing uses of join unchanged so path operations use pathe throughout the test helper.packages/3-targets/3-targets/sqlite/src/core/migrations/issue-planner.ts (1)
203-244: PreferifDefined()for the optional fields here.These helpers are pure data shapers, so the repeated ternary-spread pattern and the
Readonly<Record<...>>→Record<...>cast are both avoidable. IfbuildColumnTypeSql()only reads the map, widen that helper to accept the readonly type and useifDefined()for the optional properties. As per coding guidelines: UseifDefined()from@prisma-next/utils/definedfor conditional object spreads instead of inline conditional spread patterns.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-targets/3-targets/sqlite/src/core/migrations/issue-planner.ts` around lines 203 - 244, Replace the inline conditional spread patterns in toColumnSpec and toTableSpec with the ifDefined() helper from `@prisma-next/utils/defined` (e.g. use ifDefined(inlineAutoincrementPrimaryKey && { inlineAutoincrementPrimaryKey: true }) and similarly for u.name, fk.name, fk.onDelete, fk.onUpdate) and widen the parameter type of buildColumnTypeSql to accept Readonly<Record<string, StorageTypeInstance>> so you can remove the cast in toColumnSpec; update imports to include ifDefined and adjust the buildColumnTypeSql signature so callers like toColumnSpec no longer need to cast.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In
`@packages/3-targets/3-targets/sqlite/src/core/migrations/operations/tables.ts`:
- Around line 24-45: The renderCreateTableSql function currently only emits
columns, primary key, UNIQUE and FK constraints, which drops other
SqliteTableSpec attributes (e.g., conflict policies, table-level CHECK clauses,
WITHOUT ROWID, and any table-level constraints/clauses), causing
createTable/recreateTable to drift; update renderCreateTableSql to include
rendering of spec.conflict (table-level conflict clause if present), spec.checks
or tableChecks (emit CHECK(...) clauses), and spec.withoutRowid (append "WITHOUT
ROWID" to the CREATE TABLE statement when true), and ensure any table-level
constraints/named constraints from SqliteTableSpec are included in
constraintDefs before joining; touch symbols: renderCreateTableSql,
SqliteTableSpec, renderForeignKeyClause, createTable, recreateTable so the
emitted SQL fully reflects the spec.
In
`@packages/3-targets/6-adapters/sqlite/test/migrations/runner-integration.test.ts`:
- Around line 183-247: The test currently exercises planner.plan and then
manually replays result.plan.operations by calling driver.query for each step
(see createSqliteMigrationPlanner, planner.plan and the for-loops that call
driver.query), which skips the runner code-path; replace the manual replay with
a call into the migration runner entrypoint (invoke the project's runner such as
MigrationRunner.run or runMigrations with the planner result/contract/driver and
SqliteControlAdapter) so the test hits BEGIN EXCLUSIVE, control-table writes,
idempotent re-runs and FK-check flow, and wrap driver usage in a try/finally to
always await driver.close() on test failure; alternatively, if you intent to
only test planner+adapter, rename the test to reflect that narrower scope.
---
Duplicate comments:
In `@test/e2e/framework/test/sqlite/migrations/fk-preservation.test.ts`:
- Around line 41-81: The test can pass without actually running a recreate-table
migration, so within the applyMigration callback (the async ({ driver, schema })
=> { ... }) assert that the migration plan emitted a recreate operation by
checking the operations emitted by applyMigration and confirming an operation
with id "recreate-table" exists; specifically, update the callback used in
applyMigration to inspect the migration result (e.g., the operations/plan
returned alongside schema or an operations array exposed by applyMigration) and
add an expect(...) asserting that operations.some(op => op.id ===
'recreate-table') is true so the test guarantees the rebuild path actually ran.
---
Nitpick comments:
In `@packages/3-targets/3-targets/sqlite/src/core/migrations/issue-planner.ts`:
- Around line 203-244: Replace the inline conditional spread patterns in
toColumnSpec and toTableSpec with the ifDefined() helper from
`@prisma-next/utils/defined` (e.g. use ifDefined(inlineAutoincrementPrimaryKey &&
{ inlineAutoincrementPrimaryKey: true }) and similarly for u.name, fk.name,
fk.onDelete, fk.onUpdate) and widen the parameter type of buildColumnTypeSql to
accept Readonly<Record<string, StorageTypeInstance>> so you can remove the cast
in toColumnSpec; update imports to include ifDefined and adjust the
buildColumnTypeSql signature so callers like toColumnSpec no longer need to
cast.
In
`@packages/3-targets/6-adapters/sqlite/test/migrations/runner-integration.test.ts`:
- Around line 49-63: The storageHash generation in makeContract uses Date.now(),
causing non-deterministic fixture changes; replace
coreHash(`sha256:test-${Date.now()}`) with a stable literal (e.g.
coreHash('sha256:test-fixed') or a constant) so makeContract returns a
deterministic Contract<SqlStorage>; update the storageHash expression in the
makeContract function accordingly and ensure profileHash('sha256:test') remains
unchanged.
In `@test/e2e/framework/test/sqlite/migrations/harness.ts`:
- Line 3: Replace the Node built-in import with the cross-platform pathe import:
change the import statement that currently pulls join from 'node:path' to import
join from 'pathe' (i.e., import { join } from 'pathe';) in harness.ts and keep
all existing uses of join unchanged so path operations use pathe throughout the
test helper.
In `@test/e2e/framework/test/sqlite/utils.ts`:
- Line 3: The test util currently imports join from 'node:path'; replace that
with importing join (or joinPath if you prefer) from 'pathe' so path operations
in test/e2e/framework/test/sqlite/utils.ts use the cross-platform pathe
implementation; update any usages of join in that file accordingly (e.g., in
helper functions that build file paths) to import join from 'pathe' instead of
'node:path'.
🪄 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: fdf56454-1e34-4147-a5ec-c46979cc9211
📒 Files selected for processing (15)
coverage.config.jsonexamples/prisma-next-demo-sqlite/src/prisma/db.tspackages/3-targets/3-targets/sqlite/src/core/default-normalizer.tspackages/3-targets/3-targets/sqlite/src/core/migrations/issue-planner.tspackages/3-targets/3-targets/sqlite/src/core/migrations/operations/data-transform.tspackages/3-targets/3-targets/sqlite/src/core/migrations/operations/tables.tspackages/3-targets/3-targets/sqlite/src/core/migrations/planner-ddl-builders.tspackages/3-targets/3-targets/sqlite/src/core/migrations/runner.tspackages/3-targets/6-adapters/sqlite/src/exports/codec-types.tspackages/3-targets/6-adapters/sqlite/src/exports/control.tspackages/3-targets/6-adapters/sqlite/test/migrations/runner-integration.test.tspackages/3-targets/6-adapters/sqlite/test/migrations/runner.idempotency.test.tstest/e2e/framework/test/sqlite/migrations/fk-preservation.test.tstest/e2e/framework/test/sqlite/migrations/harness.tstest/e2e/framework/test/sqlite/utils.ts
✅ Files skipped from review due to trivial changes (1)
- packages/3-targets/6-adapters/sqlite/src/exports/control.ts
🚧 Files skipped from review as they are similar to previous changes (4)
- examples/prisma-next-demo-sqlite/src/prisma/db.ts
- packages/3-targets/3-targets/sqlite/src/core/migrations/planner-ddl-builders.ts
- packages/3-targets/6-adapters/sqlite/test/migrations/runner.idempotency.test.ts
- packages/3-targets/3-targets/sqlite/src/core/migrations/runner.ts
Code Review — PR #386 (multi-agent)Reviewed via parallel agents (architecture, security, data-integrity, migration-mappings, simplicity, performance/verification) against a worktree on Summary
🔴 P1 — BLOCKS MERGEThe headline issue: literal defaults infinite-loop the planner. Confirmed independently by two agents.
🟡 P2 — should fix
🔵 P3 — nice-to-have
What checked out cleanly
Recommended pre-merge work
Reviewed by Claude on behalf of @jkomyno. |
There was a problem hiding this comment.
Actionable comments posted: 10
🧹 Nitpick comments (2)
packages/3-targets/6-adapters/sqlite/test/migrations/planner.test.ts (1)
146-155: Assert the specific policy conflict, not onlykind: 'failure'.Right now this test can pass on any failure reason. Please assert the expected conflict (
unsupportedOperation) so policy enforcement regressions are caught precisely.Suggested assertion tightening
it('fails without additive policy', () => { const contract = makeContract({}); const result = planner.plan({ contract, schema: emptySchema, policy: { allowedOperationClasses: [] }, frameworkComponents: [], }); expect(result.kind).toBe('failure'); + if (result.kind !== 'failure') return; + expect(result.conflicts[0]?.kind).toBe('unsupportedOperation'); + expect(result.conflicts[0]?.summary).toContain('additive'); });🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-targets/6-adapters/sqlite/test/migrations/planner.test.ts` around lines 146 - 155, The test currently only checks result.kind === 'failure' which is too broad; update the assertion to verify the specific policy conflict by asserting that planner.plan(...) returns a failure with the conflict type 'unsupportedOperation' (e.g., inspect result.details/conflict or result.policyConflict field depending on planner.plan's shape) when calling planner.plan with makeContract({}), emptySchema and policy: { allowedOperationClasses: [] }; keep references to planner.plan, makeContract, emptySchema and the policy object so the test fails only if the unsupportedOperation conflict is not produced.examples/prisma-next-demo-sqlite/src/queries/dml-operations.ts (1)
4-6: Consider relying on DB default forcreatedAthere.Line 5 overrides a schema default (
now()), which can introduce app-clock vs DB-clock drift. OmittingcreatedAtkeeps behavior aligned with contract defaults.Suggested refactor
const plan = db.sql.user - .insert({ email, displayName, createdAt: new Date() }) + .insert({ email, displayName }) .returning('id', 'email') .build();🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@examples/prisma-next-demo-sqlite/src/queries/dml-operations.ts` around lines 4 - 6, The insert currently sets createdAt explicitly which overrides the DB default now() and can cause clock drift; update the db.sql.user.insert call (the plan variable) to omit the createdAt property so the database default is used (keep email, displayName and the .returning('id','email') as-is).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@examples/prisma-next-demo-sqlite/src/main.ts`:
- Around line 34-35: The parsed limit value (const limit =
Number.parseInt(args[0], 10)) is not validated and can be NaN, 0 or negative
before being passed to getUsers (and the other similar parsing site around lines
51-52); fix by sanitizing the parsed value: parse with Number.parseInt, check
Number.isFinite and Number.isInteger and ensure value > 0, otherwise fall back
to the default (e.g., 10), then pass that validated value into getUsers (and the
other call) so queries never receive invalid limits.
- Around line 32-85: Multiple branches inside the main try block (commands
handling around the cmd checks and calls to getUsers, ormClientFindUserById,
ormClientGetUserPosts, ormClientCreateUser, insertUser) call process.exit(),
which prevents the finally block from running and skips runtime.close(); change
each early process.exit() in those command-usage/error branches to set
process.exitCode = 1 (or 0 as appropriate) and then return from the main
function instead of exiting the process, so the finally block that calls
runtime.close() always executes; keep the outer catch still setting
process.exitCode on error and allow finally to close the runtime.
In `@examples/prisma-next-demo-sqlite/src/orm-client/create-user.ts`:
- Around line 29-30: The toUserCreatedAt function currently accepts strings that
may produce "Invalid Date" later; update to validate input and reject invalid
dates before mapping: if value is a Date ensure !isNaN(value.getTime()), if it's
a string attempt to parse to a Date and verify the parsed date is valid, and if
validation fails throw a clear descriptive error (e.g., TypeError or Error)
indicating the createdAt value is invalid so callers can handle it; modify the
toUserCreatedAt function and any callers that rely on it accordingly (refer to
toUserCreatedAt and UserRow['createdAt']).
In `@examples/prisma-next-demo-sqlite/src/orm-client/get-user-posts.ts`:
- Around line 13-17: The ormClientGetUserPosts function currently forwards the
raw limit into .take(limit) which can be NaN, 0, or negative; validate and
normalize limit before calling .take: parse/coerce it to an integer, treat
non-numeric or <1 values as a safe default (e.g., 10) or clamp to a minimum of
1, and then pass that sanitized value to db.User.include(...).take(...). This
change affects the ormClientGetUserPosts function and the .take(limit) call so
add validation logic there to ensure only a positive integer is used.
- Line 16: Replace the blind cast in the .where({ id: userId as UserId }) call
by adding a small validator/converter (mirror the pattern from
find-user-by-id.ts) such as toUserId(userId) or a type-guard isUserId(userId)
and use that before calling .where; implement validation logic inside toUserId
(or the type predicate) to assert/narrow the type to UserId and return the
properly typed value, then call .where({ id: toUserId(userId) }) (or
conditionally call .where only after isUserId(userId) is true).
In
`@packages/3-targets/6-adapters/sqlite/test/migrations/planner-introspection.integration.test.ts`:
- Around line 84-245: Add a new integration test in the same file that uses
createSqliteMigrationPlanner(), runPlannedSteps(driver, ...), and
SqliteControlAdapter().introspect(driver) to exercise planner→execute→introspect
for default canonicalization: define a contract table (e.g., "defaults") with
columns that have a numeric literal default, a boolean literal default, a
dbgenerated("CURRENT_TIMESTAMP") default, and a string default containing an
apostrophe; plan and execute the migration with planner.plan(...) and
runPlannedSteps, then call adapter.introspect(driver) and assert that
schema.tables['defaults']!.columns for each column contains the expected
canonicalized default representation (match on normalized literal forms and
dbgenerated expression and properly escaped apostrophe) to prevent default
drift.
- Around line 11-12: The test is using the generic Contract<SqlStorage> which
weakens type inference; import and use the locally-typed Contract from
fixtures/contract.d.ts instead of the Contract from
'@prisma-next/contract/types' and update the makeContract usage so its return is
the typed Contract (replace the type annotation Contract<SqlStorage> with the
local Contract type). Keep other imports like coreHash and profileHash as-is,
and ensure any references to table/column types now resolve to the fixture
Contract to restore strict table/column inference for makeContract and related
assertions.
In `@packages/3-targets/6-adapters/sqlite/test/migrations/planner.test.ts`:
- Around line 44-156: Add three regression tests to the SQLite migration planner
suite using createSqliteMigrationPlanner() and planner.plan: (1) a
numeric/boolean literal default equivalence test that creates a contract with a
column default expressed as a numeric/boolean literal and an existing schema
with the equivalent canonical default (use makeContract/makeTable/makeColumn and
assert planner.plan returns no-op or no ADD COLUMN/ALTER for that column); (2) a
dbgenerated("CURRENT_TIMESTAMP") canonicalization test that ensures a column
defined with dbgenerated("CURRENT_TIMESTAMP") in the contract does not produce a
spurious change when the existing schema has the canonicalized form (assert
result.kind === 'success' and no conflicting operations like ALTER for that
column id); and (3) an apostrophe-containing string default test where a column
default contains an apostrophe (e.g., "O'Brien") and the planner correctly
canonicalizes/quotes it so no unnecessary migration is planned (assert no
ALTER/ADD for column id or that generated SQL properly contains the quoted
default). Ensure each test follows the existing pattern (use planner.plan, check
result.kind, then inspect ops for column.<table>.<column> or absence of
operations).
In
`@packages/3-targets/6-adapters/sqlite/test/migrations/render-typescript.roundtrip.test.ts`:
- Around line 82-87: The rewriteImports function only replaces a single literal
single-quoted occurrence and will fail if the renderer uses double quotes or
multiple occurrences; update rewriteImports to perform a global, quote-agnostic
replacement of the module specifier by using a regex that matches either single
or double quotes and all occurrences (capture the quote if you want to preserve
it) and replace each match with targetSqliteMigrationExport so every occurrence
"'@prisma-next/target-sqlite/migration'" or
"\"@prisma-next/target-sqlite/migration\"" is rewritten reliably.
- Around line 95-105: afterEach currently calls rm(tmpDir, ...) unconditionally
which can throw if beforeEach failed to set tmpDir; update the teardown in the
afterEach hook to guard removal by checking tmpDir (and/or that the path exists)
before calling rm. Locate the tmpDir variable and the beforeEach/afterEach
blocks in the test file (see mkdtemp in beforeEach and rm in afterEach) and
change afterEach to only attempt rm when tmpDir is a non-empty string (or the
path exists) to avoid masking setup failures.
---
Nitpick comments:
In `@examples/prisma-next-demo-sqlite/src/queries/dml-operations.ts`:
- Around line 4-6: The insert currently sets createdAt explicitly which
overrides the DB default now() and can cause clock drift; update the
db.sql.user.insert call (the plan variable) to omit the createdAt property so
the database default is used (keep email, displayName and the
.returning('id','email') as-is).
In `@packages/3-targets/6-adapters/sqlite/test/migrations/planner.test.ts`:
- Around line 146-155: The test currently only checks result.kind === 'failure'
which is too broad; update the assertion to verify the specific policy conflict
by asserting that planner.plan(...) returns a failure with the conflict type
'unsupportedOperation' (e.g., inspect result.details/conflict or
result.policyConflict field depending on planner.plan's shape) when calling
planner.plan with makeContract({}), emptySchema and policy: {
allowedOperationClasses: [] }; keep references to planner.plan, makeContract,
emptySchema and the policy object so the test fails only if the
unsupportedOperation conflict is not produced.
🪄 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: 2b9ad33d-4dfc-4676-9c17-d2a83fbae385
📒 Files selected for processing (16)
coverage.config.jsonexamples/prisma-next-demo-sqlite/README.mdexamples/prisma-next-demo-sqlite/package.jsonexamples/prisma-next-demo-sqlite/prisma/contract.tsexamples/prisma-next-demo-sqlite/scripts/seed.tsexamples/prisma-next-demo-sqlite/src/main.tsexamples/prisma-next-demo-sqlite/src/orm-client/client.tsexamples/prisma-next-demo-sqlite/src/orm-client/create-user.tsexamples/prisma-next-demo-sqlite/src/orm-client/get-user-posts.tsexamples/prisma-next-demo-sqlite/src/prisma/contract.d.tsexamples/prisma-next-demo-sqlite/src/prisma/contract.jsonexamples/prisma-next-demo-sqlite/src/queries/dml-operations.tsexamples/prisma-next-demo-sqlite/src/queries/get-users.tspackages/3-targets/6-adapters/sqlite/test/migrations/planner-introspection.integration.test.tspackages/3-targets/6-adapters/sqlite/test/migrations/planner.test.tspackages/3-targets/6-adapters/sqlite/test/migrations/render-typescript.roundtrip.test.ts
✅ Files skipped from review due to trivial changes (3)
- examples/prisma-next-demo-sqlite/src/queries/get-users.ts
- examples/prisma-next-demo-sqlite/package.json
- examples/prisma-next-demo-sqlite/README.md
🚧 Files skipped from review as they are similar to previous changes (5)
- examples/prisma-next-demo-sqlite/src/orm-client/client.ts
- coverage.config.json
- examples/prisma-next-demo-sqlite/scripts/seed.ts
- examples/prisma-next-demo-sqlite/src/prisma/contract.json
- examples/prisma-next-demo-sqlite/prisma/contract.ts
| const limit = args[0] ? Number.parseInt(args[0], 10) : 10; | ||
| const users = await getUsers(limit); |
There was a problem hiding this comment.
Validate limit arguments before use.
Lines 34 and 51 accept invalid values (NaN, 0, negatives) and pass them into query helpers.
Suggested fix
- const limit = args[0] ? Number.parseInt(args[0], 10) : 10;
+ const parsed = args[0] ? Number.parseInt(args[0], 10) : 10;
+ if (!Number.isInteger(parsed) || parsed <= 0) {
+ console.error('Usage: pnpm start -- users [positive-limit]');
+ process.exitCode = 1;
+ return;
+ }
+ const limit = parsed;
@@
- const limit = limitStr ? Number.parseInt(limitStr, 10) : 10;
+ const parsed = limitStr ? Number.parseInt(limitStr, 10) : 10;
+ if (!Number.isInteger(parsed) || parsed <= 0) {
+ console.error('Usage: pnpm start -- repo-user-posts <id> [positive-limit]');
+ process.exitCode = 1;
+ return;
+ }
+ const limit = parsed;Also applies to: 51-52
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@examples/prisma-next-demo-sqlite/src/main.ts` around lines 34 - 35, The
parsed limit value (const limit = Number.parseInt(args[0], 10)) is not validated
and can be NaN, 0 or negative before being passed to getUsers (and the other
similar parsing site around lines 51-52); fix by sanitizing the parsed value:
parse with Number.parseInt, check Number.isFinite and Number.isInteger and
ensure value > 0, otherwise fall back to the default (e.g., 10), then pass that
validated value into getUsers (and the other call) so queries never receive
invalid limits.
saevarb
left a comment
There was a problem hiding this comment.
A few comments, but otherwise looks good to me. I did not review all the tests
b3038d2 to
fb97556
Compare
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (2)
packages/3-targets/6-adapters/sqlite/test/control-mutation-defaults.test.ts (1)
55-64: Add thedatetime("now")synonym case for completenessYou already validate
datetime('now'); adding the double-quoted form would fully mirror the documented synonym set and harden against future regressions.💡 Suggested test addition
+ it('canonicalizes dbgenerated("datetime(\\"now\\")") to { function "now()" }', () => { + const result = dbgenerated.lower({ + call: makeCall('dbgenerated', [arg('"datetime(\\"now\\")"')]), + context: stubContext, + }); + expect(result).toMatchObject({ + ok: true, + value: { kind: 'storage', defaultValue: { kind: 'function', expression: 'now()' } }, + }); + });🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-targets/6-adapters/sqlite/test/control-mutation-defaults.test.ts` around lines 55 - 64, Add a parallel test case to the existing one that calls dbgenerated.lower with makeCall('dbgenerated', [arg('"datetime(\"now\")"')]) (mirroring the existing test that uses single quotes) to assert the same output shape: ok: true and value: { kind: 'storage', defaultValue: { kind: 'function', expression: 'now()' } }; locate the test near the existing it(...) block in control-mutation-defaults.test.ts and use the same stubContext so both the single-quoted and double-quoted datetime("now") forms are validated by dbgenerated.lower.test/e2e/framework/test/sqlite/migrations/widening.test.ts (1)
95-102: Tighten the row assertion instead of optional chaining.Line 101 uses
row?.createdAtin a success-path assertion; assert the row shape directly so failures point to the real cause.As per coding guidelines: "Prefer assertions over defensive checks ... remove optional chaining" and "Prefer object matchers over multiple individual `expect().toBe()` calls in test assertions."Cleaner assertion with explicit shape check
const row = ( await driver.query<{ createdAt: string }>( 'SELECT createdAt FROM "User" WHERE id = ?', [1], ) ).rows[0]; - expect(typeof row?.createdAt).toBe('string'); + expect(row).toMatchObject({ createdAt: expect.any(String) });🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/e2e/framework/test/sqlite/migrations/widening.test.ts` around lines 95 - 102, The test currently uses optional chaining on the fetched row (variable row) when asserting createdAt; replace this defensive check with a tight assertion that the row exists and has the expected shape. Locate the code that assigns row (the result of driver.query) and change the assertion to directly assert the row object—for example use an object matcher like expect(row).toMatchObject({ createdAt: expect.any(String) }) or first assert expect(row).toBeDefined() then expect(row.createdAt).toEqual(expect.any(String)) so failures point to missing row instead of silently passing due to optional chaining.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In
`@packages/3-targets/3-targets/sqlite/src/core/migrations/operations/tables.ts`:
- Around line 226-276: The recreate postcheck currently only adds
nullability/default/type/extra_default checks in the loop (see checks array,
esc(), byName, t and recreateTableStrategy()), but it must also verify
primary-key, unique and foreign-key mismatches so a recreated table with wrong
constraints cannot pass; update the loop to handle the constraint issue kinds
produced by recreateTableStrategy (e.g. primary-key, unique, foreign-key
mismatch identifiers used in your diff) by adding appropriate SELECT-based
postchecks (use pragma_table_info(...) "pk" for primary key position,
pragma_index_list/pragma_index_info for unique/index constraints, and
pragma_foreign_key_list for FK definitions) referencing issue.column or other
issue metadata, or if those issue objects lack enough detail, fall back to
enqueueing a full schema-verify postcheck instead of the lightweight checks.
In
`@packages/3-targets/3-targets/sqlite/src/core/migrations/planner-strategies.ts`:
- Around line 146-155: The RecreateTableCall currently uses schemaColumnNames
(Object.keys(schemaTable.columns)) so contract-only columns (in
tableSpec.columns but not in schemaTable.columns) are omitted from the
INSERT...SELECT; detect if any contract-only column is NOT NULL and has no
default (and is not a generated column) before pushing the RecreateTableCall and
instead surface a planner conflict. Concretely: compute contractOnly =
Object.keys(tableSpec.columns).filter(c => !schemaTable.columns[c]); check
contractOnly.some(c => tableSpec.columns[c].notNull &&
!tableSpec.columns[c].default && !tableSpec.columns[c].generated); if true, do
not push the new RecreateTableCall and instead add/return a planner
conflict/error referencing the tableName and the offending column(s) (use the
same metadata used by buildRecreateSummary/buildRecreatePostchecks to describe
the issue).
In `@test/e2e/framework/test/sqlite/migrations/widening.test.ts`:
- Around line 92-94: The test currently pins the exact string "datetime('now')"
by asserting expect(stored).toBe("datetime('now')"); instead, change the
assertion to check semantic equivalence using the same parser used elsewhere
(e.g., call parseSqliteDefault on stored and compare to
parseSqliteDefault("datetime('now')") or use the harness helper that validates
defaults) so the test accepts equivalent SQLite spellings; update the assertion
around the variable stored in widening.test.ts and keep the subsequent INSERT
(driver.query) unchanged.
---
Nitpick comments:
In `@packages/3-targets/6-adapters/sqlite/test/control-mutation-defaults.test.ts`:
- Around line 55-64: Add a parallel test case to the existing one that calls
dbgenerated.lower with makeCall('dbgenerated', [arg('"datetime(\"now\")"')])
(mirroring the existing test that uses single quotes) to assert the same output
shape: ok: true and value: { kind: 'storage', defaultValue: { kind: 'function',
expression: 'now()' } }; locate the test near the existing it(...) block in
control-mutation-defaults.test.ts and use the same stubContext so both the
single-quoted and double-quoted datetime("now") forms are validated by
dbgenerated.lower.
In `@test/e2e/framework/test/sqlite/migrations/widening.test.ts`:
- Around line 95-102: The test currently uses optional chaining on the fetched
row (variable row) when asserting createdAt; replace this defensive check with a
tight assertion that the row exists and has the expected shape. Locate the code
that assigns row (the result of driver.query) and change the assertion to
directly assert the row object—for example use an object matcher like
expect(row).toMatchObject({ createdAt: expect.any(String) }) or first assert
expect(row).toBeDefined() then expect(row.createdAt).toEqual(expect.any(String))
so failures point to missing row instead of silently passing due to optional
chaining.
🪄 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: 30a7a8f2-f526-4637-956c-1291c3d3d864
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (9)
packages/3-targets/3-targets/sqlite/src/core/default-normalizer.tspackages/3-targets/3-targets/sqlite/src/core/migrations/op-factory-call.tspackages/3-targets/3-targets/sqlite/src/core/migrations/operations/tables.tspackages/3-targets/3-targets/sqlite/src/core/migrations/planner-strategies.tspackages/3-targets/3-targets/sqlite/test/migrations/op-factory-call.test.tspackages/3-targets/6-adapters/sqlite/src/core/control-mutation-defaults.tspackages/3-targets/6-adapters/sqlite/test/control-mutation-defaults.test.tspackages/3-targets/6-adapters/sqlite/test/migrations/render-typescript.roundtrip.test.tstest/e2e/framework/test/sqlite/migrations/widening.test.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- packages/3-targets/3-targets/sqlite/src/core/default-normalizer.ts
- packages/3-targets/6-adapters/sqlite/src/core/control-mutation-defaults.ts
- issue-planner: surface enum_values_changed as a verifier-bug conflict
instead of silently returning ok([]) — SQLite has sql.enums: false, so
receiving one means the verifier emitted a wrong issue.
- op-factory-call: take id/label as required args on DataTransformCall.
The op is generic; baking in "backfill"-flavored strings forced every
caller to look like a backfill. Caller in
nullabilityTighteningBackfillStrategy now passes the same strings it
used to rely on.
- planner: refresh JSDoc to drop the per-strategy enumeration. Strategies
can compose and may be user-provided in the future, so describing the
contract instead of listing strategies keeps the doc honest.
- runner / family-sql verify: drop the inline marker-row type and extend
parseContractMarkerRow to also parse JSON-string contract_json (SQLite
stores it as TEXT; Postgres returns it pre-parsed). New ContractMarkerRow
type is exported from @prisma-next/family-sql/verify and reused by the
SQLite runner.
- demo main.ts: replace `process.exit(1)` inside the try/catch with
`process.exitCode = 1; return;` so the `finally { runtime.close() }`
always runs.
- adapter-sqlite render-typescript.roundtrip test: guard the `afterEach`
cleanup so a setup failure isn't masked by an `rm(undefined, …)` error.
36cd767 to
472497f
Compare
Implement the SQLite migration control plane (Milestone 4): Adapter (control-mutation-defaults.ts): - PSL scalar type → SQLite native type mappings - Default function registry (autoincrement, now, uuid, etc.) Adapter (control-adapter.ts): - SqliteControlAdapter with introspect() via sqlite_master + PRAGMA - parseSqliteDefault() normalizer returning ColumnDefault - normalizeSqliteNativeType() for schema verification Target (migrations/): - Planner generating CREATE TABLE, ADD COLUMN, CREATE INDEX ops - DDL builders with SQLite dialect (AUTOINCREMENT, inline FK/UNIQUE) - Runner with BEGIN EXCLUSIVE transactions, control tables (_prisma_marker, _prisma_ledger) using TEXT instead of JSONB - Statement builders with ? params instead of $1 Tests: - 88 adapter tests (introspection, default parsing, codecs) - 41 target tests (DDL builders, planner round-trips, runner lifecycle with real file-backed databases, idempotency, error scenarios matching Postgres test patterns)
Extend the SQLite migration planner with full reconciliation support: - Widening: recreate-table for nullability relaxation, default changes - Destructive: DROP TABLE, DROP INDEX, DROP COLUMN, recreate-table for type changes, nullability tightening, constraint changes - Conflict reporting with granular kinds (typeMismatch, nullabilityConflict, indexIncompatible, foreignKeyConflict) Add e2e migration tests in the e2e package using the contract authoring DSL (defineContract/model/field) covering additive, schema evolution, destructive, widening, and recreate-table operations.
The SQLite recreate-table flow (used for widening/destructive column changes) drops and rebuilds the table. Two problems made this unsafe: - FK-backing indexes were not re-emitted, so verification failed after recreate when the contract declared an FK with index:true. - foreign_keys was left ON during the migration, so DROP TABLE on a referenced parent cascade-deleted rows in child tables. The planner now re-emits FK-backing indexes alongside declared indexes when building recreate-table operations. The runner turns foreign_keys OFF before BEGIN EXCLUSIVE (the pragma is a no-op inside a transaction), runs PRAGMA foreign_key_check before commit, and restores the pragma in an outer finally. A new FOREIGN_KEY_VIOLATION error code surfaces any violations detected by the integrity check. Also fixes the adapter so the test suite can load: controlMutationDefaults was a thunk but the framework expects a plain object (matches postgres); scalarTypeDescriptors was nested under a nonexistent pslTypeDescriptors field; and control-mutation-defaults.ts imported type names that do not exist in family-sql (they live in framework-components). Tests added in test/e2e/framework/test/sqlite/migrations.test.ts: - preserves FK when the child table (holder of the FK) is recreated - preserves FK when the parent (referenced) table is recreated - preserves declared indexes when the table is recreated
…igration E2E Three focused follow-ups from a local review of the SQLite migration work: - Marker singleton invariant is now schema-enforced. `_prisma_marker.id` was `INTEGER PRIMARY KEY DEFAULT 1` with the "only row 1 exists" rule encoded only in the runner's `WHERE id = 1`. Replaced with `INTEGER PRIMARY KEY CHECK (id = 1)` so a stray second row is rejected at the database level instead of silently accumulated. - Removed a dead `sqliteControlAdapterDescriptor` default export from `packages/3-targets/6-adapters/sqlite/src/core/control-adapter.ts`. That descriptor had only the meta fields and `create()` — no `controlMutationDefaults`, no `scalarTypeDescriptors`. It was never imported, but if it ever had been it would have silently bypassed PSL mappings and default registries. `exports/control.ts` remains the single canonical adapter descriptor (same shape as postgres). - Split `test/e2e/framework/test/sqlite/migrations.test.ts` (~1300 lines mixing infrastructure and five concern areas) into `migrations/harness.ts` + four focused test files (`additive.test.ts`, `destructive.test.ts`, `widening.test.ts`, `fk-preservation.test.ts`). Test count unchanged (31 cases across 4 files); each file now browseable without scrolling.
…s + IR The SQLite planner becomes a thin wrapper over `planIssues` (the same shape Postgres uses): strategies absorb cohesive multi-issue recipes, `mapIssueToCall` handles per-issue defaults, and the result is a `SqliteOpFactoryCall[]` IR consumed by both the runtime ops view (`renderOps`) and the TypeScript authoring surface (`renderCallsToTypeScript`). Plans returned by the planner now satisfy `MigrationPlanWithAuthoringSurface` (ADR 194), unblocking class-flow authoring (ADR 193) and ops.json scaffolding (ADR 192) for SQLite. The `recreateTableStrategy` is the cornerstone: type/nullability/default/ constraint mismatches all collapse into a single recreate-table op per table, preserving the byte-exact SQL strings, idempotent postchecks, and operation IDs of the previous monolithic planner so all 82 existing e2e tests pass unchanged. A `nullabilityTighteningBackfillStrategy` mirrors Postgres's `nullableTighteningCallStrategy`: when policy allows `'data'` and the contract tightens nullable -> NOT NULL, the planner emits a `DataTransformCall` stub that the user fills with an `UPDATE ... WHERE col IS NULL` before the recreate copies data into the tightened schema. The runner-owned control-table filter (`_prisma_marker`, `_prisma_ledger`) is now an explicit `CONTROL_TABLE_NAMES` set rather than a `_prisma_*` prefix match, so stale `_prisma_new_*` temp tables left by crashed recreates surface as droppable `extra_table` issues. Adds 53 unit tests covering `planIssues`, `recreateTableStrategy`, each `*Call`'s `toOp()`/`renderTypeScript()`, and the `TypeScriptRenderableSqliteMigration` authoring surface. Coverage rises from 72.4% / 56.6% / 76.6% / 75.0% to 86.1% / 70.2% / 89.1% / 87.8% (stmts/branches/funcs/lines); thresholds are now locked in at 79/65/88/79 matching Postgres.
…trol-adapter seam
Adds `examples/prisma-next-demo-sqlite/` mirroring `examples/prisma-next-demo`
against `@prisma-next/sqlite`. While porting it, the `dbInit` flow on
SQLite blew up against `information_schema.tables` and surfaced a string
of half-wired SQLite plumbing that this commit also repairs.
- TypeScript contract authoring (`prisma/contract.ts`) + emit workflow
(`src/prisma/db.ts`) and no-emit workflow (`src/prisma-no-emit/`).
- ORM-client examples + SQL DSL examples + telemetry middleware.
- Integration tests against a temporary file-based SQLite database
applied via `dbInit`.
- Drops queries that don't fit SQLite: pgvector similarity, `distinctOn`,
PSL-only `@@discriminator` polymorphism, `@@enum`, `ilike`, and the
budget-violation/guardrail-delete commands (the budget middleware
trips on the ORM's N+1 include strategy when LATERAL is unavailable —
see README for the trade-off).
- See `examples/prisma-next-demo-sqlite/README.md` for the full diff vs
the Postgres demo.
`@prisma-next/family-sql/verify` was hardcoded to Postgres SQL
(`information_schema.tables` probe + `prisma_contract.marker` read with
`$1` placeholders), so any non-Postgres `dbInit`/`dbUpdate`/`verify`
failed before reaching its own runner. Move marker reads to the adapter:
- Add `readMarker(driver)` to `SqlControlAdapter`. Each target adapter
owns its existence probe + marker SELECT.
- `createSqlFamilyInstance` routes through a `getControlAdapter()` helper
that materializes the adapter from the stack and runs the structural
guard once. The structural guard now also checks for `readMarker`.
- Implement `PostgresControlAdapter.readMarker` with the existing
`prisma_contract.marker` probe + read.
- Drop `readMarker`, `readMarkerSql`, and `markerTableExistsSql` from
`@prisma-next/family-sql/verify` (and the public re-export).
`parseContractMarkerRow` stays family-level — adapters call it on
rows they fetched themselves.
- `PostgresMigrationRunner` now calls `family.readMarker({ driver })`
instead of the deleted helper.
- `family.sign-database.test.ts` uses `familyInstance.readMarker(...)`.
- Implement `SqliteControlAdapter.readMarker` (`sqlite_master` probe +
`_prisma_marker` read — the table the migration runner actually
creates) and `SqliteControlAdapter.lower`.
- Extract `renderLoweredSql(ast, contract)` from `SqliteAdapterImpl.lower`
so runtime and control adapters emit byte-identical SQL.
- Filter `_prisma_marker` / `_prisma_ledger` out of
`SqliteControlAdapter.introspect` — they're runner-managed and must
not surface as `extra_table` under strict schema verification.
- Wire `@prisma-next/ids` builtin generators into the SQLite runtime
adapter's `mutationDefaultGenerators` (was `() => []`, so contracts
using `field.id.uuidv4()` failed at insert with
`RUNTIME.MUTATION_DEFAULT_GENERATOR_MISSING`).
- Repoint the runtime adapter's `readMarkerStatement` from the
never-created `prisma_contract_marker` to `_prisma_marker`.
- Regenerate `test/integration/test/sql-builder/fixtures/generated/contract.d.ts`
after the codec-types relocation, mirroring 83cc67e.
…shared utilities target-side
Two related changes that bring the SQLite target's architecture into line
with Postgres.
1. Operation factories now take flat specs, not StorageColumn/StorageTable.
`createTable`, `addColumn`, and `recreateTable` previously consumed
`StorageColumn` / `StorageTable` plus `codecHooks` / `storageTypes`
maps and resolved `typeRef` / rendered DEFAULT clauses inline. The
`*Call` IR nodes carried those non-serializable maps too, which made
`renderTypeScript()` for `RecreateTableCall` impossible to fully
render and required a `resolveStorageTableTypeRefs` helper to
pre-resolve at render time.
Postgres resolves once at the call-construction boundary (in
`issue-planner.ts:toColumnSpec`) and stores a flat `ColumnSpec` in
the Call. SQLite now does the same:
- New flat shapes in `operations/shared.ts`: `SqliteColumnSpec`,
`SqliteTableSpec`, `SqliteIndexSpec`, `SqlitePrimaryKeySpec`,
`SqliteUniqueSpec`, `SqliteForeignKeySpec`. Plus
`renderColumnDefinition` / `renderForeignKeyClause` helpers.
- `toColumnSpec` and `toTableSpec` in `issue-planner.ts` build the
flat specs from `StorageColumn` / `StorageTable` once, calling the
low-level `buildColumnTypeSql` / `buildColumnDefaultSql` helpers.
- `CreateTableCall(name, spec)`, `AddColumnCall(name, columnSpec)`,
and `RecreateTableCall({ tableName, contractTable: SqliteTableSpec,
schemaColumnNames, indexes, issues, operationClass })` carry only
flat data. `renderTypeScript()` on each is now a one-liner over
`jsonToTsSource(spec)` — the rendered scaffold is fully
self-contained.
- Inline `INTEGER PRIMARY KEY AUTOINCREMENT` is encoded as a flag on
the column spec; the table-level PK clause skips it. Detection
lives in `isInlineAutoincrementPrimaryKey` in
`planner-ddl-builders.ts`.
- `RecreateTableCall` now receives pre-merged `indexes` (declared +
FK-backing, deduped by column-set) and `schemaColumnNames` for the
data-copy column list, instead of the full `SqlTableIR`.
Postchecks for type/nullability/default mismatches read directly from
the embedded `SqliteColumnSpec` (via `typeSql.toLowerCase()` and the
pre-rendered `defaultSql`), so the recreate factory no longer needs
to consult the original `StorageColumn`.
2. Shared utilities moved from adapter-sqlite to target-sqlite to break
the workspace dependency cycle.
target-sqlite imported `quoteIdentifier`, `escapeLiteral`,
`parseSqliteDefault`, `normalizeSqliteNativeType`, and `CodecTypes`
from adapter-sqlite, while adapter-sqlite needed target-sqlite's new
subpath exports for the round-trip test. That pair created a
bidirectional workspace dep that turbo refused to plan.
Postgres avoids the cycle by hosting the foundational utilities in
target-postgres (one-way edge: adapter → target). SQLite now does the
same. Moved from `adapter-sqlite/src/core` → `target-sqlite/src/core`:
- `sql-utils.ts` (quoteIdentifier, escapeLiteral, SqlEscapeError)
- `codec-ids.ts`
- `codecs.ts` (CodecTypes, JsonValue, codecDefinitions, dataTypes)
- `default-normalizer.ts` (extracted from control-adapter.ts)
- `native-type-normalizer.ts` (extracted)
target-sqlite gains subpath exports for these plus
`op-factory-call`, `planner`, `planner-produced-sqlite-migration`,
`planner-target-details`, `render-ops`, `statement-builders` — all
matching the postgres surface.
adapter-sqlite imports them via `@prisma-next/target-sqlite/*`.
`adapter-sqlite/control` and `adapter-sqlite/codec-types` re-export
the same symbols so the demo, e2e harness, and generated contracts
keep working without changes.
Integration tests that exercise full target↔adapter↔driver wiring
(runner.basic, runner.errors, runner.idempotency, runner-integration,
plus shared fixtures) moved from `target-sqlite/test` to
`adapter-sqlite/test/migrations` — matching where Postgres puts the
equivalents.
Renderer fixes uncovered while aligning with Postgres:
- `Migration.run(import.meta.url, M)` was emitted by the renderer but
the method didn't exist. Postgres emits `MigrationCLI.run(...)` and
re-exports `MigrationCLI` from `target-postgres/migration`. SQLite now
matches.
- `enum_values_changed` had no explicit handler in `mapIssueToCall` and
fell through to a generic `unsupportedOperation` conflict. Now
explicitly returns `ok([])` with a comment about `sql.enums: false`.
- Dropped the redundant `Object.freeze` wrapper around the planner
success result.
New round-trip test: `adapter-sqlite/test/migrations/render-typescript.roundtrip.test.ts`
mirrors postgres's. It builds calls directly, wraps them in
`TypeScriptRenderableSqliteMigration`, rewrites the bare import to a
`file://` URL into the live workspace, runs the rendered scaffold via
`tsx`, and asserts `ops.json` deep-equals `renderOps(calls)`. Three
cases: full additive (CREATE TABLE with inline AUTOINCREMENT PK +
unique + add column + create index + drop table); empty calls list;
RecreateTableCall.
Verification:
- target-sqlite: 77 unit tests pass
- adapter-sqlite: 108 tests pass (codecs + control-adapter + adapter +
18 moved runner tests + 3 new round-trip tests)
- e2e migrations: 31 tests pass
- prisma-next-demo-sqlite: 21 tests pass
- pnpm lint (turbo, all 65 packages): clean — cycle is gone
… _prisma_marker The runtime adapter's readMarkerStatement was repointed to _prisma_marker in d9001c8, but the sql-builder e2e fixture still seeded the old prisma_contract_marker name and schema, so verifyPlanIfNeeded failed with 'no such table: _prisma_marker'. Match the runner-created schema (INTEGER PRIMARY KEY CHECK (id = 1)).
…n adapter target-sqlite's runner.ts (591 lines), statement-builders.ts, codecs.ts, and other foundational files moved in c5851d5 to break a workspace cycle. Their integration tests run from adapter-sqlite/test/migrations under a separate vitest config, so the per-package coverage report doesn't see them and the threshold (79/65/88/79, matching Postgres) fails at ~56%. Mirror the equivalent Postgres warning entry with a 90-day expiry.
Addresses the CodeRabbit comments that the human reviewer didn't
already mark resolved.
- demo/db.ts: drop the .d extension from the Contract import per the
no-extensions rule.
- issue-planner: replace 'as unknown as' with structural ('tableName' in
call) narrowing.
- adapter-sqlite codec-types facade: align the doc comment with the
actual re-export path and drop the 'preserve backward-compat' framing.
- target-sqlite runner: surface JSON parse failures from readMarker
instead of silently coercing strings into Record<string, unknown>;
drop the unused safeJsonParse helper.
- planner-ddl-builders: throw a clear error on unresolved typeRef
instead of falling back to a column with undefined nativeType (which
later threw an opaque toUpperCase-of-undefined).
- default-normalizer: tighten HEX_PATTERN to disallow leading minus (so
a non-integer column with '-0xff' default no longer produces NaN);
only strip outer parens when they form a single matched wrapping pair
so composite expressions like '(a)+(b)' survive; export
stripOuterParens for reuse.
- recreateTable: skip the INSERT...SELECT copy step when no columns are
shared (instead of emitting invalid 'INSERT INTO tmp () SELECT FROM
old').
- recreateTable nullability postcheck: only emit when issue.expected is
exactly 'true' or 'false' so a typo upstream can't silently invert
the wantNotNull semantic.
- recreateTable default postcheck: strip outer parens from expectedRaw
to match SQLite's pragma_table_info.dflt_value normalization (was
failing for function defaults like 'datetime(\'now\')').
- runner.idempotency.test: replace 'SELECT 1/0' with
'SELECT raise(FAIL, ...)' since SQLite returns NULL for divide-by-
zero, hiding regressions.
- fk-preservation.test: assert the planner actually emitted
recreateTable.User; harness now exposes plannedOperationIds so future
changes that suppress recreate fail this test instead of silently
passing on the unchanged table.
- data-transform.ts: rewrite the misleading 'lazy' docstring; the
factory invokes opts.run() eagerly (planner stubs handle deferral via
DataTransformCall.renderTypeScript).
- adapter-sqlite/control: drop the 'backward-compat' framing in the
facade comment and document why SqliteControlAdapter is still exposed
(until the upstream SqlControlAdapterDescriptor narrowing is
reconciled).
- runner-integration.test: import SqliteControlAdapter from the
package-internal core path instead of through the public exports.
Comments dismissed by the human reviewer (LIKE escaping in the demo,
node:path-vs-pathe in the demo, ADD COLUMN NOT NULL in columns.ts,
.all/.run/.exec split in the e2e harness, and the CodeQL improper-
code-sanitization alert) are preserved as-is.
The render-typescript round-trip test invokes 'tsx migration.ts' which pays the full cold-transform cost on a fresh worker. typeScriptCompilation (8s base) doubled to 16s on CI was a hair too tight: the first test in the suite consistently took ~16.1s and timed out. Switch to coldTransformImport (30s base / 60s on CI) which is the documented 'heavy module dynamic import' bucket — same bucket Postgres should arguably also be in, though it currently fits inside the tighter limit because its dependency graph is smaller.
…tion files The file 'runner-integration.test.ts' was misnamed: nothing in it exercised the migration runner (no BEGIN EXCLUSIVE, no marker / ledger writes, no idempotent re-run, no FK integrity check). Those paths are covered by the runner.basic / runner.errors / runner.idempotency siblings. The two describe blocks here actually cover: - planner unit tests against synthetic contracts and schemas, and - planner + adapter introspection round-trip: feed planner-emitted DDL to a real SQLite database, then read it back through SqliteControlAdapter.introspect() and compare. Split into two clearly-scoped files (planner.test.ts and planner-introspection.integration.test.ts) and wrap the integration tests' driver lifecycle in try/finally so a failed assertion no longer leaks the in-memory database handle.
The SQLite demo grew into a near-mirror of the Postgres demo with 17 ORM
examples + 8 SQL builder queries + 3 in-demo test files. The tests
re-asserted behaviour already covered by test/e2e/framework/test/sqlite/
and the sql-orm-client / sql-builder integration suites.
Trim the demo to a focused minimal surface:
- ORM client: simple read (find-user-by-id), relational include
(get-user-posts now uses User.include('posts', ...).first()), and a
write (create-user)
- SQL builder: simple read (get-users) and a write
(dml-operations.insertUser)
Drop everything else: dashboards, cursors, custom collections (.admins(),
.byEmail(), …), combine() insights, group-by/having, upsert,
create-user-with-address, the no-emit workflow (src/prisma-no-emit/ +
main-no-emit.ts), and the whole test/ directory. ORM and SQL builder
semantics are tested at the framework / package level — the demo no
longer doubles as a regression suite.
Trim Contract: drop User.kind (only used by dropped admin / breakdown
helpers) and User.address (only used by dropped create-user-with-address).
Keep User and Post + the User → Post.userId FK so the relational ORM
example still has something to traverse. Re-emit contract.json /
contract.d.ts.
Trim package.json: drop test, db:drop, start:no-emit scripts and the
vitest dev-deps. Drop scripts/drop-db.ts and vitest.config.ts.
Update coverage.config.json: the target-sqlite warning entry no longer
references the demo's tests (gone) and points at the
planner-introspection.integration test (renamed earlier in this branch).
…ugh lowerDbgenerated
parseSqliteDefault rewrites stored 'CURRENT_TIMESTAMP', "datetime('now')",
and 'datetime("now")' to the canonical { function 'now()' } shape
(default-normalizer.ts:60-62). lowerDbgenerated, however, kept the user's
expression verbatim — so a contract written as dbgenerated("CURRENT_TIMESTAMP")
ended up with { function 'CURRENT_TIMESTAMP' } and drifted permanently
against the schema it had just produced. The runner's post-execute
verifySqlSchema then rolled back the migration, so users of that PSL
default literally couldn't apply their initial migration.
Make lowerDbgenerated symmetric: when the argument is one of the SQLite
synonyms for wall-clock now (CURRENT_TIMESTAMP, current_timestamp,
datetime('now'), datetime("now"), or now() itself), canonicalize to
{ function 'now()' } before storing in the contract. Unknown expressions
are still preserved verbatim.
Also tighten the case where dbgenerated's argument is whitespace-padded
(e.g. dbgenerated(" CURRENT_TIMESTAMP ")) — store the trimmed value
so it matches what the introspection side will produce.
Tests:
- adapter-sqlite/test/control-mutation-defaults.test.ts (new): 4 unit
tests on the registry's 'dbgenerated' handler covering the synonym
canonicalization and the unknown-expression passthrough.
- test/e2e/framework/test/sqlite/migrations/widening.test.ts: positive
round-trip — author a contract with defaultSql('now()'), apply, and
assert the introspected default is the SQLite-native datetime('now')
spelling (the runner's verifySqlSchema already proves the canonical
equivalence; this assertion just pins the storage form).
…ld summary + postchecks at planner
RecreateTableCall used to carry a 'readonly issues: SchemaIssue[]' field
that the recreateTable factory then re-walked at toOp() time to format
the operation summary and to emit per-issue postchecks. That meant the
IR — and the rendered authoring scaffold — leaked a verifier-time
concept (SchemaIssue) into the user-facing migration.ts surface.
Pre-compute both at the planner side and pass flat data to the call:
- Move the description formatting into a small exported helper,
buildRecreateSummary(tableName, issues), in operations/tables.ts.
- Rename buildIssuePostchecks to buildRecreatePostchecks and export it
from operations/tables.ts so the planner can pre-build the postcheck
list (still a Step[] of { description; sql }).
- recreateTable factory now takes 'summary: string' and
'postchecks: readonly Step[]' instead of 'issues'.
- RecreateTableCall stores those flat fields directly. SchemaIssue
import is gone from op-factory-call.ts.
- recreateTableStrategy in planner-strategies.ts calls the two helpers
with entry.issues at the construction site.
The rendered scaffold's call shape becomes
recreateTable({ summary: '…', postchecks: [...], … })
instead of
recreateTable({ issues: [...], … })
which is what the user sees in their migration.ts.
Updated tests pass synthetic summary/postchecks instead of synthetic
issue arrays. All 281 sqlite tests across target-sqlite, adapter-sqlite,
and the migrations e2e suite remain green.
…ostrophe-default e2e regression The migration ops had two functions doing the same job: operations/shared.ts:12-14 esc(value: string): string sql-utils.ts:38-47 escapeLiteral(value: string): string Both double single quotes for embedding in SQL string literals. The only difference was that escapeLiteral rejects NUL bytes via SqlEscapeError, while esc accepted them silently. Drop esc and switch every call site (operations/columns.ts, operations/indexes.ts, operations/tables.ts) to escapeLiteral so the NUL-rejection check applies uniformly across migration step SQL. Also add a widening e2e regression that round-trips a string default containing an apostrophe through recreate-table — covers the path where the recreate-table postcheck builder applies escapeLiteral on top of an already-doubled SQL literal (text default 'It''s'). SQLite collapses the doubled quotes back when parsing the outer literal so the comparison against pragma_table_info.dflt_value matches; this test pins that round-trip.
parseSqliteDefault returned integer-affinity defaults as JS `string`
('42'), but contract literals authored with `.default(42)` are JS
`number`. The verifier's `literalValuesEqual` does no cross-type
coercion, so every contract with a numeric default reported
`default_mismatch` on every plan.
Mirror `parsePostgresDefault`'s bigint handling: parse as JS `number`
when the value is in the safe-integer range, fall back to the raw
text only for SQLite's 64-bit integers that exceed JS's safe range.
SQLite has no native boolean type — booleans were previously stored as INTEGER 0/1 but exposed through a dedicated `sqlite/boolean@1` codec that translated JS `boolean` ↔ wire `number`. The codec hid the underlying integer affinity and produced a default-drift footgun (literal 0/1 in the schema vs JS true/false in the contract). Drop the codec, the `booleanColumn` descriptor, and the PSL `Boolean → sqlite/boolean@1` mapping. Authors model boolean fields as `integerColumn` (or PSL `Int`) with explicit 0/1 values — same shape as on the wire, no implicit JS coercion. Also fixes the now-stale `control-adapter.test.ts` assertion that integer defaults parse to a string (the Postgres-equivalent integer-default fix landed in the prior commit).
- issue-planner: surface enum_values_changed as a verifier-bug conflict
instead of silently returning ok([]) — SQLite has sql.enums: false, so
receiving one means the verifier emitted a wrong issue.
- op-factory-call: take id/label as required args on DataTransformCall.
The op is generic; baking in "backfill"-flavored strings forced every
caller to look like a backfill. Caller in
nullabilityTighteningBackfillStrategy now passes the same strings it
used to rely on.
- planner: refresh JSDoc to drop the per-strategy enumeration. Strategies
can compose and may be user-provided in the future, so describing the
contract instead of listing strategies keeps the doc honest.
- runner / family-sql verify: drop the inline marker-row type and extend
parseContractMarkerRow to also parse JSON-string contract_json (SQLite
stores it as TEXT; Postgres returns it pre-parsed). New ContractMarkerRow
type is exported from @prisma-next/family-sql/verify and reused by the
SQLite runner.
- demo main.ts: replace `process.exit(1)` inside the try/catch with
`process.exitCode = 1; return;` so the `finally { runtime.close() }`
always runs.
- adapter-sqlite render-typescript.roundtrip test: guard the `afterEach`
cleanup so a setup failure isn't masked by an `rm(undefined, …)` error.
`buildRecreatePostchecks` previously only covered column-level issues (nullability/default/type/extra_default), so a recreated table with the right columns but the wrong primary key, unique, or foreign-key shape would pass the postcheck and report success silently. Widen the helper to take the full SqliteTableSpec (so it can read the contract's PK/uniques/FKs) and emit one postcheck per declared constraint when an issue of the matching kind fires: - primary key: pragma_table_info shows exactly the expected columns with pk > 0 (or zero columns for "no PK"). - unique: for each contract unique, exists a unique index in pragma_index_list whose pragma_index_info covers exactly that column set. - foreign key: for each contract FK, pragma_foreign_key_list contains a matching from/to row group (works for single- and multi-column FKs via SUM(CASE WHEN (from,to) IN (…))). Also adds a target-sqlite unit test (recreate-postchecks.test.ts) asserting the SQL shape per kind, and an e2e regression that introduces a new FK on an existing column under the destructive policy — exercises the new FK postcheck end-to-end.
…ite marker main added a `marker.invariants` column to the contract-marker schema while the SQLite branch was repairing the marker/control-adapter seam. Their intersection wasn't covered in any single rebased commit, so this lands the SQLite-side support for invariants: - `_prisma_marker` CREATE TABLE gains an `invariants` TEXT column with `'[]'` default (JSON-encoded array — SQLite has no native array type). - `readMarkerStatement` and `buildWriteMarkerStatements` select / write the column. `WriteMarkerInput.invariants` is now required. - `SqliteMigrationRunner.upsertMarker` merges existing + incoming invariants client-side under the `BEGIN EXCLUSIVE` transaction (no SQL- side merge, unlike Postgres's array(...) trick). - `SqliteMigrationRunner.readMarker` and `SqliteControlAdapter.readMarker` JSON-decode the invariants TEXT before delegating to the shared `parseContractMarkerRow` schema, which expects `string[]`. - `ContractMarkerRow` (in `family-sql/verify`) widens `invariants` to `unknown` so each target can hand the wire shape to the parser without a cast. - `PostgresControlAdapter.readMarker` now selects `invariants` (it was missing post-rebase because the d9001c8/main intersection dropped it). - Postgres integration test and integration tests' `family.sign-database` switch from the removed `readMarker(driver)` standalone helper to the per-adapter / familyInstance method already in use elsewhere. - Export `PostgresControlAdapter` from `@prisma-next/adapter-postgres/control` to mirror `SqliteControlAdapter`'s export.
472497f to
b6114a0
Compare
The runner.basic.integration test imported PostgresControlAdapter via the public package subpath `@prisma-next/adapter-postgres/control`, which forced typecheck to depend on the package's own built `dist/` — turbo's typecheck task graph doesn't gate self-typecheck on self-build, so CI failed with TS2307 on a clean checkout. Switch to a relative `../../src/core/control-adapter` import (matching the sqlite test convention) so typecheck stands alone.
closes [TML-2168](https://linear.app/prisma-company/issue/TML-2168/support-sqlite-migrations) ## Intent Complete the SQLite target's control plane — migration planner, runner, schema introspection, PSL type mappings, and TypeScript authoring surface — so `db init` / `db update` work against SQLite databases using the same contract-driven workflow as Postgres. The planner now mirrors Postgres's strategies + IR architecture (issue-based planning, flat call specs, recreate-table for non-additive changes), and a port of `prisma-next-demo` to SQLite shakes out a real cross-target seam — marker reads were hardcoded to Postgres SQL in `family-sql/verify`, so any non-Postgres `dbInit` failed before reaching its own runner. That gets fixed adapter-side as part of this PR. ## Change map | Area | What changed | Why | |------|-------------|-----| | **Planner architecture** | Thin `planner.ts` wraps `planIssues`; cohesive recipes live in `planner-strategies.ts` (recreate-table, nullability backfill); per-issue defaults in `mapIssueToCall`; result is a `SqliteOpFactoryCall[]` IR | Mirrors Postgres so SQLite plans satisfy `MigrationPlanWithAuthoringSurface` (ADR 194), unblocking class-flow authoring (ADR 193) and ops.json scaffolding (ADR 192) | | **Recreate-table** | Single op per table absorbs type/nullability/default/constraint mismatches; preserves FK-backing indexes; runner toggles `foreign_keys` OFF outside the transaction and runs `PRAGMA foreign_key_check` before commit | SQLite `ALTER TABLE` is too limited for these changes; FK preservation prevents cascade-deletes during `DROP TABLE` of a referenced parent | | **Operation factories** | `createTable`, `addColumn`, `recreateTable` now consume flat specs (`SqliteColumnSpec`, `SqliteTableSpec`, …) resolved once at the issue-planner boundary; `*Call` IR carries serializable data only | Makes `renderTypeScript()` a one-liner over `jsonToTsSource(spec)`, so the rendered scaffold is fully self-contained — same shape Postgres uses | | **Runner** | `BEGIN EXCLUSIVE` for locking, `_prisma_marker` / `_prisma_ledger` control tables (TEXT for JSON/timestamps), idempotent re-runs (postchecks satisfied → skip), per-op error codes (`FOREIGN_KEY_VIOLATION` for integrity-check failures), schema verification before commit | SQLite has no advisory locks; marker schema now uses `INTEGER PRIMARY KEY CHECK (id = 1)` so a stray second row is rejected at the database level | | **Schema introspection** | `SqliteControlAdapter.introspect()` reads `sqlite_master` + PRAGMAs (`table_info`, `foreign_key_list`, `index_list`, `index_info`); filters control tables out so they don't surface as `extra_table` issues | Required for both the planner's diff and the runner's post-migration verification | | **Default parsing** | `parseSqliteDefault` normalizes stored defaults (strips parens, maps `datetime('now')` → `now()`, handles numeric/string/null literals) | Lets schema verification compare introspected defaults against contract defaults | | **PSL type mappings** | `control-mutation-defaults.ts` maps PSL scalars → SQLite affinities/codecs (`Boolean → integer`, `DateTime → text`, `Json → text`) and lowers default functions (autoincrement, now, uuid, cuid, ulid, nanoid, dbgenerated) | Required for `target = "sqlite"` in PSL to emit correct contracts | | **TS authoring surface** | `renderCallsToTypeScript` + `TypeScriptRenderableSqliteMigration` emit a runnable `migration.ts` with `MigrationCLI.run(import.meta.url, M)`; round-trip test executes the rendered file via `tsx` and asserts `ops.json` deep-equals `renderOps(calls)` | SQLite now matches Postgres's authoring surface so the demo's emitted migrations actually run | | **Cross-target seam: `readMarker`** | Moved from `family-sql/verify` (Postgres-only SQL) to `SqlControlAdapter.readMarker(driver)`; `Postgres` and `SQLite` adapters each implement their own probe + read | The hardcoded `information_schema.tables` + `prisma_contract.marker` SQL was breaking SQLite `dbInit` before the runner even started | | **Demo** | New `examples/prisma-next-demo-sqlite/` mirrors `prisma-next-demo` against `@prisma-next/sqlite` (TS-authored contract + emit/no-emit workflows, ORM and SQL DSL examples, integration tests on a temporary file-backed DB); README documents the diff vs Postgres demo (no `distinctOn` / `ilike` / `pgvector` / discriminator polymorphism) | Validates the SQLite target end-to-end and is the vehicle that surfaced the marker seam and several other half-wired pieces | | **Architecture cleanup** | Foundational utilities (`sql-utils`, `codec-ids`, `codecs`, `default-normalizer`, `native-type-normalizer`) relocate from `adapter-sqlite` → `target-sqlite`; full-stack runner integration tests move from `target-sqlite/test` → `adapter-sqlite/test/migrations` | Breaks a workspace dep cycle (`adapter ↔ target`); matches Postgres layering exactly | ## The story This branch finishes the SQLite target. The runtime plane (driver, adapter, codecs, query builder, ORM) was already in place; this PR adds the control plane and a real consumer (the demo) to validate the whole stack. The planner is the centerpiece. The first cut was a monolithic per-table walker that emitted CREATE TABLE / ADD COLUMN / CREATE INDEX directly. That worked for additive migrations but not for type/nullability/default changes — SQLite's `ALTER TABLE` can't do most of them — so the recreate-table strategy was added: detect mismatches, then in a single op create a new table with the contract shape, copy data, drop the old, rename the new. To make recreate-table safe, the runner toggles `PRAGMA foreign_keys` OFF outside the transaction (the pragma is a no-op inside one) and runs `PRAGMA foreign_key_check` before commit; the planner re-emits FK-backing indexes alongside declared indexes so they survive the rebuild. A later refactor pulls the planner into the same shape as Postgres — a thin wrapper over `planIssues`, with cohesive recipes living in `planner-strategies.ts`. `recreateTableStrategy` collapses all per-column issues for a table into one op; `nullabilityTighteningBackfillStrategy` mirrors Postgres's behaviour, emitting a `DataTransformCall` stub the user fills with `UPDATE … WHERE col IS NULL` before the recreate copies data into the tightened schema. The result is a `SqliteOpFactoryCall[]` IR consumed by both the runtime ops view (`renderOps`) and the TypeScript authoring surface (`renderCallsToTypeScript`). A round-trip test in `adapter-sqlite/test/migrations/render-typescript.roundtrip.test.ts` builds calls, renders them to a file, executes the file via `tsx`, and asserts the produced `ops.json` deep-equals `renderOps(calls)`. The demo port (`examples/prisma-next-demo-sqlite/`) is the integration test for the whole thing. It mirrors the Postgres demo's contract, ORM-client, SQL DSL, and middleware examples, and runs a real `dbInit` against a temporary file-backed SQLite database in its integration suite. While porting it, `dbInit` blew up against `information_schema.tables` — the family's `readMarker` was hardcoded to Postgres SQL. The fix moves marker reads to the adapter: `SqlControlAdapter.readMarker(driver)` is now part of the interface, each target implements its own probe + read, and `family-sql/verify` no longer carries Postgres-specific SQL. `PostgresMigrationRunner` switches from the deleted helper to `family.readMarker({ driver })`. SQLite's implementation probes `sqlite_master` and reads `_prisma_marker`. The demo also dropped queries that don't fit SQLite (pgvector similarity, `distinctOn`, `@@discriminator` polymorphism, `@@enum`, `ilike`, budget-violation guardrails — the budget middleware trips on the ORM's N+1 include strategy when LATERAL is unavailable); the README documents these trade-offs. A late refactor relocates foundational utilities from `adapter-sqlite/src/core` to `target-sqlite/src/core` (`sql-utils`, `codec-ids`, `codecs`, `default-normalizer`, `native-type-normalizer`), exposes them as subpath exports, and moves full-stack runner integration tests from `target-sqlite/test` to `adapter-sqlite/test/migrations`. This breaks a workspace cycle (`adapter ↔ target`) that turbo refused to plan and matches Postgres's one-way `adapter → target` edge. `adapter-sqlite/control` and `adapter-sqlite/codec-types` re-export the same symbols so the demo, e2e harness, and generated contracts keep working. Two smaller hardenings rounded the work out. The marker singleton invariant is now schema-enforced — `_prisma_marker.id` was `INTEGER PRIMARY KEY DEFAULT 1` with the "only row 1 exists" rule encoded only in the runner's `WHERE id = 1`; replaced with `INTEGER PRIMARY KEY CHECK (id = 1)` so a stray second row is rejected at the database level. And a dead `sqliteControlAdapterDescriptor` default export (no `controlMutationDefaults`, no `scalarTypeDescriptors`) was removed from `control-adapter.ts`; `exports/control.ts` is now the single canonical adapter descriptor. The 1300-line E2E test file was split into `harness.ts` + four focused files (`additive.test.ts`, `destructive.test.ts`, `widening.test.ts`, `fk-preservation.test.ts`) — same 31 cases, each file browseable without scrolling. ## Behavior changes & evidence | Change | Evidence | |--------|----------| | `createPlanner()` / `createRunner()` callable on the SQLite target descriptor; full lifecycle works on a real file-backed DB | [runner-integration.test.ts](packages/3-targets/6-adapters/sqlite/test/migrations/runner-integration.test.ts) | | Planner emits correct DDL with inline AUTOINCREMENT PKs, FKs, uniques, defaults | [planner-ddl-builders.test.ts](packages/3-targets/3-targets/sqlite/test/planner-ddl-builders.test.ts) | | Recreate-table preserves FKs and indexes through table rebuild | [test/sqlite/migrations/fk-preservation.test.ts](test/e2e/framework/test/sqlite/migrations/fk-preservation.test.ts) | | Widening (nullable → NOT NULL with backfill, default changes) goes through recreate-table | [test/sqlite/migrations/widening.test.ts](test/e2e/framework/test/sqlite/migrations/widening.test.ts) | | Destructive ops (DROP TABLE, DROP COLUMN, DROP INDEX, type changes) work end-to-end | [test/sqlite/migrations/destructive.test.ts](test/e2e/framework/test/sqlite/migrations/destructive.test.ts) | | Runner is idempotent — re-running the same plan skips already-applied operations | [runner.idempotency.test.ts](packages/3-targets/6-adapters/sqlite/test/migrations/runner.idempotency.test.ts) | | Runner surfaces precheck failure, execution failure, policy violation, marker mismatch, destination mismatch | [runner.errors.test.ts](packages/3-targets/6-adapters/sqlite/test/migrations/runner.errors.test.ts) | | Issue-based planner emits expected calls per issue kind | [issue-planner.test.ts](packages/3-targets/3-targets/sqlite/test/migrations/issue-planner.test.ts), [planner-strategies.test.ts](packages/3-targets/3-targets/sqlite/test/migrations/planner-strategies.test.ts) | | TS-rendered `migration.ts` runs via `tsx` and reproduces `ops.json` | [render-typescript.roundtrip.test.ts](packages/3-targets/6-adapters/sqlite/test/migrations/render-typescript.roundtrip.test.ts) | | Introspection round-trips: create schema → introspect → verify IR matches | [control-adapter.test.ts](packages/3-targets/6-adapters/sqlite/test/control-adapter.test.ts) | | `readMarker` adapter contract works against Postgres + SQLite without Postgres-specific SQL leaking into the family | [family.sign-database.test.ts](test/integration/test/family.sign-database.test.ts), demo's `dbInit` flow | | `prisma-next-demo-sqlite` runs the same ORM/SQL DSL examples as the Postgres demo | [examples/prisma-next-demo-sqlite/test/repositories.integration.test.ts](examples/prisma-next-demo-sqlite/test/repositories.integration.test.ts) | ## Compatibility / migration / risk - **No user-visible breaking changes.** SQLite is new; the `readMarker` move is internal — the only external caller (`PostgresMigrationRunner`) is updated in the same PR. - **Family-SQL contract change**: `SqlControlAdapter.readMarker` is now a required method. Any downstream adapter not in this PR would need to implement it (only Postgres + SQLite exist today). - **Workspace deps**: `target-sqlite` adds runtime deps on `@prisma-next/family-sql`, `@prisma-next/sql-schema-ir`, `@prisma-next/sql-errors`, `@prisma-next/utils`. `adapter-sqlite` now depends on `@prisma-next/target-sqlite/*` subpath exports (cycle eliminated; one-way edge `adapter → target` matches Postgres). - **Demo policy trade-offs**: `prisma-next-demo-sqlite` drops queries that depend on `distinctOn`, `ilike`, `pgvector`, `@@discriminator`, `@@enum`, and the budget-violation guardrails. The README documents each trade-off; nothing about the SQLite target itself is downgraded. - **Test coverage thresholds**: `target-sqlite` thresholds now locked at 79/65/88/79 (stmts/branches/funcs/lines), matching Postgres. All 65 packages green under `pnpm lint` (turbo). ## Follow-ups / open questions - `:memory:` database support — out of scope, file-only for now. - `sql-lane` (legacy) and `kysely-lane` SQLite — explicitly out of scope. - WAL mode configuration API and SQLite extensions loading — capability declared, not yet wired. - Migration `DOWN` operations — not in this PR. - Distributed/replicated SQLite (LiteFS, Turso) — future target variant. ## Non-goals / intentionally out of scope - Migration `DOWN` operations. - `:memory:` SQLite databases. - `sql-lane` / `kysely-lane` SQLite support. - FTS5 / R*Tree extension support. - WAL configuration / extension loading APIs. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added a complete SQLite example app (ORM + SQL builder), CLI seed/utility commands, and sample data. * Implemented a full SQLite migration system: planner, renderer, runnable migrations, runner with marker/ledger support, idempotency, and foreign-key violation checks. * Exposed migration authoring surface and richer migration operation types (including data-transform/backfill). * **Documentation** * Added README and config examples for the SQLite demo. * **Tests** * Extensive unit, integration, and end-to-end SQLite migration test suites added. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
…nts (M3 R4 T3.9)
Three amendments to cipherstash-migration.spec.md draining the M3
R1+R3+R4 deviation backlog into the canonical sub-spec:
- § 1 TS-authored layout (M3 R1 deviation): document that the
package authors contract + migrations directly in TypeScript
under src/core/ rather than committing pre-rendered .json files.
Both authoring styles produce the same ExtensionMigrationPackage
shape; the TS approach co-locates constants with the values that
consume them, which keeps the FR11 invariantId immutability
surface visible in code review, and treats the vendored EQL
bundle in eql-install.generated.ts as the byte-for-byte source
of truth.
- § 3 structural-ops × bundle-CREATEs conflict resolution
(M3 R3, option (c)): document that the EQL bundle owns the
typed-object DDL; structural cipherstash:create-*-v1 ops keep
their stable invariantIds (so verifier's invariantsMismatch gate
passes) but their execute[] is no-op SELECT 1. Future
IR-vocabulary expansion will give them real verification work.
- § 3 constants drift cleanup (M3 R4 item 22, FR11 pre-publication):
document the EQL_V2_ORE_COMPOSITE_TYPES sync (added
ore_block_u64_8_256_term + ore_cllw_var_8; fixed cclw -> cllw
typo) and the cipherstashFutureIR.enums sync (4 enum values:
active/inactive/encrypting/pending). Pre-publication so FR11
immutability not violated.
- § 6 Scenario D vacuously satisfied (M3 R4 T3.8 audit finding):
no cipherstash-specific strictVerification: false flag exists in
packages/ or examples/ today. All extant matches are orthogonal
(M2 R5 intentional per-space mechanism / mongo synthetic-contract
fixtures / pre-existing SQL adapter test fixtures from PR #386
+ #404). The "first attempt" workaround NFR1 wanted to revert
lived only in the abandoned projects/cipherstash-integration/
design and never landed in workspace packages. NFR1 / TC-23 /
AC-13 vacuously held.
…nts (M3 R4 T3.9)
Three amendments to cipherstash-migration.spec.md draining the M3
R1+R3+R4 deviation backlog into the canonical sub-spec:
- § 1 TS-authored layout (M3 R1 deviation): document that the
package authors contract + migrations directly in TypeScript
under src/core/ rather than committing pre-rendered .json files.
Both authoring styles produce the same ExtensionMigrationPackage
shape; the TS approach co-locates constants with the values that
consume them, which keeps the FR11 invariantId immutability
surface visible in code review, and treats the vendored EQL
bundle in eql-install.generated.ts as the byte-for-byte source
of truth.
- § 3 structural-ops × bundle-CREATEs conflict resolution
(M3 R3, option (c)): document that the EQL bundle owns the
typed-object DDL; structural cipherstash:create-*-v1 ops keep
their stable invariantIds (so verifier's invariantsMismatch gate
passes) but their execute[] is no-op SELECT 1. Future
IR-vocabulary expansion will give them real verification work.
- § 3 constants drift cleanup (M3 R4 item 22, FR11 pre-publication):
document the EQL_V2_ORE_COMPOSITE_TYPES sync (added
ore_block_u64_8_256_term + ore_cllw_var_8; fixed cclw -> cllw
typo) and the cipherstashFutureIR.enums sync (4 enum values:
active/inactive/encrypting/pending). Pre-publication so FR11
immutability not violated.
- § 6 Scenario D vacuously satisfied (M3 R4 T3.8 audit finding):
no cipherstash-specific strictVerification: false flag exists in
packages/ or examples/ today. All extant matches are orthogonal
(M2 R5 intentional per-space mechanism / mongo synthetic-contract
fixtures / pre-existing SQL adapter test fixtures from PR #386
+ #404). The "first attempt" workaround NFR1 wanted to revert
lived only in the abandoned projects/cipherstash-integration/
design and never landed in workspace packages. NFR1 / TC-23 /
AC-13 vacuously held.
…nts (M3 R4 T3.9)
Three amendments to cipherstash-migration.spec.md draining the M3
R1+R3+R4 deviation backlog into the canonical sub-spec:
- § 1 TS-authored layout (M3 R1 deviation): document that the
package authors contract + migrations directly in TypeScript
under src/core/ rather than committing pre-rendered .json files.
Both authoring styles produce the same ExtensionMigrationPackage
shape; the TS approach co-locates constants with the values that
consume them, which keeps the FR11 invariantId immutability
surface visible in code review, and treats the vendored EQL
bundle in eql-install.generated.ts as the byte-for-byte source
of truth.
- § 3 structural-ops × bundle-CREATEs conflict resolution
(M3 R3, option (c)): document that the EQL bundle owns the
typed-object DDL; structural cipherstash:create-*-v1 ops keep
their stable invariantIds (so verifier's invariantsMismatch gate
passes) but their execute[] is no-op SELECT 1. Future
IR-vocabulary expansion will give them real verification work.
- § 3 constants drift cleanup (M3 R4 item 22, FR11 pre-publication):
document the EQL_V2_ORE_COMPOSITE_TYPES sync (added
ore_block_u64_8_256_term + ore_cllw_var_8; fixed cclw -> cllw
typo) and the cipherstashFutureIR.enums sync (4 enum values:
active/inactive/encrypting/pending). Pre-publication so FR11
immutability not violated.
- § 6 Scenario D vacuously satisfied (M3 R4 T3.8 audit finding):
no cipherstash-specific strictVerification: false flag exists in
packages/ or examples/ today. All extant matches are orthogonal
(M2 R5 intentional per-space mechanism / mongo synthetic-contract
fixtures / pre-existing SQL adapter test fixtures from PR #386
+ #404). The "first attempt" workaround NFR1 wanted to revert
lived only in the abandoned projects/cipherstash-integration/
design and never landed in workspace packages. NFR1 / TC-23 /
AC-13 vacuously held.
…nts (M3 R4 T3.9)
Three amendments to cipherstash-migration.spec.md draining the M3
R1+R3+R4 deviation backlog into the canonical sub-spec:
- § 1 TS-authored layout (M3 R1 deviation): document that the
package authors contract + migrations directly in TypeScript
under src/core/ rather than committing pre-rendered .json files.
Both authoring styles produce the same ExtensionMigrationPackage
shape; the TS approach co-locates constants with the values that
consume them, which keeps the FR11 invariantId immutability
surface visible in code review, and treats the vendored EQL
bundle in eql-install.generated.ts as the byte-for-byte source
of truth.
- § 3 structural-ops × bundle-CREATEs conflict resolution
(M3 R3, option (c)): document that the EQL bundle owns the
typed-object DDL; structural cipherstash:create-*-v1 ops keep
their stable invariantIds (so verifier's invariantsMismatch gate
passes) but their execute[] is no-op SELECT 1. Future
IR-vocabulary expansion will give them real verification work.
- § 3 constants drift cleanup (M3 R4 item 22, FR11 pre-publication):
document the EQL_V2_ORE_COMPOSITE_TYPES sync (added
ore_block_u64_8_256_term + ore_cllw_var_8; fixed cclw -> cllw
typo) and the cipherstashFutureIR.enums sync (4 enum values:
active/inactive/encrypting/pending). Pre-publication so FR11
immutability not violated.
- § 6 Scenario D vacuously satisfied (M3 R4 T3.8 audit finding):
no cipherstash-specific strictVerification: false flag exists in
packages/ or examples/ today. All extant matches are orthogonal
(M2 R5 intentional per-space mechanism / mongo synthetic-contract
fixtures / pre-existing SQL adapter test fixtures from PR #386
+ #404). The "first attempt" workaround NFR1 wanted to revert
lived only in the abandoned projects/cipherstash-integration/
design and never landed in workspace packages. NFR1 / TC-23 /
AC-13 vacuously held.
…nts (M3 R4 T3.9)
Three amendments to cipherstash-migration.spec.md draining the M3
R1+R3+R4 deviation backlog into the canonical sub-spec:
- § 1 TS-authored layout (M3 R1 deviation): document that the
package authors contract + migrations directly in TypeScript
under src/core/ rather than committing pre-rendered .json files.
Both authoring styles produce the same ExtensionMigrationPackage
shape; the TS approach co-locates constants with the values that
consume them, which keeps the FR11 invariantId immutability
surface visible in code review, and treats the vendored EQL
bundle in eql-install.generated.ts as the byte-for-byte source
of truth.
- § 3 structural-ops × bundle-CREATEs conflict resolution
(M3 R3, option (c)): document that the EQL bundle owns the
typed-object DDL; structural cipherstash:create-*-v1 ops keep
their stable invariantIds (so verifier's invariantsMismatch gate
passes) but their execute[] is no-op SELECT 1. Future
IR-vocabulary expansion will give them real verification work.
- § 3 constants drift cleanup (M3 R4 item 22, FR11 pre-publication):
document the EQL_V2_ORE_COMPOSITE_TYPES sync (added
ore_block_u64_8_256_term + ore_cllw_var_8; fixed cclw -> cllw
typo) and the cipherstashFutureIR.enums sync (4 enum values:
active/inactive/encrypting/pending). Pre-publication so FR11
immutability not violated.
- § 6 Scenario D vacuously satisfied (M3 R4 T3.8 audit finding):
no cipherstash-specific strictVerification: false flag exists in
packages/ or examples/ today. All extant matches are orthogonal
(M2 R5 intentional per-space mechanism / mongo synthetic-contract
fixtures / pre-existing SQL adapter test fixtures from PR #386
+ #404). The "first attempt" workaround NFR1 wanted to revert
lived only in the abandoned projects/cipherstash-integration/
design and never landed in workspace packages. NFR1 / TC-23 /
AC-13 vacuously held.
…nts (M3 R4 T3.9)
Three amendments to cipherstash-migration.spec.md draining the M3
R1+R3+R4 deviation backlog into the canonical sub-spec:
- § 1 TS-authored layout (M3 R1 deviation): document that the
package authors contract + migrations directly in TypeScript
under src/core/ rather than committing pre-rendered .json files.
Both authoring styles produce the same ExtensionMigrationPackage
shape; the TS approach co-locates constants with the values that
consume them, which keeps the FR11 invariantId immutability
surface visible in code review, and treats the vendored EQL
bundle in eql-install.generated.ts as the byte-for-byte source
of truth.
- § 3 structural-ops × bundle-CREATEs conflict resolution
(M3 R3, option (c)): document that the EQL bundle owns the
typed-object DDL; structural cipherstash:create-*-v1 ops keep
their stable invariantIds (so verifier's invariantsMismatch gate
passes) but their execute[] is no-op SELECT 1. Future
IR-vocabulary expansion will give them real verification work.
- § 3 constants drift cleanup (M3 R4 item 22, FR11 pre-publication):
document the EQL_V2_ORE_COMPOSITE_TYPES sync (added
ore_block_u64_8_256_term + ore_cllw_var_8; fixed cclw -> cllw
typo) and the cipherstashFutureIR.enums sync (4 enum values:
active/inactive/encrypting/pending). Pre-publication so FR11
immutability not violated.
- § 6 Scenario D vacuously satisfied (M3 R4 T3.8 audit finding):
no cipherstash-specific strictVerification: false flag exists in
packages/ or examples/ today. All extant matches are orthogonal
(M2 R5 intentional per-space mechanism / mongo synthetic-contract
fixtures / pre-existing SQL adapter test fixtures from PR #386
+ #404). The "first attempt" workaround NFR1 wanted to revert
lived only in the abandoned projects/cipherstash-integration/
design and never landed in workspace packages. NFR1 / TC-23 /
AC-13 vacuously held.
…nts (M3 R4 T3.9)
Three amendments to cipherstash-migration.spec.md draining the M3
R1+R3+R4 deviation backlog into the canonical sub-spec:
- § 1 TS-authored layout (M3 R1 deviation): document that the
package authors contract + migrations directly in TypeScript
under src/core/ rather than committing pre-rendered .json files.
Both authoring styles produce the same ExtensionMigrationPackage
shape; the TS approach co-locates constants with the values that
consume them, which keeps the FR11 invariantId immutability
surface visible in code review, and treats the vendored EQL
bundle in eql-install.generated.ts as the byte-for-byte source
of truth.
- § 3 structural-ops × bundle-CREATEs conflict resolution
(M3 R3, option (c)): document that the EQL bundle owns the
typed-object DDL; structural cipherstash:create-*-v1 ops keep
their stable invariantIds (so verifier's invariantsMismatch gate
passes) but their execute[] is no-op SELECT 1. Future
IR-vocabulary expansion will give them real verification work.
- § 3 constants drift cleanup (M3 R4 item 22, FR11 pre-publication):
document the EQL_V2_ORE_COMPOSITE_TYPES sync (added
ore_block_u64_8_256_term + ore_cllw_var_8; fixed cclw -> cllw
typo) and the cipherstashFutureIR.enums sync (4 enum values:
active/inactive/encrypting/pending). Pre-publication so FR11
immutability not violated.
- § 6 Scenario D vacuously satisfied (M3 R4 T3.8 audit finding):
no cipherstash-specific strictVerification: false flag exists in
packages/ or examples/ today. All extant matches are orthogonal
(M2 R5 intentional per-space mechanism / mongo synthetic-contract
fixtures / pre-existing SQL adapter test fixtures from PR #386
+ #404). The "first attempt" workaround NFR1 wanted to revert
lived only in the abandoned projects/cipherstash-integration/
design and never landed in workspace packages. NFR1 / TC-23 /
AC-13 vacuously held.
…nts (M3 R4 T3.9)
Three amendments to cipherstash-migration.spec.md draining the M3
R1+R3+R4 deviation backlog into the canonical sub-spec:
- § 1 TS-authored layout (M3 R1 deviation): document that the
package authors contract + migrations directly in TypeScript
under src/core/ rather than committing pre-rendered .json files.
Both authoring styles produce the same ExtensionMigrationPackage
shape; the TS approach co-locates constants with the values that
consume them, which keeps the FR11 invariantId immutability
surface visible in code review, and treats the vendored EQL
bundle in eql-install.generated.ts as the byte-for-byte source
of truth.
- § 3 structural-ops × bundle-CREATEs conflict resolution
(M3 R3, option (c)): document that the EQL bundle owns the
typed-object DDL; structural cipherstash:create-*-v1 ops keep
their stable invariantIds (so verifier's invariantsMismatch gate
passes) but their execute[] is no-op SELECT 1. Future
IR-vocabulary expansion will give them real verification work.
- § 3 constants drift cleanup (M3 R4 item 22, FR11 pre-publication):
document the EQL_V2_ORE_COMPOSITE_TYPES sync (added
ore_block_u64_8_256_term + ore_cllw_var_8; fixed cclw -> cllw
typo) and the cipherstashFutureIR.enums sync (4 enum values:
active/inactive/encrypting/pending). Pre-publication so FR11
immutability not violated.
- § 6 Scenario D vacuously satisfied (M3 R4 T3.8 audit finding):
no cipherstash-specific strictVerification: false flag exists in
packages/ or examples/ today. All extant matches are orthogonal
(M2 R5 intentional per-space mechanism / mongo synthetic-contract
fixtures / pre-existing SQL adapter test fixtures from PR #386
+ #404). The "first attempt" workaround NFR1 wanted to revert
lived only in the abandoned projects/cipherstash-integration/
design and never landed in workspace packages. NFR1 / TC-23 /
AC-13 vacuously held.
…nts (M3 R4 T3.9)
Three amendments to cipherstash-migration.spec.md draining the M3
R1+R3+R4 deviation backlog into the canonical sub-spec:
- § 1 TS-authored layout (M3 R1 deviation): document that the
package authors contract + migrations directly in TypeScript
under src/core/ rather than committing pre-rendered .json files.
Both authoring styles produce the same ExtensionMigrationPackage
shape; the TS approach co-locates constants with the values that
consume them, which keeps the FR11 invariantId immutability
surface visible in code review, and treats the vendored EQL
bundle in eql-install.generated.ts as the byte-for-byte source
of truth.
- § 3 structural-ops × bundle-CREATEs conflict resolution
(M3 R3, option (c)): document that the EQL bundle owns the
typed-object DDL; structural cipherstash:create-*-v1 ops keep
their stable invariantIds (so verifier's invariantsMismatch gate
passes) but their execute[] is no-op SELECT 1. Future
IR-vocabulary expansion will give them real verification work.
- § 3 constants drift cleanup (M3 R4 item 22, FR11 pre-publication):
document the EQL_V2_ORE_COMPOSITE_TYPES sync (added
ore_block_u64_8_256_term + ore_cllw_var_8; fixed cclw -> cllw
typo) and the cipherstashFutureIR.enums sync (4 enum values:
active/inactive/encrypting/pending). Pre-publication so FR11
immutability not violated.
- § 6 Scenario D vacuously satisfied (M3 R4 T3.8 audit finding):
no cipherstash-specific strictVerification: false flag exists in
packages/ or examples/ today. All extant matches are orthogonal
(M2 R5 intentional per-space mechanism / mongo synthetic-contract
fixtures / pre-existing SQL adapter test fixtures from PR #386
+ #404). The "first attempt" workaround NFR1 wanted to revert
lived only in the abandoned projects/cipherstash-integration/
design and never landed in workspace packages. NFR1 / TC-23 /
AC-13 vacuously held.
…nts (M3 R4 T3.9)
Three amendments to cipherstash-migration.spec.md draining the M3
R1+R3+R4 deviation backlog into the canonical sub-spec:
- § 1 TS-authored layout (M3 R1 deviation): document that the
package authors contract + migrations directly in TypeScript
under src/core/ rather than committing pre-rendered .json files.
Both authoring styles produce the same ExtensionMigrationPackage
shape; the TS approach co-locates constants with the values that
consume them, which keeps the FR11 invariantId immutability
surface visible in code review, and treats the vendored EQL
bundle in eql-install.generated.ts as the byte-for-byte source
of truth.
- § 3 structural-ops × bundle-CREATEs conflict resolution
(M3 R3, option (c)): document that the EQL bundle owns the
typed-object DDL; structural cipherstash:create-*-v1 ops keep
their stable invariantIds (so verifier's invariantsMismatch gate
passes) but their execute[] is no-op SELECT 1. Future
IR-vocabulary expansion will give them real verification work.
- § 3 constants drift cleanup (M3 R4 item 22, FR11 pre-publication):
document the EQL_V2_ORE_COMPOSITE_TYPES sync (added
ore_block_u64_8_256_term + ore_cllw_var_8; fixed cclw -> cllw
typo) and the cipherstashFutureIR.enums sync (4 enum values:
active/inactive/encrypting/pending). Pre-publication so FR11
immutability not violated.
- § 6 Scenario D vacuously satisfied (M3 R4 T3.8 audit finding):
no cipherstash-specific strictVerification: false flag exists in
packages/ or examples/ today. All extant matches are orthogonal
(M2 R5 intentional per-space mechanism / mongo synthetic-contract
fixtures / pre-existing SQL adapter test fixtures from PR #386
+ #404). The "first attempt" workaround NFR1 wanted to revert
lived only in the abandoned projects/cipherstash-integration/
design and never landed in workspace packages. NFR1 / TC-23 /
AC-13 vacuously held.
…nts (M3 R4 T3.9)
Three amendments to cipherstash-migration.spec.md draining the M3
R1+R3+R4 deviation backlog into the canonical sub-spec:
- § 1 TS-authored layout (M3 R1 deviation): document that the
package authors contract + migrations directly in TypeScript
under src/core/ rather than committing pre-rendered .json files.
Both authoring styles produce the same ExtensionMigrationPackage
shape; the TS approach co-locates constants with the values that
consume them, which keeps the FR11 invariantId immutability
surface visible in code review, and treats the vendored EQL
bundle in eql-install.generated.ts as the byte-for-byte source
of truth.
- § 3 structural-ops × bundle-CREATEs conflict resolution
(M3 R3, option (c)): document that the EQL bundle owns the
typed-object DDL; structural cipherstash:create-*-v1 ops keep
their stable invariantIds (so verifier's invariantsMismatch gate
passes) but their execute[] is no-op SELECT 1. Future
IR-vocabulary expansion will give them real verification work.
- § 3 constants drift cleanup (M3 R4 item 22, FR11 pre-publication):
document the EQL_V2_ORE_COMPOSITE_TYPES sync (added
ore_block_u64_8_256_term + ore_cllw_var_8; fixed cclw -> cllw
typo) and the cipherstashFutureIR.enums sync (4 enum values:
active/inactive/encrypting/pending). Pre-publication so FR11
immutability not violated.
- § 6 Scenario D vacuously satisfied (M3 R4 T3.8 audit finding):
no cipherstash-specific strictVerification: false flag exists in
packages/ or examples/ today. All extant matches are orthogonal
(M2 R5 intentional per-space mechanism / mongo synthetic-contract
fixtures / pre-existing SQL adapter test fixtures from PR #386
+ #404). The "first attempt" workaround NFR1 wanted to revert
lived only in the abandoned projects/cipherstash-integration/
design and never landed in workspace packages. NFR1 / TC-23 /
AC-13 vacuously held.
…nts (M3 R4 T3.9)
Three amendments to cipherstash-migration.spec.md draining the M3
R1+R3+R4 deviation backlog into the canonical sub-spec:
- § 1 TS-authored layout (M3 R1 deviation): document that the
package authors contract + migrations directly in TypeScript
under src/core/ rather than committing pre-rendered .json files.
Both authoring styles produce the same ExtensionMigrationPackage
shape; the TS approach co-locates constants with the values that
consume them, which keeps the FR11 invariantId immutability
surface visible in code review, and treats the vendored EQL
bundle in eql-install.generated.ts as the byte-for-byte source
of truth.
- § 3 structural-ops × bundle-CREATEs conflict resolution
(M3 R3, option (c)): document that the EQL bundle owns the
typed-object DDL; structural cipherstash:create-*-v1 ops keep
their stable invariantIds (so verifier's invariantsMismatch gate
passes) but their execute[] is no-op SELECT 1. Future
IR-vocabulary expansion will give them real verification work.
- § 3 constants drift cleanup (M3 R4 item 22, FR11 pre-publication):
document the EQL_V2_ORE_COMPOSITE_TYPES sync (added
ore_block_u64_8_256_term + ore_cllw_var_8; fixed cclw -> cllw
typo) and the cipherstashFutureIR.enums sync (4 enum values:
active/inactive/encrypting/pending). Pre-publication so FR11
immutability not violated.
- § 6 Scenario D vacuously satisfied (M3 R4 T3.8 audit finding):
no cipherstash-specific strictVerification: false flag exists in
packages/ or examples/ today. All extant matches are orthogonal
(M2 R5 intentional per-space mechanism / mongo synthetic-contract
fixtures / pre-existing SQL adapter test fixtures from PR #386
+ #404). The "first attempt" workaround NFR1 wanted to revert
lived only in the abandoned projects/cipherstash-integration/
design and never landed in workspace packages. NFR1 / TC-23 /
AC-13 vacuously held.
closes TML-2168
Intent
Complete the SQLite target's control plane — migration planner, runner, schema introspection, PSL type mappings, and TypeScript authoring surface — so
db init/db updatework against SQLite databases using the same contract-driven workflow as Postgres. The planner now mirrors Postgres's strategies + IR architecture (issue-based planning, flat call specs, recreate-table for non-additive changes), and a port ofprisma-next-demoto SQLite shakes out a real cross-target seam — marker reads were hardcoded to Postgres SQL infamily-sql/verify, so any non-PostgresdbInitfailed before reaching its own runner. That gets fixed adapter-side as part of this PR.Change map
planner.tswrapsplanIssues; cohesive recipes live inplanner-strategies.ts(recreate-table, nullability backfill); per-issue defaults inmapIssueToCall; result is aSqliteOpFactoryCall[]IRMigrationPlanWithAuthoringSurface(ADR 194), unblocking class-flow authoring (ADR 193) and ops.json scaffolding (ADR 192)foreign_keysOFF outside the transaction and runsPRAGMA foreign_key_checkbefore commitALTER TABLEis too limited for these changes; FK preservation prevents cascade-deletes duringDROP TABLEof a referenced parentcreateTable,addColumn,recreateTablenow consume flat specs (SqliteColumnSpec,SqliteTableSpec, …) resolved once at the issue-planner boundary;*CallIR carries serializable data onlyrenderTypeScript()a one-liner overjsonToTsSource(spec), so the rendered scaffold is fully self-contained — same shape Postgres usesBEGIN EXCLUSIVEfor locking,_prisma_marker/_prisma_ledgercontrol tables (TEXT for JSON/timestamps), idempotent re-runs (postchecks satisfied → skip), per-op error codes (FOREIGN_KEY_VIOLATIONfor integrity-check failures), schema verification before commitINTEGER PRIMARY KEY CHECK (id = 1)so a stray second row is rejected at the database levelSqliteControlAdapter.introspect()readssqlite_master+ PRAGMAs (table_info,foreign_key_list,index_list,index_info); filters control tables out so they don't surface asextra_tableissuesparseSqliteDefaultnormalizes stored defaults (strips parens, mapsdatetime('now')→now(), handles numeric/string/null literals)control-mutation-defaults.tsmaps PSL scalars → SQLite affinities/codecs (Boolean → integer,DateTime → text,Json → text) and lowers default functions (autoincrement, now, uuid, cuid, ulid, nanoid, dbgenerated)target = "sqlite"in PSL to emit correct contractsrenderCallsToTypeScript+TypeScriptRenderableSqliteMigrationemit a runnablemigration.tswithMigrationCLI.run(import.meta.url, M); round-trip test executes the rendered file viatsxand assertsops.jsondeep-equalsrenderOps(calls)readMarkerfamily-sql/verify(Postgres-only SQL) toSqlControlAdapter.readMarker(driver);PostgresandSQLiteadapters each implement their own probe + readinformation_schema.tables+prisma_contract.markerSQL was breaking SQLitedbInitbefore the runner even startedexamples/prisma-next-demo-sqlite/mirrorsprisma-next-demoagainst@prisma-next/sqlite(TS-authored contract + emit/no-emit workflows, ORM and SQL DSL examples, integration tests on a temporary file-backed DB); README documents the diff vs Postgres demo (nodistinctOn/ilike/pgvector/ discriminator polymorphism)sql-utils,codec-ids,codecs,default-normalizer,native-type-normalizer) relocate fromadapter-sqlite→target-sqlite; full-stack runner integration tests move fromtarget-sqlite/test→adapter-sqlite/test/migrationsadapter ↔ target); matches Postgres layering exactlyThe story
This branch finishes the SQLite target. The runtime plane (driver, adapter, codecs, query builder, ORM) was already in place; this PR adds the control plane and a real consumer (the demo) to validate the whole stack.
The planner is the centerpiece. The first cut was a monolithic per-table walker that emitted CREATE TABLE / ADD COLUMN / CREATE INDEX directly. That worked for additive migrations but not for type/nullability/default changes — SQLite's
ALTER TABLEcan't do most of them — so the recreate-table strategy was added: detect mismatches, then in a single op create a new table with the contract shape, copy data, drop the old, rename the new. To make recreate-table safe, the runner togglesPRAGMA foreign_keysOFF outside the transaction (the pragma is a no-op inside one) and runsPRAGMA foreign_key_checkbefore commit; the planner re-emits FK-backing indexes alongside declared indexes so they survive the rebuild.A later refactor pulls the planner into the same shape as Postgres — a thin wrapper over
planIssues, with cohesive recipes living inplanner-strategies.ts.recreateTableStrategycollapses all per-column issues for a table into one op;nullabilityTighteningBackfillStrategymirrors Postgres's behaviour, emitting aDataTransformCallstub the user fills withUPDATE … WHERE col IS NULLbefore the recreate copies data into the tightened schema. The result is aSqliteOpFactoryCall[]IR consumed by both the runtime ops view (renderOps) and the TypeScript authoring surface (renderCallsToTypeScript). A round-trip test inadapter-sqlite/test/migrations/render-typescript.roundtrip.test.tsbuilds calls, renders them to a file, executes the file viatsx, and asserts the producedops.jsondeep-equalsrenderOps(calls).The demo port (
examples/prisma-next-demo-sqlite/) is the integration test for the whole thing. It mirrors the Postgres demo's contract, ORM-client, SQL DSL, and middleware examples, and runs a realdbInitagainst a temporary file-backed SQLite database in its integration suite. While porting it,dbInitblew up againstinformation_schema.tables— the family'sreadMarkerwas hardcoded to Postgres SQL. The fix moves marker reads to the adapter:SqlControlAdapter.readMarker(driver)is now part of the interface, each target implements its own probe + read, andfamily-sql/verifyno longer carries Postgres-specific SQL.PostgresMigrationRunnerswitches from the deleted helper tofamily.readMarker({ driver }). SQLite's implementation probessqlite_masterand reads_prisma_marker. The demo also dropped queries that don't fit SQLite (pgvector similarity,distinctOn,@@discriminatorpolymorphism,@@enum,ilike, budget-violation guardrails — the budget middleware trips on the ORM's N+1 include strategy when LATERAL is unavailable); the README documents these trade-offs.A late refactor relocates foundational utilities from
adapter-sqlite/src/coretotarget-sqlite/src/core(sql-utils,codec-ids,codecs,default-normalizer,native-type-normalizer), exposes them as subpath exports, and moves full-stack runner integration tests fromtarget-sqlite/testtoadapter-sqlite/test/migrations. This breaks a workspace cycle (adapter ↔ target) that turbo refused to plan and matches Postgres's one-wayadapter → targetedge.adapter-sqlite/controlandadapter-sqlite/codec-typesre-export the same symbols so the demo, e2e harness, and generated contracts keep working.Two smaller hardenings rounded the work out. The marker singleton invariant is now schema-enforced —
_prisma_marker.idwasINTEGER PRIMARY KEY DEFAULT 1with the "only row 1 exists" rule encoded only in the runner'sWHERE id = 1; replaced withINTEGER PRIMARY KEY CHECK (id = 1)so a stray second row is rejected at the database level. And a deadsqliteControlAdapterDescriptordefault export (nocontrolMutationDefaults, noscalarTypeDescriptors) was removed fromcontrol-adapter.ts;exports/control.tsis now the single canonical adapter descriptor. The 1300-line E2E test file was split intoharness.ts+ four focused files (additive.test.ts,destructive.test.ts,widening.test.ts,fk-preservation.test.ts) — same 31 cases, each file browseable without scrolling.Behavior changes & evidence
createPlanner()/createRunner()callable on the SQLite target descriptor; full lifecycle works on a real file-backed DBmigration.tsruns viatsxand reproducesops.jsonreadMarkeradapter contract works against Postgres + SQLite without Postgres-specific SQL leaking into the familydbInitflowprisma-next-demo-sqliteruns the same ORM/SQL DSL examples as the Postgres demoCompatibility / migration / risk
readMarkermove is internal — the only external caller (PostgresMigrationRunner) is updated in the same PR.SqlControlAdapter.readMarkeris now a required method. Any downstream adapter not in this PR would need to implement it (only Postgres + SQLite exist today).target-sqliteadds runtime deps on@prisma-next/family-sql,@prisma-next/sql-schema-ir,@prisma-next/sql-errors,@prisma-next/utils.adapter-sqlitenow depends on@prisma-next/target-sqlite/*subpath exports (cycle eliminated; one-way edgeadapter → targetmatches Postgres).prisma-next-demo-sqlitedrops queries that depend ondistinctOn,ilike,pgvector,@@discriminator,@@enum, and the budget-violation guardrails. The README documents each trade-off; nothing about the SQLite target itself is downgraded.target-sqlitethresholds now locked at 79/65/88/79 (stmts/branches/funcs/lines), matching Postgres. All 65 packages green underpnpm lint(turbo).Follow-ups / open questions
:memory:database support — out of scope, file-only for now.sql-lane(legacy) andkysely-laneSQLite — explicitly out of scope.DOWNoperations — not in this PR.Non-goals / intentionally out of scope
DOWNoperations.:memory:SQLite databases.sql-lane/kysely-laneSQLite support.Summary by CodeRabbit
New Features
Documentation
Tests