Repository navigation
feat(sqlite): add SQLite target (milestones 1–3) - #274
Conversation
📝 WalkthroughWalkthroughThis pull request introduces comprehensive SQLite support to Prisma Next, including a SQLite adapter (AST-to-SQL lowering), driver (connection/transaction management), target package, and runtime extension. It also adds a new Changes
Sequence Diagram(s)sequenceDiagram
actor Client
participant ORM as ORM Client
participant Compiler as Query Compiler
participant Runtime as SQL Runtime
participant Adapter as SQLite Adapter
participant Driver as SQLite Driver
participant DB as SQLite DB
Client->>ORM: createAll(rows)
ORM->>ORM: Check capabilities.sql.defaultInInsert
alt defaultInInsert = true
ORM->>Compiler: compileInsertReturning(rows)
Compiler-->>ORM: single SqlQueryPlan
ORM->>Runtime: dispatchMutationRows([plan])
Runtime->>Adapter: execute(plan)
Adapter->>Adapter: lower(INSERT AST)
Adapter-->>Runtime: { sql, params }
Runtime->>Driver: execute(sql, params)
Driver->>DB: INSERT all rows<br/>(uniform columns)
DB-->>Driver: result rows
Driver-->>Runtime: rows
Runtime-->>ORM: mapped rows
else defaultInInsert = false
ORM->>Compiler: compileInsertReturningSplit(rows)
Compiler->>Compiler: groupRowsByColumnSignature()
Compiler-->>ORM: SqlQueryPlan[]
ORM->>Runtime: dispatchSplitMutationRows(plans)
loop For each plan
Runtime->>Adapter: execute(plan)
Adapter->>Adapter: lower(INSERT AST)
Adapter-->>Runtime: { sql, params }
Runtime->>Driver: execute(sql, params)
Driver->>DB: INSERT row group<br/>(group-specific columns)
DB-->>Driver: result rows
Driver-->>Runtime: rows
end
Runtime->>Runtime: stitch results<br/>+ strip hidden fields
Runtime-->>ORM: mapped rows
end
ORM-->>Client: result
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested reviewers
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
|
@prisma-next/mongo-runtime
@prisma-next/family-mongo
@prisma-next/sql-runtime
@prisma-next/family-sql
@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/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/vite-plugin-contract-emit
@prisma-next/runtime-executor
@prisma-next/mongo-codec
@prisma-next/mongo-contract
@prisma-next/mongo-value
@prisma-next/mongo-contract-psl
@prisma-next/mongo-emitter
@prisma-next/mongo-query-ast
@prisma-next/mongo-orm
@prisma-next/mongo-pipeline-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: 13
🧹 Nitpick comments (11)
packages/3-targets/6-adapters/sqlite/README.md (2)
48-84: Adddirection TBinside Mermaid subgraphs.The Mermaid diagram contains four subgraphs (Runtime, SQLite Adapter, SQLite Driver, Descriptors) that lack explicit direction specification. As per coding guidelines, prefer
direction TBinside Mermaidsubgraphblocks for consistency.📊 Proposed enhancement
```mermaid flowchart TD subgraph "Runtime" + direction TB RT[Runtime] PLAN[Plan] end subgraph "SQLite Adapter" + direction TB ADAPTER[Adapter] LOWERER[AST Lowering] CODECS[Codecs] CAPS[Capabilities] end subgraph "SQLite Driver" + direction TB DRIVER[Driver] DB[(SQLite)] end subgraph "Descriptors" + direction TB RUNTIME_DESC[Runtime Descriptor] CODECTYPES[Codec Types] COLTYPES[Column Types] end🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-targets/6-adapters/sqlite/README.md` around lines 48 - 84, The Mermaid subgraphs ("Runtime", "SQLite Adapter", "SQLite Driver", "Descriptors") need explicit direction set; inside each subgraph block (the ones containing RT/PLAN, ADAPTER/LOWERER/CODECS/CAPS, DRIVER/DB, and RUNTIME_DESC/CODECTYPES/COLTYPES respectively) add the line `direction TB` immediately after the subgraph declaration so each subgraph uses top-to-bottom layout.
1-194: Consider focusing README more on usage over implementation details.The README contains extensive internal implementation details (codec wire formats, AST lowering internals, internal package structure). While adapter packages require some technical detail for framework developers and contract authors, consider streamlining the README to focus more on:
- When to use this adapter
- How to import and configure it
- What codec types are available for contract authoring
- Key behavioral differences from other adapters
Implementation details like AST lowering specifics, internal component architecture, and codec wire format encoding could be moved to dedicated architecture docs or inline code documentation.
As per coding guidelines, READMEs should focus on what the package does, when to use it, and concrete examples, avoiding internal implementation detail unless it materially affects usage.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-targets/6-adapters/sqlite/README.md` around lines 1 - 194, The README is too implementation-heavy; trim internal details and rework it to focus on usage: explain when to use this SQLite adapter, show import/config examples (runtime descriptor export via runtime.ts), list codec types available for contract authoring (e.g., CodecTypes, JsonValue) and common column descriptors (e.g., textColumn, integerColumn, jsonColumn), and call out behavioral differences (e.g., includeMany implemented via correlated subquery/json_group_array, capabilities like sql.returning/jsonAgg/lateral:false) as brief bullets; move deep implementation sections (AST lowering, codec wire formats, internal architecture, sql-utils, core internals like Adapter and adapters' lowerer) into a separate ARCHITECTURE.md or inline source docs and keep the README examples and exports section concise.packages/3-targets/3-targets/sqlite/tsconfig.json (1)
7-8: Consider addingtest/fixtures/**/*to the exclude array.Per coding guidelines, test fixture files should be excluded from TypeScript typechecking because fixtures often use internal types that aren't exported from packages.
♻️ Proposed fix
"include": ["src/**/*.ts", "test/**/*.ts"], - "exclude": ["dist"] + "exclude": ["dist", "test/fixtures/**/*"] }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-targets/3-targets/sqlite/tsconfig.json` around lines 7 - 8, The tsconfig currently includes "test/**/*.ts" which causes test fixture files to be typechecked; update the tsconfig's "exclude" array (the existing "exclude": ["dist"]) to also include "test/fixtures/**/*" so that fixture files are ignored by TypeScript typechecking; specifically modify the tsconfig.json exclude entry referenced here to add "test/fixtures/**/*".packages/3-targets/6-adapters/sqlite/tsconfig.json (1)
7-8: Consider addingtest/fixtures/**/*to the exclude array.Same as the target package — excluding test fixture files prevents type-checking issues when fixtures use internal types.
♻️ Proposed fix
"include": ["src/**/*.ts", "test/**/*.ts"], - "exclude": ["dist"] + "exclude": ["dist", "test/fixtures/**/*"] }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-targets/6-adapters/sqlite/tsconfig.json` around lines 7 - 8, The tsconfig currently includes "src/**/*.ts" and "test/**/*.ts" but does not exclude test fixture files which can cause type-checking issues; update the "exclude" array in this tsconfig (the JSON object containing "include" and "exclude") to add "test/fixtures/**/*" alongside "dist" so fixture files are ignored during type-checking.packages/3-targets/6-adapters/sqlite/src/core/sql-utils.ts (1)
26-35: Clarify literal-escaping API to avoid unsafe interpolation.
escapeLiteral()currently returns unquoted content, whilequoteIdentifier()returns a fully quoted token. Consider adding a quoted-literal helper (or renaming this function) so call sites are less error-prone.Suggested additive helper
export function escapeLiteral(value: string): string { if (value.includes('\0')) { throw new SqlEscapeError( 'Literal value cannot contain null bytes', value.replace(/\0/g, '\\0'), 'literal', ); } return value.replace(/'/g, "''"); } + +export function quoteLiteral(value: string): string { + return `'${escapeLiteral(value)}'`; +}🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-targets/6-adapters/sqlite/src/core/sql-utils.ts` around lines 26 - 35, The current escapeLiteral(value: string) returns an unquoted, escaped value which is error-prone compared to quoteIdentifier(); add a new helper quoteLiteral(value: string): string that validates for null bytes (reuse the SqlEscapeError check used in escapeLiteral), escapes single-quotes (using the existing replacement logic) and returns the value wrapped in single quotes; either keep escapeLiteral as an internal helper (rename to escapeLiteralRaw if you prefer) or update all call sites to use quoteLiteral instead of embedding quotes around escapeLiteral results so callers get a safely quoted literal by default.packages/3-extensions/sqlite/README.md (1)
11-44: Add a minimal usage example and clickable doc links.Great architectural context, but this README would be more usable with one concrete
sqlite(...)quick-start snippet and markdown links in “Related Docs” instead of plain path text.As per coding guidelines, "**/README.md: For user-facing packages, keep README.md focused on what the package does, when to use it, and a few concrete examples."
Also applies to: 67-69
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-extensions/sqlite/README.md` around lines 11 - 44, Add a minimal quick-start usage example showing how to call sqlite(...) and then use db.runtime() or db.connect(...) (include typical usage of db.sql, db.orm, db.context or db.stack) and show a simple query or connection flow; replace plain package path text in the "Dependencies" (and the "Related Docs" section at lines ~67-69) with clickable Markdown links to the respective package docs (use the package names shown, e.g., `@prisma-next/sql-runtime`, `@prisma-next/sql-builder`, etc.), and ensure the README remains concise and focused on purpose, when to use the package, and the single short example.packages/3-targets/6-adapters/sqlite/src/core/codec-ids.ts (1)
1-6: Keep the generic SQL codec ID forwards out ofsrc/core.This internal module is becoming a re-export surface. If these constants need to be public, re-export them from an
src/exports/*file; otherwise import them directly where they are used.As per coding guidelines, "Do not reexport things from one file in another, except in the exports/ folders."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-targets/6-adapters/sqlite/src/core/codec-ids.ts` around lines 1 - 6, This file re-exports SQL_CHAR_CODEC_ID, SQL_FLOAT_CODEC_ID, SQL_INT_CODEC_ID, and SQL_VARCHAR_CODEC_ID from another package which violates the rule against forwarding re-exports from src/core; either remove this re-export and update all consumers to import these constants directly from '@prisma-next/sql-relational-core/ast', or move the re-export into an exports surface (e.g., create or add to src/exports/* and export SQL_CHAR_CODEC_ID, SQL_FLOAT_CODEC_ID, SQL_INT_CODEC_ID, SQL_VARCHAR_CODEC_ID there), then update imports accordingly so no forwarding re-exports remain in src/core.packages/3-extensions/sqlite/test/integration/sql-builder.test.ts (1)
152-160: Unnecessary type cast.The cast
as Dateon line 157 is redundant sinceexpectTypeOf(rows[0]!).toEqualTypeOf<{ id: number; created_at: Date }>()on line 159 already asserts the type. You can call.toISOString()directly.♻️ Proposed fix
- expect((rows[0]!.created_at as Date).toISOString()).toBe('2024-01-01T00:00:00.000Z'); + expect(rows[0]!.created_at.toISOString()).toBe('2024-01-01T00:00:00.000Z');🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-extensions/sqlite/test/integration/sql-builder.test.ts` around lines 152 - 160, Remove the redundant type cast on rows[0]!.created_at in the "datetime survives insert and select" test: since the test already asserts the compile-time type with expectTypeOf(rows[0]!).toEqualTypeOf<{ id: number; created_at: Date }>(), call .toISOString() directly on rows[0]!.created_at (from the rows variable returned by runtime().execute(...) on db().typed_rows.select(...)) instead of using (rows[0]!.created_at as Date).toISOString().packages/3-extensions/sqlite/test/integration/setup.ts (1)
62-65: String interpolation in SQL is discouraged even for internal values.While
sqlContract.storage.storageHashandprofileHashare computed internally and not user-controlled, using string interpolation in SQL statements is a code smell that could become a vulnerability if the pattern is copied elsewhere. Consider using parameterized queries for consistency.♻️ Suggested parameterized approach
db.exec(` - INSERT INTO prisma_contract_marker (id, core_hash, profile_hash) - VALUES (1, '${sqlContract.storage.storageHash}', '${sqlContract.profileHash ?? sqlContract.storage.storageHash}') - `); + INSERT INTO prisma_contract_marker (id, core_hash, profile_hash) + VALUES (?, ?, ?) + `); + // Note: DatabaseSync.exec() doesn't support params, so use prepare().run() instead: + const insertMarker = db.prepare( + 'INSERT INTO prisma_contract_marker (id, core_hash, profile_hash) VALUES (?, ?, ?)' + ); + insertMarker.run(1, sqlContract.storage.storageHash, sqlContract.profileHash ?? sqlContract.storage.storageHash);🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-extensions/sqlite/test/integration/setup.ts` around lines 62 - 65, The INSERT uses string interpolation which is unsafe; change the db.exec call that inserts into prisma_contract_marker to use a parameterized query or prepared statement instead of embedding values directly: build the SQL with placeholders for id, core_hash and profile_hash (referencing prisma_contract_marker and the call site db.exec) and pass sqlContract.storage.storageHash and (sqlContract.profileHash ?? sqlContract.storage.storageHash) as parameters to db.exec (or bind them via a prepared statement) so values are supplied separately from the SQL text.packages/3-targets/7-drivers/sqlite/test/sqlite-driver.test.ts (2)
117-125: Same refactor opportunity for FK constraint error test.♻️ Suggested refactor
- try { - await driver.query('INSERT INTO child VALUES (?, ?)', [1, 999]); - expect.unreachable('should have thrown'); - } catch (error) { - expect(SqlQueryError.is(error)).toBe(true); - expect((error as SqlQueryError).sqlState).toBe('23503'); - } + const error = await expect( + driver.query('INSERT INTO child VALUES (?, ?)', [1, 999]), + ).rejects.toThrow(SqlQueryError); + expect(error.sqlState).toBe('23503');🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-targets/7-drivers/sqlite/test/sqlite-driver.test.ts` around lines 117 - 125, Refactor the FK constraint error assertion in the test that calls driver.query('INSERT INTO child VALUES (?, ?)', [1, 999]) so it uses the shared assertion helper instead of an inline try/catch: replace the try/catch block that checks SqlQueryError.is(error) and (error as SqlQueryError).sqlState === '23503' with a call to the existing helper (or add a small helper) that asserts an async query rejects with a SqlQueryError having sqlState '23503'; target the driver.query call and SqlQueryError/ sqlState '23503' when locating the code to change.
100-108: Preferexpect().toThrow()pattern for error assertions.The coding guidelines recommend using
expect(() => ...).toThrow()instead of manual try/catch blocks. For checking additional error properties likesqlState, you can capture the error and assert separately.♻️ Suggested refactor
- try { - await driver.query('INSERT INTO t VALUES (?, ?)', [2, 'a']); - expect.unreachable('should have thrown'); - } catch (error) { - expect(SqlQueryError.is(error)).toBe(true); - expect((error as SqlQueryError).sqlState).toBe('23505'); - } + const error = await expect( + driver.query('INSERT INTO t VALUES (?, ?)', [2, 'a']), + ).rejects.toThrow(SqlQueryError); + expect(error.sqlState).toBe('23505');🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-targets/7-drivers/sqlite/test/sqlite-driver.test.ts` around lines 100 - 108, Replace the manual try/catch with Jest's async rejection matchers: use await expect(driver.query('INSERT INTO t VALUES (?, ?)', [2, 'a'])).rejects.toThrow() to assert an error was thrown, then capture the rejected error for property checks (e.g., const error = await driver.query(...).catch(e => e); expect(SqlQueryError.is(error)).toBe(true); expect((error as SqlQueryError).sqlState).toBe('23505');) and finally call driver.close(); this keeps the error-existence check via rejects.toThrow and still allows asserting the sqlState and SqlQueryError.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 `@architecture.config.json`:
- Around line 177-224: The architecture.config.json is missing globs for several
SQLite export files which breaks dependency guards; add entries for
packages/3-targets/6-adapters/sqlite/src/exports/codec-types.ts,
column-types.ts, types.ts with domain "targets", layer "adapters", plane
"shared" and add an entry for
packages/3-targets/3-targets/sqlite/src/exports/pack.ts with domain
"extensions", layer "targets", plane "runtime" so each unmapped export has its
own glob (match the existing object shape used for other sqlite export entries).
In `@packages/3-extensions/sql-orm-client/src/query-plan-mutations.ts`:
- Around line 147-193: The split compilers currently return [] for empty input
because groupRowsByColumnSignature yields no groups; make them behave like the
non-split compilers by delegating empty-batch validation to the original
functions: in compileInsertReturningSplit, add an early guard if rows.length ===
0 that calls compileInsertReturning(contract, tableName, rows, returningColumns)
so the same validation/throw path is executed; do the same in
compileInsertCountSplit by calling compileInsertCount(contract, tableName, rows)
when rows.length === 0. This preserves existing error behavior without changing
groupRowsByColumnSignature.
In `@packages/3-extensions/sqlite/src/runtime/sqlite.ts`:
- Around line 170-190: connect() currently throws when driverConnected or
connectPromise is truthy and doesn't await an in-flight open nor clear stale
backgroundConnectError after a failed open; update connect() to: if
connectPromise exists, await connectPromise and then return getRuntime() (so
concurrent callers share the same open), ensure connectDriver() sets/clears
connectPromise and that any backgroundConnectError is cleared before calling
getRuntime() (or cleared immediately when connectDriver() succeeds/when
retrying) so subsequent calls to connect() can retry with a corrected binding;
refer to the connect(), connectPromise, driverConnected, backgroundConnectError,
connectDriver(), and getRuntime() symbols when making these changes.
In `@packages/3-extensions/sqlite/tsconfig.json`:
- Line 8: Update the tsconfig.json "exclude" array to omit test fixtures from
TypeScript typechecking by adding the pattern 'test/fixtures/**/*' to the
existing exclude entries (i.e., modify the "exclude" property so it includes
'test/fixtures/**/*' in addition to current values).
In `@packages/3-targets/3-targets/sqlite/README.md`:
- Line 9: Update the README entry that currently states "Plane: multi-plane
(migration, runtime)" to reflect the actual current scope: change the Plane
classification to a single-plane or more accurate description (e.g., "Plane:
runtime" or "Plane: control-plane planned") and/or add a parenthetical noting
that migration planner/runner, schema introspection, and control-plane target
descriptor are non-goals/future milestones; specifically modify the "Plane:
multi-plane (migration, runtime)" line and ensure it aligns with the "Non-goals"
section that lists migration planner/runner, schema introspection, and
control-plane target descriptor.
In `@packages/3-targets/6-adapters/sqlite/package.json`:
- Around line 20-21: The package.json lists an unused dependency
"@prisma-next/cli"; remove the "@prisma-next/cli": "workspace:*" entry from the
"dependencies" section in packages/3-targets/6-adapters/sqlite/package.json,
then run the package manager install (yarn/npm/pnpm) to update the lockfile and
node_modules, and run a quick search for any imports/usages of
"@prisma-next/cli" in the sqlite adapter (no results expected) to ensure nothing
else depends on it.
In `@packages/3-targets/6-adapters/sqlite/src/core/types.ts`:
- Around line 1-3: The file currently imports Contract from
'@prisma-next/contract/types' and composes Contract<SqlStorage> manually;
replace that by importing the SQL-specific contract type SqlContract from
'@prisma-next/sql-contract/types' and use SqlContract wherever
Contract<SqlStorage> appears (keep existing SqlStorage and LoweredStatement
imports as-is) so the type surface is canonical and consistent across targets.
In `@packages/3-targets/6-adapters/sqlite/tsdown.config.ts`:
- Around line 4-10: The tsdown entry list is missing the adapter entry so the
adapter build will be omitted; update the tsdown config's entry array (the array
currently containing 'src/exports/types.ts', 'src/exports/codec-types.ts',
'src/exports/column-types.ts', 'src/exports/control.ts',
'src/exports/runtime.ts') to also include 'src/exports/adapter.ts' so all
required entry points (adapter.ts, types.ts, codec-types.ts, control.ts,
runtime.ts) are present.
In `@packages/3-targets/7-drivers/sqlite/src/normalize-error.ts`:
- Around line 93-104: The condition that checks code === 'ERR_SQLITE_ERROR' is
unreachable because isSqliteError(error) already handles that case; update the
connection-related branch in normalize-error.ts to only match non-SQLite Node.js
errors by replacing the current condition with a guard like
!isSqliteError(error) && (error.message.includes('database is locked') ||
error.message.includes('unable to open database')), remove the direct code ===
'ERR_SQLITE_ERROR' check and keep returning new
SqlConnectionError(error.message, { cause: error, transient: false }) so only
non-SQLite connection errors are converted here.
In `@packages/3-targets/7-drivers/sqlite/src/sqlite-driver.ts`:
- Around line 70-76: The beginTransaction(), release(), and connect() paths
currently call into the sqlite DB directly and can throw errors that bypass
normalizeSqliteError; update SqliteDriver.connect,
SqliteDriver.beginTransaction, and SqliteDriver.release (and the code around the
SqliteTransactionImpl creation) to wrap the db open/BEGIN/close operations with
normalizeSqliteError(...) (or call a shared helper that invokes the operation
inside normalizeSqliteError) so any thrown error is normalized to the same shape
as execute()/query()/commit()/rollback(); ensure you reference
normalizeSqliteError when wrapping the calls so BEGIN, close, and open failures
are caught and rethrown in the normalized form.
- Around line 200-203: createBoundDriverFromBinding currently calls
SqliteBoundDriver.connect(binding) but doesn't await it, so connection failures
are swallowed and a not-connected driver is returned; change
createBoundDriverFromBinding to propagate the connect result (make the function
async or return a Promise) and await SqliteBoundDriver.connect(binding) (or let
the returned Promise reject on failure) before returning the driver so callers
receive connection errors at bind time; reference: createBoundDriverFromBinding
and SqliteBoundDriver.connect.
- Around line 172-175: acquireConnection() currently calls openConnection(path)
each time which creates a new isolated in-memory DB when path is ':memory:';
change the logic in acquireConnection (and/or in `#requireConnected/binding`
resolution) to detect in-memory URIs and normalize or reuse a single shared
connection: either convert ':memory:' to the shared URI form
'file::memory:?cache=shared' before calling openConnection, or keep a cached
DatabaseSync instance on the driver for memory databases and return a
SqliteConnectionImpl that wraps that single instance (use SqliteConnectionImpl,
openConnection, acquireConnection and `#requireConnected` to locate where to apply
the normalization/caching). Ensure the chosen approach is applied only for
in-memory URIs so file-based behavior is unchanged.
In `@packages/3-targets/7-drivers/sqlite/tsconfig.json`:
- Line 8: Update the tsconfig.json's "exclude" array to also omit test fixtures
from package typechecking by adding the pattern "test/fixtures/**/*" alongside
the existing "dist" entry; locate the "exclude" property in the tsconfig.json
for this package and append the fixture glob so TypeScript will ignore
fixture-only internals during compilation.
---
Nitpick comments:
In `@packages/3-extensions/sqlite/README.md`:
- Around line 11-44: Add a minimal quick-start usage example showing how to call
sqlite(...) and then use db.runtime() or db.connect(...) (include typical usage
of db.sql, db.orm, db.context or db.stack) and show a simple query or connection
flow; replace plain package path text in the "Dependencies" (and the "Related
Docs" section at lines ~67-69) with clickable Markdown links to the respective
package docs (use the package names shown, e.g., `@prisma-next/sql-runtime`,
`@prisma-next/sql-builder`, etc.), and ensure the README remains concise and
focused on purpose, when to use the package, and the single short example.
In `@packages/3-extensions/sqlite/test/integration/setup.ts`:
- Around line 62-65: The INSERT uses string interpolation which is unsafe;
change the db.exec call that inserts into prisma_contract_marker to use a
parameterized query or prepared statement instead of embedding values directly:
build the SQL with placeholders for id, core_hash and profile_hash (referencing
prisma_contract_marker and the call site db.exec) and pass
sqlContract.storage.storageHash and (sqlContract.profileHash ??
sqlContract.storage.storageHash) as parameters to db.exec (or bind them via a
prepared statement) so values are supplied separately from the SQL text.
In `@packages/3-extensions/sqlite/test/integration/sql-builder.test.ts`:
- Around line 152-160: Remove the redundant type cast on rows[0]!.created_at in
the "datetime survives insert and select" test: since the test already asserts
the compile-time type with expectTypeOf(rows[0]!).toEqualTypeOf<{ id: number;
created_at: Date }>(), call .toISOString() directly on rows[0]!.created_at (from
the rows variable returned by runtime().execute(...) on
db().typed_rows.select(...)) instead of using (rows[0]!.created_at as
Date).toISOString().
In `@packages/3-targets/3-targets/sqlite/tsconfig.json`:
- Around line 7-8: The tsconfig currently includes "test/**/*.ts" which causes
test fixture files to be typechecked; update the tsconfig's "exclude" array (the
existing "exclude": ["dist"]) to also include "test/fixtures/**/*" so that
fixture files are ignored by TypeScript typechecking; specifically modify the
tsconfig.json exclude entry referenced here to add "test/fixtures/**/*".
In `@packages/3-targets/6-adapters/sqlite/README.md`:
- Around line 48-84: The Mermaid subgraphs ("Runtime", "SQLite Adapter", "SQLite
Driver", "Descriptors") need explicit direction set; inside each subgraph block
(the ones containing RT/PLAN, ADAPTER/LOWERER/CODECS/CAPS, DRIVER/DB, and
RUNTIME_DESC/CODECTYPES/COLTYPES respectively) add the line `direction TB`
immediately after the subgraph declaration so each subgraph uses top-to-bottom
layout.
- Around line 1-194: The README is too implementation-heavy; trim internal
details and rework it to focus on usage: explain when to use this SQLite
adapter, show import/config examples (runtime descriptor export via runtime.ts),
list codec types available for contract authoring (e.g., CodecTypes, JsonValue)
and common column descriptors (e.g., textColumn, integerColumn, jsonColumn), and
call out behavioral differences (e.g., includeMany implemented via correlated
subquery/json_group_array, capabilities like
sql.returning/jsonAgg/lateral:false) as brief bullets; move deep implementation
sections (AST lowering, codec wire formats, internal architecture, sql-utils,
core internals like Adapter and adapters' lowerer) into a separate
ARCHITECTURE.md or inline source docs and keep the README examples and exports
section concise.
In `@packages/3-targets/6-adapters/sqlite/src/core/codec-ids.ts`:
- Around line 1-6: This file re-exports SQL_CHAR_CODEC_ID, SQL_FLOAT_CODEC_ID,
SQL_INT_CODEC_ID, and SQL_VARCHAR_CODEC_ID from another package which violates
the rule against forwarding re-exports from src/core; either remove this
re-export and update all consumers to import these constants directly from
'@prisma-next/sql-relational-core/ast', or move the re-export into an exports
surface (e.g., create or add to src/exports/* and export SQL_CHAR_CODEC_ID,
SQL_FLOAT_CODEC_ID, SQL_INT_CODEC_ID, SQL_VARCHAR_CODEC_ID there), then update
imports accordingly so no forwarding re-exports remain in src/core.
In `@packages/3-targets/6-adapters/sqlite/src/core/sql-utils.ts`:
- Around line 26-35: The current escapeLiteral(value: string) returns an
unquoted, escaped value which is error-prone compared to quoteIdentifier(); add
a new helper quoteLiteral(value: string): string that validates for null bytes
(reuse the SqlEscapeError check used in escapeLiteral), escapes single-quotes
(using the existing replacement logic) and returns the value wrapped in single
quotes; either keep escapeLiteral as an internal helper (rename to
escapeLiteralRaw if you prefer) or update all call sites to use quoteLiteral
instead of embedding quotes around escapeLiteral results so callers get a safely
quoted literal by default.
In `@packages/3-targets/6-adapters/sqlite/tsconfig.json`:
- Around line 7-8: The tsconfig currently includes "src/**/*.ts" and
"test/**/*.ts" but does not exclude test fixture files which can cause
type-checking issues; update the "exclude" array in this tsconfig (the JSON
object containing "include" and "exclude") to add "test/fixtures/**/*" alongside
"dist" so fixture files are ignored during type-checking.
In `@packages/3-targets/7-drivers/sqlite/test/sqlite-driver.test.ts`:
- Around line 117-125: Refactor the FK constraint error assertion in the test
that calls driver.query('INSERT INTO child VALUES (?, ?)', [1, 999]) so it uses
the shared assertion helper instead of an inline try/catch: replace the
try/catch block that checks SqlQueryError.is(error) and (error as
SqlQueryError).sqlState === '23503' with a call to the existing helper (or add a
small helper) that asserts an async query rejects with a SqlQueryError having
sqlState '23503'; target the driver.query call and SqlQueryError/ sqlState
'23503' when locating the code to change.
- Around line 100-108: Replace the manual try/catch with Jest's async rejection
matchers: use await expect(driver.query('INSERT INTO t VALUES (?, ?)', [2,
'a'])).rejects.toThrow() to assert an error was thrown, then capture the
rejected error for property checks (e.g., const error = await
driver.query(...).catch(e => e); expect(SqlQueryError.is(error)).toBe(true);
expect((error as SqlQueryError).sqlState).toBe('23505');) and finally call
driver.close(); this keeps the error-existence check via rejects.toThrow and
still allows asserting the sqlState and SqlQueryError.is.
🪄 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: 2aa9620d-105e-444c-affe-b88001fa582e
⛔ Files ignored due to path filters (7)
packages/2-sql/4-lanes/sql-builder/test/fixtures/generated/contract.d.tsis excluded by!**/generated/**packages/2-sql/4-lanes/sql-builder/test/fixtures/generated/contract.jsonis excluded by!**/generated/**packages/3-extensions/sql-orm-client/test/fixtures/generated/contract.d.tsis excluded by!**/generated/**packages/3-extensions/sql-orm-client/test/fixtures/generated/contract.jsonis excluded by!**/generated/**pnpm-lock.yamlis excluded by!**/pnpm-lock.yamltest/e2e/framework/test/fixtures/generated/contract.d.tsis excluded by!**/generated/**test/e2e/framework/test/fixtures/generated/contract.jsonis excluded by!**/generated/**
📒 Files selected for processing (94)
architecture.config.jsondocs/reference/capabilities.mdexamples/prisma-next-demo/src/prisma/contract.d.tsexamples/prisma-next-demo/src/prisma/contract.jsonpackages/2-sql/2-authoring/contract-ts/src/staged-contract-types.tspackages/2-sql/4-lanes/relational-core/src/ast/adapter-types.tspackages/2-sql/4-lanes/relational-core/src/types.tspackages/2-sql/4-lanes/relational-core/test/utils.tspackages/2-sql/5-runtime/src/sql-family-adapter.tspackages/2-sql/5-runtime/src/sql-runtime.tspackages/2-sql/5-runtime/test/execution-stack.test.tspackages/2-sql/5-runtime/test/sql-family-adapter.test.tspackages/2-sql/5-runtime/test/sql-runtime.test.tspackages/2-sql/5-runtime/test/utils.tspackages/3-extensions/sql-orm-client/src/collection-mutation-dispatch.tspackages/3-extensions/sql-orm-client/src/collection.tspackages/3-extensions/sql-orm-client/src/query-plan-mutations.tspackages/3-extensions/sql-orm-client/src/query-plan.tspackages/3-extensions/sql-orm-client/test/collection-fixtures.tspackages/3-extensions/sql-orm-client/test/collection-mutation-dispatch.test.tspackages/3-extensions/sql-orm-client/test/collection.state.test.tspackages/3-extensions/sql-orm-client/test/query-plan-mutations.test.tspackages/3-extensions/sqlite/README.mdpackages/3-extensions/sqlite/package.jsonpackages/3-extensions/sqlite/src/exports/runtime.tspackages/3-extensions/sqlite/src/runtime/binding.tspackages/3-extensions/sqlite/src/runtime/sqlite.tspackages/3-extensions/sqlite/test/integration/contract-type.tspackages/3-extensions/sqlite/test/integration/contract.tspackages/3-extensions/sqlite/test/integration/orm.test.tspackages/3-extensions/sqlite/test/integration/setup.tspackages/3-extensions/sqlite/test/integration/sql-builder.test.tspackages/3-extensions/sqlite/tsconfig.jsonpackages/3-extensions/sqlite/tsconfig.prod.jsonpackages/3-extensions/sqlite/tsdown.config.tspackages/3-extensions/sqlite/vitest.config.tspackages/3-targets/3-targets/sqlite/README.mdpackages/3-targets/3-targets/sqlite/package.jsonpackages/3-targets/3-targets/sqlite/src/core/descriptor-meta.tspackages/3-targets/3-targets/sqlite/src/exports/pack.tspackages/3-targets/3-targets/sqlite/src/exports/runtime.tspackages/3-targets/3-targets/sqlite/tsconfig.jsonpackages/3-targets/3-targets/sqlite/tsconfig.prod.jsonpackages/3-targets/3-targets/sqlite/tsdown.config.tspackages/3-targets/3-targets/sqlite/vitest.config.tspackages/3-targets/6-adapters/postgres/src/core/adapter.tspackages/3-targets/6-adapters/postgres/src/core/descriptor-meta.tspackages/3-targets/6-adapters/sqlite/README.mdpackages/3-targets/6-adapters/sqlite/package.jsonpackages/3-targets/6-adapters/sqlite/src/core/adapter.tspackages/3-targets/6-adapters/sqlite/src/core/codec-ids.tspackages/3-targets/6-adapters/sqlite/src/core/codecs.tspackages/3-targets/6-adapters/sqlite/src/core/descriptor-meta.tspackages/3-targets/6-adapters/sqlite/src/core/sql-utils.tspackages/3-targets/6-adapters/sqlite/src/core/types.tspackages/3-targets/6-adapters/sqlite/src/exports/codec-types.tspackages/3-targets/6-adapters/sqlite/src/exports/column-types.tspackages/3-targets/6-adapters/sqlite/src/exports/control.tspackages/3-targets/6-adapters/sqlite/src/exports/runtime.tspackages/3-targets/6-adapters/sqlite/src/exports/types.tspackages/3-targets/6-adapters/sqlite/test/adapter.test.tspackages/3-targets/6-adapters/sqlite/test/codecs.test.tspackages/3-targets/6-adapters/sqlite/tsconfig.jsonpackages/3-targets/6-adapters/sqlite/tsconfig.prod.jsonpackages/3-targets/6-adapters/sqlite/tsdown.config.tspackages/3-targets/6-adapters/sqlite/vitest.config.tspackages/3-targets/7-drivers/sqlite/README.mdpackages/3-targets/7-drivers/sqlite/package.jsonpackages/3-targets/7-drivers/sqlite/src/core/descriptor-meta.tspackages/3-targets/7-drivers/sqlite/src/exports/control.tspackages/3-targets/7-drivers/sqlite/src/exports/runtime.tspackages/3-targets/7-drivers/sqlite/src/normalize-error.tspackages/3-targets/7-drivers/sqlite/src/sqlite-driver.tspackages/3-targets/7-drivers/sqlite/test/control-driver.test.tspackages/3-targets/7-drivers/sqlite/test/runtime-driver.test.tspackages/3-targets/7-drivers/sqlite/test/sqlite-driver.test.tspackages/3-targets/7-drivers/sqlite/tsconfig.jsonpackages/3-targets/7-drivers/sqlite/tsconfig.prod.jsonpackages/3-targets/7-drivers/sqlite/tsdown.config.tspackages/3-targets/7-drivers/sqlite/vitest.config.tstest/integration/test/authoring/parity/core-surface/expected.contract.jsontest/integration/test/authoring/parity/default-cuid-2/expected.contract.jsontest/integration/test/authoring/parity/default-dbgenerated/expected.contract.jsontest/integration/test/authoring/parity/default-nanoid-16/expected.contract.jsontest/integration/test/authoring/parity/default-nanoid/expected.contract.jsontest/integration/test/authoring/parity/default-pack-slugid/expected.contract.jsontest/integration/test/authoring/parity/default-ulid/expected.contract.jsontest/integration/test/authoring/parity/default-uuid-v4/expected.contract.jsontest/integration/test/authoring/parity/default-uuid-v7/expected.contract.jsontest/integration/test/authoring/parity/map-attributes/expected.contract.jsontest/integration/test/authoring/parity/pgvector-named-type/expected.contract.jsontest/integration/test/authoring/parity/relation-backrelation-list/expected.contract.jsontest/integration/test/fixtures/contract.d.tstest/integration/test/fixtures/contract.json
| async connect(bindingInput) { | ||
| if (driverConnected || connectPromise) { | ||
| throw new Error('SQLite client already connected'); | ||
| } | ||
|
|
||
| if (bindingInput !== undefined) { | ||
| binding = resolveSqliteBinding(bindingInput); | ||
| } | ||
|
|
||
| if (binding === undefined) { | ||
| throw new Error( | ||
| 'SQLite binding not configured. Pass path to sqlite(...) or call db.connect({ path }).', | ||
| ); | ||
| } | ||
|
|
||
| const runtime = getRuntime(); | ||
| if (driverConnected) { | ||
| return runtime; | ||
| } | ||
|
|
||
| await connectDriver(binding); |
There was a problem hiding this comment.
Make connect() await in-flight work and clear stale failures before retrying.
If runtime() has already started a background open, Line 171 throws SQLite client already connected instead of awaiting the same connectPromise. After a failed open, backgroundConnectError remains set and connect() calls getRuntime() before clearing it, so callers cannot retry with a corrected path even though connectDriver() reset connectPromise.
Suggested fix
async connect(bindingInput) {
- if (driverConnected || connectPromise) {
+ if (driverConnected) {
throw new Error('SQLite client already connected');
}
+ if (connectPromise) {
+ if (bindingInput !== undefined) {
+ throw new Error('SQLite client connection already in progress');
+ }
+ await connectPromise;
+ return getRuntime();
+ }
if (bindingInput !== undefined) {
binding = resolveSqliteBinding(bindingInput);
}
if (binding === undefined) {
throw new Error(
'SQLite binding not configured. Pass path to sqlite(...) or call db.connect({ path }).',
);
}
+ backgroundConnectError = undefined;
const runtime = getRuntime();
if (driverConnected) {
return runtime;
}
await connectDriver(binding);
return runtime;
},📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| async connect(bindingInput) { | |
| if (driverConnected || connectPromise) { | |
| throw new Error('SQLite client already connected'); | |
| } | |
| if (bindingInput !== undefined) { | |
| binding = resolveSqliteBinding(bindingInput); | |
| } | |
| if (binding === undefined) { | |
| throw new Error( | |
| 'SQLite binding not configured. Pass path to sqlite(...) or call db.connect({ path }).', | |
| ); | |
| } | |
| const runtime = getRuntime(); | |
| if (driverConnected) { | |
| return runtime; | |
| } | |
| await connectDriver(binding); | |
| async connect(bindingInput) { | |
| if (driverConnected) { | |
| throw new Error('SQLite client already connected'); | |
| } | |
| if (connectPromise) { | |
| if (bindingInput !== undefined) { | |
| throw new Error('SQLite client connection already in progress'); | |
| } | |
| await connectPromise; | |
| return getRuntime(); | |
| } | |
| if (bindingInput !== undefined) { | |
| binding = resolveSqliteBinding(bindingInput); | |
| } | |
| if (binding === undefined) { | |
| throw new Error( | |
| 'SQLite binding not configured. Pass path to sqlite(...) or call db.connect({ path }).', | |
| ); | |
| } | |
| backgroundConnectError = undefined; | |
| const runtime = getRuntime(); | |
| if (driverConnected) { | |
| return runtime; | |
| } | |
| await connectDriver(binding); |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/3-extensions/sqlite/src/runtime/sqlite.ts` around lines 170 - 190,
connect() currently throws when driverConnected or connectPromise is truthy and
doesn't await an in-flight open nor clear stale backgroundConnectError after a
failed open; update connect() to: if connectPromise exists, await connectPromise
and then return getRuntime() (so concurrent callers share the same open), ensure
connectDriver() sets/clears connectPromise and that any backgroundConnectError
is cleared before calling getRuntime() (or cleared immediately when
connectDriver() succeeds/when retrying) so subsequent calls to connect() can
retry with a corrected binding; refer to the connect(), connectPromise,
driverConnected, backgroundConnectError, connectDriver(), and getRuntime()
symbols when making these changes.
1c0b962 to
1baf7fe
Compare
There was a problem hiding this comment.
Actionable comments posted: 3
♻️ Duplicate comments (1)
packages/3-extensions/sqlite/src/runtime/sqlite.ts (1)
170-194:⚠️ Potential issue | 🟡 Minor
connect()rejects concurrent callers instead of awaiting in-flight connection.If
connect()is called while a background connection is in progress (connectPromiseis truthy butdriverConnectedis false), line 171-172 throws "already connected" instead of awaiting the existing connection attempt. This can cause spurious failures when multiple call sites race to connect.🛠️ Suggested approach
async connect(bindingInput) { - if (driverConnected || connectPromise) { + if (driverConnected) { throw new Error('SQLite client already connected'); } + if (connectPromise) { + // Await in-flight connection instead of rejecting + await connectPromise; + return getRuntime(); + } backgroundConnectError = undefined;This allows concurrent
connect()callers to share the same connection attempt.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-extensions/sqlite/src/runtime/sqlite.ts` around lines 170 - 194, The connect() function incorrectly throws when connectPromise is truthy but driverConnected is false, causing concurrent callers to fail; change the logic in connect() to, after resolving binding, check if driverConnected is true then return getRuntime(); otherwise if connectPromise exists await connectPromise (so concurrent callers share the in-flight connect) before returning getRuntime(); ensure any existing connectDriver(binding) still sets connectPromise and clears it on completion/failure so driverConnected and backgroundConnectError are handled consistently (referencing connect(), driverConnected, connectPromise, connectDriver, binding, resolveSqliteBinding, and getRuntime).
🧹 Nitpick comments (3)
test/e2e/sqlite/test/utils.ts (1)
1-4: Preferpatheovernode:pathfor cross-platform consistency.Based on learnings, this repo prefers
patheovernode:pathfor path manipulation, especially in test utilities.♻️ Suggested fix
import { mkdtempSync, readFileSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; -import { join } from 'node:path'; +import { join } from 'pathe'; import { DatabaseSync } from 'node:sqlite';🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/e2e/sqlite/test/utils.ts` around lines 1 - 4, Replace the use of Node's path module with pathe for cross-platform consistency: update the import that currently imports join from 'node:path' to import join from 'pathe' and ensure any usages of join in this file (e.g., in test/e2e/sqlite/test/utils.ts where join is used alongside mkdtempSync, readFileSync, rmSync and tmpdir) continue to work unchanged; no other behavior changes are needed.test/e2e/sqlite/test/orm.test.ts (1)
1-1: Usepathefor path helpers in this test.This repo standardizes on
pathein TypeScript files, so pullingdirname/resolvefromnode:pathdrifts from the existing cross-platform convention.♻️ Suggested change
-import { dirname, resolve } from 'node:path'; +import { dirname, resolve } from 'pathe';As per coding guidelines,
**/*.{ts,tsx,mts,cts}: Usepatheinstead ofnode:pathfor path manipulation in TypeScript files.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/e2e/sqlite/test/orm.test.ts` at line 1, The test imports path helpers from node:path; replace those with pathe equivalents to follow repo conventions. Update the import line using dirname and resolve so both are pulled from 'pathe' (referencing the existing identifiers dirname and resolve in the file) and ensure any subsequent usage in the file continues to call dirname(...) and resolve(...). Run the test to verify no path-related regressions.test/e2e/sqlite/test/sql-builder.test.ts (1)
1-1: Usepathefor path helpers in this test.This repo standardizes on
pathein TypeScript files, so pullingdirname/resolvefromnode:pathdrifts from the existing cross-platform convention.♻️ Suggested change
-import { dirname, resolve } from 'node:path'; +import { dirname, resolve } from 'pathe';As per coding guidelines,
**/*.{ts,tsx,mts,cts}: Usepatheinstead ofnode:pathfor path manipulation in TypeScript files.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/e2e/sqlite/test/sql-builder.test.ts` at line 1, The test currently imports dirname and resolve from node:path; replace that with pathe's helpers by importing { dirname, resolve } from 'pathe' and update any uses accordingly (e.g., references to dirname(...) and resolve(...)) so the test follows the repo convention of using pathe for cross-platform path handling.
🤖 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/7-drivers/sqlite/src/exports/runtime.ts`:
- Around line 117-124: The explain method currently throws
driverError('DRIVER.NOT_CONNECTED', USE_BEFORE_CONNECT_MESSAGE) when the
delegate lacks an explain implementation; change this to a more accurate error
(e.g., driverError('DRIVER.NOT_IMPLEMENTED', 'Driver does not support explain')
or another existing "not implemented/unsupported" error code) so that
SqliteBoundDriver.explain (and `#requireDelegate` / explain.call(delegate,
request)) reports "explain not supported" instead of "not connected"; update the
thrown error code and message in the explain function accordingly.
In `@test/e2e/sqlite/test/orm.test.ts`:
- Around line 213-223: The test currently only checks the create return value;
read the row back before deleting it to ensure SQLite's SELECT preserves null
JSON: after creating with ormClient.TypedRow.create(...), fetch the row via
ormClient.TypedRow.where((r) => r.id.eq(12)).first() (or the equivalent
single-row read helper), assert that the returned object's metadata is null,
then perform the existing ormClient.TypedRow.where((r) =>
r.id.eq(12)).deleteCount() cleanup; update the assertions to use the fetched row
(e.g., found.metadata === null) rather than only created.metadata.
In `@test/e2e/sqlite/test/sql-builder.test.ts`:
- Around line 58-68: The test "callback record select" currently only checks
output shape; update it to assert concrete projected values so the alias mapping
is exercised: after calling runtime.execute(db.users.select((f) => ({ myId:
f.id, myName: f.name })).build()), add an assertion that at least one returned
row (e.g., rows[0]) has the expected myId and myName values from the test
fixture/contract (use known ID/name from the seed data for this runtime),
keeping the existing shape and type assertions.
---
Duplicate comments:
In `@packages/3-extensions/sqlite/src/runtime/sqlite.ts`:
- Around line 170-194: The connect() function incorrectly throws when
connectPromise is truthy but driverConnected is false, causing concurrent
callers to fail; change the logic in connect() to, after resolving binding,
check if driverConnected is true then return getRuntime(); otherwise if
connectPromise exists await connectPromise (so concurrent callers share the
in-flight connect) before returning getRuntime(); ensure any existing
connectDriver(binding) still sets connectPromise and clears it on
completion/failure so driverConnected and backgroundConnectError are handled
consistently (referencing connect(), driverConnected, connectPromise,
connectDriver, binding, resolveSqliteBinding, and getRuntime).
---
Nitpick comments:
In `@test/e2e/sqlite/test/orm.test.ts`:
- Line 1: The test imports path helpers from node:path; replace those with pathe
equivalents to follow repo conventions. Update the import line using dirname and
resolve so both are pulled from 'pathe' (referencing the existing identifiers
dirname and resolve in the file) and ensure any subsequent usage in the file
continues to call dirname(...) and resolve(...). Run the test to verify no
path-related regressions.
In `@test/e2e/sqlite/test/sql-builder.test.ts`:
- Line 1: The test currently imports dirname and resolve from node:path; replace
that with pathe's helpers by importing { dirname, resolve } from 'pathe' and
update any uses accordingly (e.g., references to dirname(...) and resolve(...))
so the test follows the repo convention of using pathe for cross-platform path
handling.
In `@test/e2e/sqlite/test/utils.ts`:
- Around line 1-4: Replace the use of Node's path module with pathe for
cross-platform consistency: update the import that currently imports join from
'node:path' to import join from 'pathe' and ensure any usages of join in this
file (e.g., in test/e2e/sqlite/test/utils.ts where join is used alongside
mkdtempSync, readFileSync, rmSync and tmpdir) continue to work unchanged; no
other behavior changes are needed.
🪄 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: 0d82b04d-0357-4e9b-9405-031ec401dfb2
⛔ Files ignored due to path filters (9)
packages/2-sql/4-lanes/sql-builder/test/fixtures/generated/contract.d.tsis excluded by!**/generated/**packages/2-sql/4-lanes/sql-builder/test/fixtures/generated/contract.jsonis excluded by!**/generated/**packages/3-extensions/sql-orm-client/test/fixtures/generated/contract.d.tsis excluded by!**/generated/**packages/3-extensions/sql-orm-client/test/fixtures/generated/contract.jsonis excluded by!**/generated/**pnpm-lock.yamlis excluded by!**/pnpm-lock.yamltest/e2e/framework/test/fixtures/generated/contract.d.tsis excluded by!**/generated/**test/e2e/framework/test/fixtures/generated/contract.jsonis excluded by!**/generated/**test/e2e/sqlite/test/fixtures/generated/contract.d.tsis excluded by!**/generated/**test/e2e/sqlite/test/fixtures/generated/contract.jsonis excluded by!**/generated/**
📒 Files selected for processing (101)
.gitignorearchitecture.config.jsondocs/reference/capabilities.mdexamples/prisma-next-demo/src/prisma/contract.d.tsexamples/prisma-next-demo/src/prisma/contract.jsonpackage.jsonpackages/2-sql/2-authoring/contract-ts/src/contract-types.tspackages/2-sql/4-lanes/relational-core/src/ast/adapter-types.tspackages/2-sql/4-lanes/relational-core/test/utils.tspackages/2-sql/5-runtime/src/sql-family-adapter.tspackages/2-sql/5-runtime/src/sql-runtime.tspackages/2-sql/5-runtime/test/execution-stack.test.tspackages/2-sql/5-runtime/test/sql-family-adapter.test.tspackages/2-sql/5-runtime/test/sql-runtime.test.tspackages/2-sql/5-runtime/test/utils.tspackages/3-extensions/sql-orm-client/src/collection-mutation-dispatch.tspackages/3-extensions/sql-orm-client/src/collection.tspackages/3-extensions/sql-orm-client/src/query-plan-mutations.tspackages/3-extensions/sql-orm-client/src/query-plan.tspackages/3-extensions/sql-orm-client/test/collection-fixtures.tspackages/3-extensions/sql-orm-client/test/collection-mutation-dispatch.test.tspackages/3-extensions/sql-orm-client/test/collection.state.test.tspackages/3-extensions/sql-orm-client/test/query-plan-mutations.test.tspackages/3-extensions/sqlite/README.mdpackages/3-extensions/sqlite/package.jsonpackages/3-extensions/sqlite/src/exports/runtime.tspackages/3-extensions/sqlite/src/runtime/binding.tspackages/3-extensions/sqlite/src/runtime/sqlite.tspackages/3-extensions/sqlite/tsconfig.jsonpackages/3-extensions/sqlite/tsconfig.prod.jsonpackages/3-extensions/sqlite/tsdown.config.tspackages/3-extensions/sqlite/vitest.config.tspackages/3-targets/3-targets/sqlite/README.mdpackages/3-targets/3-targets/sqlite/package.jsonpackages/3-targets/3-targets/sqlite/src/core/descriptor-meta.tspackages/3-targets/3-targets/sqlite/src/exports/control.tspackages/3-targets/3-targets/sqlite/src/exports/pack.tspackages/3-targets/3-targets/sqlite/src/exports/runtime.tspackages/3-targets/3-targets/sqlite/tsconfig.jsonpackages/3-targets/3-targets/sqlite/tsconfig.prod.jsonpackages/3-targets/3-targets/sqlite/tsdown.config.tspackages/3-targets/3-targets/sqlite/vitest.config.tspackages/3-targets/6-adapters/postgres/src/core/adapter.tspackages/3-targets/6-adapters/postgres/src/core/descriptor-meta.tspackages/3-targets/6-adapters/sqlite/README.mdpackages/3-targets/6-adapters/sqlite/package.jsonpackages/3-targets/6-adapters/sqlite/src/core/adapter.tspackages/3-targets/6-adapters/sqlite/src/core/codec-ids.tspackages/3-targets/6-adapters/sqlite/src/core/codecs.tspackages/3-targets/6-adapters/sqlite/src/core/descriptor-meta.tspackages/3-targets/6-adapters/sqlite/src/core/sql-utils.tspackages/3-targets/6-adapters/sqlite/src/core/types.tspackages/3-targets/6-adapters/sqlite/src/exports/adapter.tspackages/3-targets/6-adapters/sqlite/src/exports/codec-types.tspackages/3-targets/6-adapters/sqlite/src/exports/column-types.tspackages/3-targets/6-adapters/sqlite/src/exports/control.tspackages/3-targets/6-adapters/sqlite/src/exports/runtime.tspackages/3-targets/6-adapters/sqlite/src/exports/types.tspackages/3-targets/6-adapters/sqlite/test/adapter.test.tspackages/3-targets/6-adapters/sqlite/test/codecs.test.tspackages/3-targets/6-adapters/sqlite/tsconfig.jsonpackages/3-targets/6-adapters/sqlite/tsconfig.prod.jsonpackages/3-targets/6-adapters/sqlite/tsdown.config.tspackages/3-targets/6-adapters/sqlite/vitest.config.tspackages/3-targets/7-drivers/sqlite/README.mdpackages/3-targets/7-drivers/sqlite/package.jsonpackages/3-targets/7-drivers/sqlite/src/core/descriptor-meta.tspackages/3-targets/7-drivers/sqlite/src/exports/control.tspackages/3-targets/7-drivers/sqlite/src/exports/runtime.tspackages/3-targets/7-drivers/sqlite/src/normalize-error.tspackages/3-targets/7-drivers/sqlite/src/sqlite-driver.tspackages/3-targets/7-drivers/sqlite/test/control-driver.test.tspackages/3-targets/7-drivers/sqlite/test/runtime-driver.test.tspackages/3-targets/7-drivers/sqlite/test/sqlite-driver.test.tspackages/3-targets/7-drivers/sqlite/tsconfig.jsonpackages/3-targets/7-drivers/sqlite/tsconfig.prod.jsonpackages/3-targets/7-drivers/sqlite/tsdown.config.tspackages/3-targets/7-drivers/sqlite/vitest.config.tstest/e2e/sqlite/biome.jsonctest/e2e/sqlite/package.jsontest/e2e/sqlite/test/fixtures/contract.tstest/e2e/sqlite/test/fixtures/prisma-next.config.tstest/e2e/sqlite/test/orm.test.tstest/e2e/sqlite/test/sql-builder.test.tstest/e2e/sqlite/test/utils.tstest/e2e/sqlite/tsconfig.jsontest/e2e/sqlite/vitest.config.tstest/integration/test/authoring/parity/core-surface/expected.contract.jsontest/integration/test/authoring/parity/default-cuid-2/expected.contract.jsontest/integration/test/authoring/parity/default-dbgenerated/expected.contract.jsontest/integration/test/authoring/parity/default-nanoid-16/expected.contract.jsontest/integration/test/authoring/parity/default-nanoid/expected.contract.jsontest/integration/test/authoring/parity/default-pack-slugid/expected.contract.jsontest/integration/test/authoring/parity/default-ulid/expected.contract.jsontest/integration/test/authoring/parity/default-uuid-v4/expected.contract.jsontest/integration/test/authoring/parity/default-uuid-v7/expected.contract.jsontest/integration/test/authoring/parity/map-attributes/expected.contract.jsontest/integration/test/authoring/parity/pgvector-named-type/expected.contract.jsontest/integration/test/authoring/parity/relation-backrelation-list/expected.contract.jsontest/integration/test/fixtures/contract.d.tstest/integration/test/fixtures/contract.json
✅ Files skipped from review due to trivial changes (55)
- examples/prisma-next-demo/src/prisma/contract.json
- packages/3-extensions/sqlite/tsconfig.json
- packages/3-extensions/sqlite/tsconfig.prod.json
- packages/3-targets/3-targets/sqlite/tsconfig.json
- packages/3-targets/6-adapters/sqlite/src/exports/adapter.ts
- packages/3-targets/6-adapters/sqlite/tsconfig.prod.json
- packages/3-extensions/sqlite/tsdown.config.ts
- packages/3-targets/3-targets/sqlite/vitest.config.ts
- packages/3-targets/6-adapters/postgres/src/core/descriptor-meta.ts
- packages/3-targets/6-adapters/sqlite/tsconfig.json
- packages/3-targets/6-adapters/sqlite/src/exports/types.ts
- packages/3-targets/7-drivers/sqlite/tsconfig.prod.json
- test/e2e/sqlite/biome.jsonc
- test/integration/test/authoring/parity/default-cuid-2/expected.contract.json
- test/e2e/sqlite/tsconfig.json
- test/integration/test/fixtures/contract.json
- test/integration/test/authoring/parity/pgvector-named-type/expected.contract.json
- examples/prisma-next-demo/src/prisma/contract.d.ts
- packages/3-extensions/sql-orm-client/src/collection.ts
- packages/3-extensions/sqlite/README.md
- packages/3-extensions/sqlite/src/exports/runtime.ts
- packages/3-targets/3-targets/sqlite/src/core/descriptor-meta.ts
- packages/3-targets/6-adapters/sqlite/src/exports/codec-types.ts
- packages/3-targets/7-drivers/sqlite/src/core/descriptor-meta.ts
- packages/3-targets/7-drivers/sqlite/tsdown.config.ts
- test/e2e/sqlite/test/fixtures/prisma-next.config.ts
- test/integration/test/authoring/parity/default-dbgenerated/expected.contract.json
- test/integration/test/authoring/parity/default-nanoid-16/expected.contract.json
- test/integration/test/authoring/parity/default-ulid/expected.contract.json
- test/integration/test/authoring/parity/default-pack-slugid/expected.contract.json
- test/integration/test/authoring/parity/map-attributes/expected.contract.json
- packages/3-targets/6-adapters/sqlite/tsdown.config.ts
- packages/3-targets/3-targets/sqlite/tsconfig.prod.json
- packages/3-extensions/sql-orm-client/test/query-plan-mutations.test.ts
- packages/3-targets/3-targets/sqlite/README.md
- packages/3-targets/3-targets/sqlite/package.json
- test/e2e/sqlite/vitest.config.ts
- test/integration/test/authoring/parity/default-nanoid/expected.contract.json
- packages/3-targets/6-adapters/sqlite/src/core/types.ts
- packages/3-extensions/sqlite/src/runtime/binding.ts
- architecture.config.json
- .gitignore
- packages/3-targets/6-adapters/sqlite/README.md
- packages/3-targets/7-drivers/sqlite/test/runtime-driver.test.ts
- packages/2-sql/5-runtime/src/sql-runtime.ts
- packages/3-targets/6-adapters/sqlite/src/core/codec-ids.ts
- packages/3-targets/7-drivers/sqlite/package.json
- packages/3-targets/7-drivers/sqlite/tsconfig.json
- packages/3-extensions/sqlite/package.json
- packages/3-targets/7-drivers/sqlite/README.md
- packages/3-targets/7-drivers/sqlite/test/sqlite-driver.test.ts
- packages/3-targets/6-adapters/sqlite/src/exports/column-types.ts
- test/integration/test/authoring/parity/default-uuid-v7/expected.contract.json
- packages/3-targets/6-adapters/sqlite/package.json
- packages/3-targets/3-targets/sqlite/src/exports/runtime.ts
🚧 Files skipped from review as they are similar to previous changes (30)
- packages/2-sql/5-runtime/test/execution-stack.test.ts
- packages/2-sql/5-runtime/test/sql-runtime.test.ts
- docs/reference/capabilities.md
- packages/2-sql/4-lanes/relational-core/src/ast/adapter-types.ts
- packages/2-sql/4-lanes/relational-core/test/utils.ts
- packages/2-sql/5-runtime/test/sql-family-adapter.test.ts
- packages/2-sql/5-runtime/test/utils.ts
- packages/3-extensions/sql-orm-client/src/query-plan.ts
- packages/3-extensions/sqlite/vitest.config.ts
- packages/3-targets/3-targets/sqlite/src/exports/pack.ts
- packages/3-targets/3-targets/sqlite/tsdown.config.ts
- packages/3-targets/6-adapters/postgres/src/core/adapter.ts
- packages/3-extensions/sql-orm-client/test/collection.state.test.ts
- packages/3-extensions/sql-orm-client/test/collection-fixtures.ts
- packages/3-targets/7-drivers/sqlite/test/control-driver.test.ts
- test/integration/test/authoring/parity/core-surface/expected.contract.json
- test/integration/test/authoring/parity/default-uuid-v4/expected.contract.json
- packages/3-targets/6-adapters/sqlite/src/exports/control.ts
- packages/3-targets/6-adapters/sqlite/vitest.config.ts
- packages/3-extensions/sql-orm-client/src/query-plan-mutations.ts
- packages/3-extensions/sql-orm-client/src/collection-mutation-dispatch.ts
- packages/3-targets/6-adapters/sqlite/src/core/sql-utils.ts
- packages/3-targets/6-adapters/sqlite/src/exports/runtime.ts
- packages/3-targets/6-adapters/sqlite/test/codecs.test.ts
- packages/3-targets/6-adapters/sqlite/src/core/descriptor-meta.ts
- packages/3-extensions/sql-orm-client/test/collection-mutation-dispatch.test.ts
- packages/3-targets/6-adapters/sqlite/src/core/codecs.ts
- test/integration/test/authoring/parity/relation-backrelation-list/expected.contract.json
- packages/3-targets/6-adapters/sqlite/test/adapter.test.ts
- packages/2-sql/5-runtime/src/sql-family-adapter.ts
wmadden
left a comment
There was a problem hiding this comment.
Code Review — Approving with inline comments
This is a preemptive approval. Please address or respond to the inline comments before merging — no re-review needed.
Summary
This PR adds SQLite as the second SQL target via four new packages following the Postgres 4-tier pattern. Cross-cutting changes to shared code are minimal and well-factored. The code is clean, well-tested, and consistent with project conventions (~1,451 lines of implementation across ~6.5k LOC total). Findings below are focused on correctness edge cases and structural improvements.
What looks solid
- Adapter SQL rendering — thorough handling of all AST node types with 34 golden tests locking the output
- Codec design — eight codecs with typed encode/decode and explicit traits; literal
codecIdtypes flow correctly viaas const - Split-insert logic —
groupRowsByColumnSignaturewith deliberate order-preservation for autoincrement correctness - Driver state machine — discriminated union with three states avoids boolean flag sprawl
- Error normalization — correct extended-error-code masking (
errcode & 0xff) - Type preservation fix — the correct, minimal fix for literal type inference
- E2E tests — real file-backed databases with
expectTypeOfassertions proving type flow
Six inline findings (F01–F06) are posted below.
| async connect(binding: SqliteBinding): Promise<void> { | ||
| if (this.#state.kind !== 'connected') { | ||
| this.#state = { | ||
| kind: 'connected', | ||
| path: binding.path, | ||
| conn: new SqliteConnectionImpl(openConnection(binding.path)), | ||
| }; | ||
| } |
There was a problem hiding this comment.
F01 — connect() allows reconnection after close()
connect() checks this.#state.kind !== 'connected', which means a closed driver can be reconnected. Callers can't distinguish between "not yet connected" and "shut down".
Either document the allowed state transitions (if reconnection after close is intentional), or guard against it:
async connect(binding: SqliteBinding): Promise<void> {
if (this.#state.kind === 'closed') {
throw new Error('SQLite driver has been closed. Create a new driver instance.');
}
if (this.#state.kind === 'connected') return;
// ...
}| let backgroundConnectError: unknown; | ||
|
|
||
| const connectDriver = async (resolvedBinding: SqliteBinding): Promise<void> => { | ||
| if (driverConnected) return; | ||
| if (!runtimeDriver) throw new Error('SQLite runtime driver missing'); | ||
| if (connectPromise) return connectPromise; | ||
| connectPromise = runtimeDriver | ||
| .connect(resolvedBinding) | ||
| .then(() => { | ||
| driverConnected = true; | ||
| }) | ||
| .catch((err) => { | ||
| backgroundConnectError = err; | ||
| connectPromise = undefined; | ||
| throw err; | ||
| }); | ||
| return connectPromise; | ||
| }; | ||
|
|
||
| const getRuntime = (): Runtime => { | ||
| if (backgroundConnectError !== undefined) { | ||
| throw backgroundConnectError; |
There was a problem hiding this comment.
F03 — connect() fails after a failed background connect
When connectDriver fails, backgroundConnectError is stored and re-thrown on every subsequent getRuntime() call. But calling connect({ path: '/good' }) after a failed background connect throws "already connected" because runtimeInstance was already created (even though connection failed). The recovery path is broken:
sqlite({ path: '/bad' })— creates clientruntime()— creates runtime, triggers background connect which failsruntime()— throws storedbackgroundConnectErrorconnect({ path: '/good' })— throws becauseruntimeInstanceexists
Suggestion: allow connect() after a failed background connect by checking whether the driver is actually connected, not just whether a runtime exists.
- Move implementation from exports/ to core/ files (F06): driver, adapter, and target packages now have thin re-export files with implementation in core/runtime-driver, core/control-driver, core/runtime-adapter, etc. - Use === undefined instead of !value in adapter INSERT check (F02) - Fix misleading DRIVER.NOT_CONNECTED error code for explain (CR3) - Use parameterized queries for marker insertion in e2e utils (F04) - Add read-back assertion in null JSON round-trip test (CR4) - Assert concrete values in callback select test (CR5) - Add missing SQLite globs to architecture.config.json (CR1) - Include sqlite e2e tests in test:e2e script
There was a problem hiding this comment.
Actionable comments posted: 5
🧹 Nitpick comments (1)
test/e2e/sqlite/test/orm.test.ts (1)
86-87: Use object matchers for related field assertions.These assertions validate related properties from the same object; prefer
toMatchObject(...)instead of multipletoBe(...)calls.Suggested diff
- expect(user.id).toBe(200); - expect(user.name).toBe('Created'); + expect(user).toMatchObject({ id: 200, name: 'Created' }); - expect(rows[0]!.id).toBe(500); - expect(rows[1]!.id).toBe(501); + expect(rows[0]).toMatchObject({ id: 500 }); + expect(rows[1]).toMatchObject({ id: 501 }); - expect(result.id).toBe(800); - expect(result.name).toBe('Upserted'); + expect(result).toMatchObject({ id: 800, name: 'Upserted' }); - expect(result.id).toBe(801); - expect(result.name).toBe('UpsertUpdated'); + expect(result).toMatchObject({ id: 801, name: 'UpsertUpdated' });As per coding guidelines,
**/*.test.ts: "Prefer object matchers (toMatchObject) over multiple individualexpect().toBe()calls when checking 2 or more related values in tests."Also applies to: 109-110, 255-257, 270-271
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/e2e/sqlite/test/orm.test.ts` around lines 86 - 87, Replace the multiple related assertions on the same object with a single object matcher: instead of expect(user.id).toBe(200) and expect(user.name).toBe('Created'), use expect(user).toMatchObject({ id: 200, name: 'Created' }); apply the same change pattern to the other grouped assertions flagged in this test file (the other occurrences that assert multiple properties from the same object).
🤖 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/6-adapters/sqlite/src/core/adapter.ts`:
- Around line 34-43: defaultCapabilities is only shallow-frozen so
defaultCapabilities.sql remains mutable and shared; make the capabilities fully
immutable by deep-freezing the nested sql map (either by recursively freezing
objects or explicitly freezing defaultCapabilities.sql after creation). Update
the code around the defaultCapabilities constant so that defaultCapabilities and
its sql property are both Object.freeze'd (or use a small deepFreeze helper) to
prevent runtime mutation across adapter instances.
- Around line 431-451: The code currently derives columnOrder from the firstRow
and then silently truncates extra keys in subsequent rows; before building the
multi-row VALUES, validate that each row has exactly the same set of keys as
columnOrder (same length and every key matches), and if any row differs (extra
or missing keys) throw a clear Error that includes the offending row index and
key name; perform this check just after computing columnOrder and before mapping
rows (use rows, firstRow, columnOrder, quoteIdentifier, renderInsertValue, table
identifiers to locate the spot) so the INSERT either proceeds with uniform row
shapes or fails fast.
In `@packages/3-targets/7-drivers/sqlite/src/core/control-driver.ts`:
- Around line 17-24: The query method in ControlDriver (`async query<Row =
Record<string, unknown>>(sql, params?)`) currently uses a blind cast `(params ??
[]) as SQLInputValue[]`; replace this with a type-guard that verifies each
element is a valid SQLInputValue before passing to stmt.all. Implement a
predicate function (e.g., isSQLInputValue(value): value is SQLInputValue) and
use it to validate or map `params` (rejecting or throwing a clear TypeError if
any element fails), then call `this.db.prepare(sql)` and
`stmt.all(...validatedParams)`; keep the returned `{ rows }` behavior unchanged.
Ensure the new validation routine is used in `ControlDriverInstance.query` (or
the containing class/method) so no blind casts remain.
In `@packages/3-targets/7-drivers/sqlite/src/core/runtime-driver.ts`:
- Around line 103-110: The close() method can leave `#closed` false if
delegate.close() rejects; change the flow so lifecycle state is updated
regardless of errors by setting this.#closed = true before awaiting
delegate.close() or by using a try/finally around await delegate.close() to
ensure this.#closed is flipped even if delegate.close() throws; adjust
references to this.#delegate (keep nulling it as currently done) and ensure
delegate.close() is still awaited but does not prevent the `#closed` state from
being updated.
In `@test/e2e/sqlite/test/orm.test.ts`:
- Line 1: Replace the Node builtin import with the repo-standard pathe import:
change the import that currently pulls dirname and resolve from 'node:path' to
import the same symbols from 'pathe' so TypeScript path utilities use pathe;
update the import statement referencing dirname and resolve to come from 'pathe'
in the file containing the test (where dirname and resolve are used).
---
Nitpick comments:
In `@test/e2e/sqlite/test/orm.test.ts`:
- Around line 86-87: Replace the multiple related assertions on the same object
with a single object matcher: instead of expect(user.id).toBe(200) and
expect(user.name).toBe('Created'), use expect(user).toMatchObject({ id: 200,
name: 'Created' }); apply the same change pattern to the other grouped
assertions flagged in this test file (the other occurrences that assert multiple
properties from the same object).
🪄 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: ed207734-e812-4038-b802-0a1ae30af480
📒 Files selected for processing (20)
architecture.config.jsonpackage.jsonpackages/3-targets/3-targets/sqlite/src/core/control-target.tspackages/3-targets/3-targets/sqlite/src/core/runtime-target.tspackages/3-targets/3-targets/sqlite/src/exports/control.tspackages/3-targets/3-targets/sqlite/src/exports/runtime.tspackages/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/runtime-adapter.tspackages/3-targets/6-adapters/sqlite/src/exports/column-types.tspackages/3-targets/6-adapters/sqlite/src/exports/control.tspackages/3-targets/6-adapters/sqlite/src/exports/runtime.tspackages/3-targets/7-drivers/sqlite/src/core/control-driver.tspackages/3-targets/7-drivers/sqlite/src/core/runtime-driver.tspackages/3-targets/7-drivers/sqlite/src/exports/control.tspackages/3-targets/7-drivers/sqlite/src/exports/runtime.tstest/e2e/sqlite/test/orm.test.tstest/e2e/sqlite/test/sql-builder.test.tstest/e2e/sqlite/test/utils.ts
✅ Files skipped from review due to trivial changes (6)
- packages/3-targets/3-targets/sqlite/src/exports/runtime.ts
- architecture.config.json
- packages/3-targets/6-adapters/sqlite/src/exports/runtime.ts
- test/e2e/sqlite/test/utils.ts
- test/e2e/sqlite/test/sql-builder.test.ts
- packages/3-targets/7-drivers/sqlite/src/exports/control.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- packages/3-targets/7-drivers/sqlite/src/exports/runtime.ts
- package.json
| const defaultCapabilities = Object.freeze({ | ||
| sql: { | ||
| orderBy: true, | ||
| limit: true, | ||
| lateral: false, | ||
| jsonAgg: true, | ||
| returning: true, | ||
| enums: false, | ||
| }, | ||
| }); |
There was a problem hiding this comment.
Deep-freeze the nested sql capability map.
Object.freeze() is shallow here. defaultCapabilities.sql stays mutable and is shared across every adapter instance, so one accidental write can flip feature-gating process-wide.
Suggested fix
const defaultCapabilities = Object.freeze({
- sql: {
+ sql: Object.freeze({
orderBy: true,
limit: true,
lateral: false,
jsonAgg: true,
returning: true,
enums: false,
- },
+ }),
});🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/3-targets/6-adapters/sqlite/src/core/adapter.ts` around lines 34 -
43, defaultCapabilities is only shallow-frozen so defaultCapabilities.sql
remains mutable and shared; make the capabilities fully immutable by
deep-freezing the nested sql map (either by recursively freezing objects or
explicitly freezing defaultCapabilities.sql after creation). Update the code
around the defaultCapabilities constant so that defaultCapabilities and its sql
property are both Object.freeze'd (or use a small deepFreeze helper) to prevent
runtime mutation across adapter instances.
| async query<Row = Record<string, unknown>>( | ||
| sql: string, | ||
| params?: readonly unknown[], | ||
| ): Promise<{ readonly rows: Row[] }> { | ||
| try { | ||
| const stmt = this.db.prepare(sql); | ||
| const rows = stmt.all(...((params ?? []) as SQLInputValue[])) as Row[]; | ||
| return { rows }; |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Verify whether this cast pattern appears and inspect the local driver interface contract.
set -euo pipefail
rg -nP --type=ts 'as\s+SQLInputValue\[\]' packages
rg -nP --type=ts 'interface\s+ControlDriverInstance|query\s*\(\s*sql:\s*string' packagesRepository: prisma/prisma-next
Length of output: 738
🏁 Script executed:
# Find SQLInputValue type definition
rg -n 'type\s+SQLInputValue|interface\s+SQLInputValue' packages --type tsRepository: prisma/prisma-next
Length of output: 44
🏁 Script executed:
# Inspect ControlDriverInstance interface definition
cat -n packages/1-framework/1-core/framework-components/src/control-instances.ts | head -100Repository: prisma/prisma-next
Length of output: 2967
🏁 Script executed:
# Check if SQLiteControlDriver.query() is called from control plane code and if params are pre-validated
rg -B5 -A3 'ControlDriver.*query|\.query\(' packages/3-targets/7-drivers/sqlite --type ts | head -60Repository: prisma/prisma-next
Length of output: 6043
🏁 Script executed:
# Check the sqlite-driver.ts file to see if it has similar pattern in runtime plane (should not be reviewed, but useful for context)
sed -n '1,40p' packages/3-targets/7-drivers/sqlite/src/sqlite-driver.ts | cat -nRepository: prisma/prisma-next
Length of output: 1456
Replace blind parameter cast with type-guard validation.
The cast (params ?? []) as SQLInputValue[] bypasses type safety and violates the coding guideline: "No blind casts in production code… Prefer type predicates or fix the type surface." Since ControlDriverInstance.query() accepts readonly unknown[], invalid values could slip through. Validate with a type predicate before binding.
Proposed refactor
export class SqliteControlDriver implements ControlDriverInstance<'sql', 'sqlite'> {
@@
async query<Row = Record<string, unknown>>(
sql: string,
params?: readonly unknown[],
): Promise<{ readonly rows: Row[] }> {
try {
const stmt = this.db.prepare(sql);
- const rows = stmt.all(...((params ?? []) as SQLInputValue[])) as Row[];
+ const boundParams: SQLInputValue[] = [];
+ for (const [index, value] of (params ?? []).entries()) {
+ if (!isSqliteInputValue(value)) {
+ throw errorRuntime('Invalid SQLite bind parameter', {
+ why: `Unsupported bind parameter at index ${index}`,
+ fix: 'Use null, string, number, bigint, or Uint8Array values',
+ });
+ }
+ boundParams.push(value);
+ }
+ const rows = stmt.all(...boundParams) as Row[];
return { rows };
} catch (error) {
throw normalizeSqliteError(error);
}
}
@@
}
+
+function isSqliteInputValue(value: unknown): value is SQLInputValue {
+ return (
+ value === null ||
+ typeof value === 'string' ||
+ typeof value === 'number' ||
+ typeof value === 'bigint' ||
+ value instanceof Uint8Array
+ );
+}🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/3-targets/7-drivers/sqlite/src/core/control-driver.ts` around lines
17 - 24, The query method in ControlDriver (`async query<Row = Record<string,
unknown>>(sql, params?)`) currently uses a blind cast `(params ?? []) as
SQLInputValue[]`; replace this with a type-guard that verifies each element is a
valid SQLInputValue before passing to stmt.all. Implement a predicate function
(e.g., isSQLInputValue(value): value is SQLInputValue) and use it to validate or
map `params` (rejecting or throwing a clear TypeError if any element fails),
then call `this.db.prepare(sql)` and `stmt.all(...validatedParams)`; keep the
returned `{ rows }` behavior unchanged. Ensure the new validation routine is
used in `ControlDriverInstance.query` (or the containing class/method) so no
blind casts remain.
Scaffold @prisma-next/driver-sqlite and @prisma-next/adapter-sqlite as the first two packages for the SQLite target (Milestone 1). Driver: file-based SqliteDriver wrapping node:sqlite DatabaseSync with per-connection isolation, FK enforcement, busy_timeout, error normalization to SqlQueryError/SqlConnectionError, and unbound/control driver descriptors. Adapter: 8 SQLite codecs (text, integer, real, blob, boolean, datetime, json, bigint) plus 4 inherited SQL codecs, column-type descriptors, and capability metadata (returning: true, lateral: false, jsonAgg: true, enums: false).
Adapter: implement SQLite SQL renderer with ? positional params, json_object/json_group_array, ILIKE→LIKE mapping, no DISTINCT ON or LATERAL. DEFAULT in INSERT VALUES throws (unsupported by SQLite). Driver: remove primary connection — all operations acquire fresh connections via openConnection(), simplifying lifecycle management. Capabilities scoped under sql namespace, not sqlite.
…ation Add @prisma-next/target-sqlite with runtime target descriptor and pack ref for contract authoring. Add @prisma-next/sqlite extension with sqlite() factory function mirroring postgres() — lazy client with sql, schema, orm surfaces, connect()/runtime() lifecycle. Add adapter create() method for SqlRuntimeAdapterDescriptor compliance. Register all 4 SQLite packages in architecture.config.json with correct domain/layer/plane mappings. lint:deps passes with no violations.
- Move MarkerReader to AdapterProfile so each target provides its own marker SQL (Postgres: schema-qualified $1 params, SQLite: flat table ? params) - Fix sqlite() factory to pass context (not contract) to ORM builder - Add codec traits to all SQLite codecs for ORM field accessor methods - Fix codec definitions to let TS infer literal types (remove incorrect explicit generic params that broke type inference) - Remove ColumnTypeDescriptor annotation from column-type exports to preserve literal codecId types through the contract builder - Add sql-builder-new integration tests: SELECT, INSERT, UPDATE, DELETE with RETURNING, codec round-trips (boolean, datetime, JSON), and capability gating (lateralJoin, distinctOn blocked at type + runtime) - Add ORM integration tests: findMany, findFirst, create, createAll, update, updateAll, delete, deleteAll, includeMany, upsert, and typed row codec verification - Add expectTypeOf assertions verifying row types flow correctly from contract through sql-builder and ORM
Update all SQLite packages to use renamed/restructured packages from main: - core-control-plane → errors + framework-components - core-execution-plane → framework-components/execution - sql-lane/sql-builder-new → sql-builder - SqlContract → Contract from @prisma-next/contract/types - validateContract now requires codecLookup parameter - Contract shape: storageHash moved inside storage, added roots/capabilities/meta - sql-builder API: use runtime().execute(plan) pattern instead of builder .first()/.all()
…ulti-row INSERT Postgres supports DEFAULT as a value in multi-row INSERT statements; SQLite does not. Add capability sql.defaultInInsert (true for Postgres, absent for SQLite) so the ORM can branch: - When present: single multi-row INSERT with DEFAULT placeholders - When absent: split into per-column-signature INSERT statements, preserving row order Re-emit all contract fixtures to include the new capability.
Narrow acquireConnection() return type to SqliteConnectionImpl so explain() doesn't need a non-null assertion. Remove unused collect import from sql-builder test.
- target-sqlite pack.ts: fix import path for TargetPackRef - adapter-sqlite codecs test: cast object to string for JSON decode test - sql-runtime execution-stack test: add missing readMarkerStatement - sqlite extension: fix Db generic arity, add runtime to test context type
…plit by ORM The ORM splits mixed-defaults multi-row INSERTs before they reach the adapter, so all rows in a single INSERT now share the same columns. Remove collectInsertColumns union logic, take columns from first row, drop contract parameter from renderInsert.
- Throw on ILIKE instead of silently mapping to LIKE; waiting for #277 to move ilike into an extension with proper capability gating - Document groupRowsByColumnSignature order-preservation as deliberate - Add unit tests for compileInsertReturningSplit/compileInsertCountSplit - Document sql.defaultInInsert capability in capabilities reference
SqliteBoundDriver now holds a persistent SqliteConnectionImpl for top-level execute/query/explain, avoiding per-query file open/close and PRAGMA overhead. acquireConnection() still opens a fresh handle for transaction isolation. Driver state is a discriminated union (unbound | connected | closed) with no separate boolean flags.
…e to staged DSL - Remove operationSignatures (removed from SqlStaticContributions on main) - Remove schema surface from SqliteClient (removed from relational-core on main) - Add readMarkerStatement to relational-core test stub - Migrate test contract from legacy defineContract() builder to staged DSL to preserve literal codecId types through the ORM type chain - Fix ResolveModelFieldToJsType fallback from FieldValue to never so unrecognized model field formats fall through to storage column lookup
…dBuiltModels
StagedBuiltModels had two type-widening issues:
1. Model fields used { codecId, nullable } format instead of the
{ nullable, type: { kind: 'scalar', codecId } } format that
ResolveModelFieldToJsType expects. This caused all ORM field
types to resolve to unknown for staged contracts.
2. Relations were typed as Record<string, ContractRelation>, losing
literal relation names. This prevented .include('posts') from
compiling without casts.
Fix: wrap field codecId in the ContractField type structure, and add
StagedModelRelations/StagedModelRelationNames type helpers to preserve
literal relation keys in the mapped type.
Follow the Postgres README conventions: Package Classification, Responsibilities, Dependencies, Architecture diagrams, Capabilities, and Exports sections. Passes pnpm lint:docs with no new warnings.
…lity The Postgres adapter now declares sql.defaultInInsert: true, which appears in emitted contracts. Fixture expected files were stale.
Cover the defaultInInsert capability branches added for SQLite support: - 6 tests for dispatchSplitMutationRows (no-includes and with-includes) - 2 tests for createAll/createCount split-insert paths - withoutDefaultInInsert helper in collection-fixtures Restores sql-orm-client branch coverage from 92.85% to 94.15%.
- Add minimal ./control exports to target-sqlite and adapter-sqlite (descriptor meta + create() — no migration planner/runner needed) - Add codec type imports to adapter descriptor so emitted contract.d.ts resolves SQLite codec IDs to concrete JS types - Create test/e2e/sqlite/ with prisma-next.config.ts, emitted contract fixtures, and withSqliteTestRuntime helper - Port sql-builder (14) and ORM (18) integration tests to e2e using the emitted Contract type from contract.d.ts - Remove packages/3-extensions/sqlite/test/integration/
…quivalents StagedModelNames and StagedDefinitionModels were removed during the staged terminology refactor but three references in contract-types.ts were not updated.
The generated contract.d.ts and contract.json were gitignored, causing CI typechecks to fail with ~100 errors. Unignore them and add the sqlite e2e package to fixtures:emit and fixtures:check.
- Make createBoundDriverFromBinding synchronous with pre-built state - Move error normalization into openConnection for all callers - Add try/catch to beginTransaction() and release() - Clear stale backgroundConnectError in connect() to allow retries - Remove unreachable ERR_SQLITE_ERROR check in normalize-error - Add empty-row validation to split insert compilers - Fix README plane classification (runtime, authoring) - Add adapter.ts export for createSqliteAdapter
The TypeMaps type gained a FieldOutputTypes parameter on main. Regenerate fixtures so the SQLite e2e contract includes it.
- Move implementation from exports/ to core/ files (F06): driver, adapter, and target packages now have thin re-export files with implementation in core/runtime-driver, core/control-driver, core/runtime-adapter, etc. - Use === undefined instead of !value in adapter INSERT check (F02) - Fix misleading DRIVER.NOT_CONNECTED error code for explain (CR3) - Use parameterized queries for marker insertion in e2e utils (F04) - Add read-back assertion in null JSON round-trip test (CR4) - Assert concrete values in callback select test (CR5) - Add missing SQLite globs to architecture.config.json (CR1) - Include sqlite e2e tests in test:e2e script
Move sqlite e2e tests from the separate @prisma-next/e2e-sqlite-tests package into @prisma-next/e2e-tests under test/sqlite/. This ensures sqlite e2e tests run as part of test:e2e and CI without needing a separate filter. The two test suites have no conflicting dependencies.
The sqlite e2e contract fixtures were not tracked after the package merge because .gitignore excluded the new path. Update the exception and commit the generated contract files.
Consolidate the two driver classes into a single SqliteDriver that implements both SqlDriver and RuntimeDriverInstance. The unbound wrapper was unnecessary since SqliteBoundDriver already had the same state machine. The descriptor now creates SqliteDriver directly. Also fix stale lockfile from rebase (mongodb-memory-server).
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (1)
packages/3-targets/7-drivers/sqlite/src/sqlite-driver.ts (1)
68-187: Consider extracting shared query logic.
SqliteConnectionImplandSqliteTransactionImplhave identical implementations forexecute(),explain(), andquery(). Consider extracting a shared helper or base class to reduce duplication.Suggested approach
// Extract shared query logic function prepareAndExecute<Row>( db: DatabaseSync, request: SqlExecuteRequest, ): Generator<Row> { const stmt = db.prepare(request.sql); return stmt.iterate(...toSqliteParams(request.params)) as Generator<Row>; } function prepareAndQuery<Row>( db: DatabaseSync, sql: string, params?: readonly unknown[], ): Row[] { const stmt = db.prepare(sql); return stmt.all(...toSqliteParams(params)) as Row[]; } // Then use in both classes: // async *execute<Row>(request) { yield* prepareAndExecute<Row>(this.#db, request); }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-targets/7-drivers/sqlite/src/sqlite-driver.ts` around lines 68 - 187, SqliteConnectionImpl and SqliteTransactionImpl duplicate execute/explain/query logic; extract shared helpers (e.g., prepareAndExecute, prepareAndQuery) that take DatabaseSync and use toSqliteParams, then replace both classes' execute/explain/query implementations to delegate (e.g., async *execute(...) { yield* prepareAndExecute(this.#db, request) } and query/explain returning prepareAndQuery results) or move the shared methods into a small base class both classes extend to eliminate duplication while preserving normalizeSqliteError error handling in each method.
🤖 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/6-adapters/sqlite/src/core/adapter.ts`:
- Around line 322-326: The error thrown when expr.op === 'ilike' in adapter.ts
points callers to the wrong workaround; update the error text in the ilike
branch to say that SQLite does not support ILIKE and recommend correct
alternatives such as using LIKE with COLLATE NOCASE or comparing LOWER(column)
to LOWER(value) (or using a case-insensitive collation), so replace the current
message in the ilike check with one that lists these valid SQLite workarounds.
- Around line 34-42: The SQLite adapter's exported defaultCapabilities object
(constant defaultCapabilities in adapter.ts) must explicitly include
sql.defaultInInsert set to false so consumers see it as explicitly unsupported;
update the sql block inside defaultCapabilities to add the key "defaultInInsert:
false" and keep the object frozen (Object.freeze) behavior unchanged so
capability negotiation reports an explicit false instead of "not reported".
In `@packages/3-targets/7-drivers/sqlite/src/sqlite-driver.ts`:
- Around line 53-55: The toSqliteParams function currently unsafely casts
(params ?? []) as SQLInputValue[], bypassing type checks; replace the blind cast
with explicit validation and conversion: iterate over (params ?? []), check each
item against allowed SQLInputValue types (e.g., number, string, null,
Buffer/Uint8Array if supported, boolean if allowed), convert/coerce where
appropriate, and collect into a new SQLInputValue[]; if any parameter is of an
unsupported type, throw a clear error that includes the offending index/value;
keep the function signature and return an empty array when params is undefined.
---
Nitpick comments:
In `@packages/3-targets/7-drivers/sqlite/src/sqlite-driver.ts`:
- Around line 68-187: SqliteConnectionImpl and SqliteTransactionImpl duplicate
execute/explain/query logic; extract shared helpers (e.g., prepareAndExecute,
prepareAndQuery) that take DatabaseSync and use toSqliteParams, then replace
both classes' execute/explain/query implementations to delegate (e.g., async
*execute(...) { yield* prepareAndExecute(this.#db, request) } and query/explain
returning prepareAndQuery results) or move the shared methods into a small base
class both classes extend to eliminate duplication while preserving
normalizeSqliteError error handling in each method.
🪄 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: d5b11afd-5226-4f99-9d0e-fcd036a7b97a
⛔ Files ignored due to path filters (5)
packages/2-sql/4-lanes/sql-builder/test/fixtures/generated/contract.d.tsis excluded by!**/generated/**packages/2-sql/4-lanes/sql-builder/test/fixtures/generated/contract.jsonis excluded by!**/generated/**packages/3-extensions/sql-orm-client/test/fixtures/generated/contract.d.tsis excluded by!**/generated/**packages/3-extensions/sql-orm-client/test/fixtures/generated/contract.jsonis excluded by!**/generated/**pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (85)
.gitignorearchitecture.config.jsondocs/reference/capabilities.mdexamples/prisma-next-demo/src/prisma/contract.d.tsexamples/prisma-next-demo/src/prisma/contract.jsonpackage.jsonpackages/2-sql/2-authoring/contract-ts/src/contract-types.tspackages/2-sql/4-lanes/relational-core/src/ast/adapter-types.tspackages/2-sql/4-lanes/relational-core/test/utils.tspackages/2-sql/5-runtime/src/sql-family-adapter.tspackages/2-sql/5-runtime/src/sql-runtime.tspackages/2-sql/5-runtime/test/execution-stack.test.tspackages/2-sql/5-runtime/test/sql-family-adapter.test.tspackages/2-sql/5-runtime/test/sql-runtime.test.tspackages/2-sql/5-runtime/test/utils.tspackages/3-extensions/sql-orm-client/src/collection-mutation-dispatch.tspackages/3-extensions/sql-orm-client/src/collection.tspackages/3-extensions/sql-orm-client/src/query-plan-mutations.tspackages/3-extensions/sql-orm-client/src/query-plan.tspackages/3-extensions/sql-orm-client/test/collection-fixtures.tspackages/3-extensions/sql-orm-client/test/collection-mutation-dispatch.test.tspackages/3-extensions/sql-orm-client/test/collection.state.test.tspackages/3-extensions/sql-orm-client/test/query-plan-mutations.test.tspackages/3-extensions/sqlite/README.mdpackages/3-extensions/sqlite/package.jsonpackages/3-extensions/sqlite/src/exports/runtime.tspackages/3-extensions/sqlite/src/runtime/binding.tspackages/3-extensions/sqlite/src/runtime/sqlite.tspackages/3-extensions/sqlite/tsconfig.jsonpackages/3-extensions/sqlite/tsconfig.prod.jsonpackages/3-extensions/sqlite/tsdown.config.tspackages/3-extensions/sqlite/vitest.config.tspackages/3-targets/3-targets/sqlite/README.mdpackages/3-targets/3-targets/sqlite/package.jsonpackages/3-targets/3-targets/sqlite/src/core/control-target.tspackages/3-targets/3-targets/sqlite/src/core/descriptor-meta.tspackages/3-targets/3-targets/sqlite/src/core/runtime-target.tspackages/3-targets/3-targets/sqlite/src/exports/control.tspackages/3-targets/3-targets/sqlite/src/exports/pack.tspackages/3-targets/3-targets/sqlite/src/exports/runtime.tspackages/3-targets/3-targets/sqlite/tsconfig.jsonpackages/3-targets/3-targets/sqlite/tsconfig.prod.jsonpackages/3-targets/3-targets/sqlite/tsdown.config.tspackages/3-targets/3-targets/sqlite/vitest.config.tspackages/3-targets/6-adapters/postgres/src/core/adapter.tspackages/3-targets/6-adapters/postgres/src/core/descriptor-meta.tspackages/3-targets/6-adapters/sqlite/README.mdpackages/3-targets/6-adapters/sqlite/package.jsonpackages/3-targets/6-adapters/sqlite/src/core/adapter.tspackages/3-targets/6-adapters/sqlite/src/core/codec-ids.tspackages/3-targets/6-adapters/sqlite/src/core/codecs.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/descriptor-meta.tspackages/3-targets/6-adapters/sqlite/src/core/runtime-adapter.tspackages/3-targets/6-adapters/sqlite/src/core/sql-utils.tspackages/3-targets/6-adapters/sqlite/src/core/types.tspackages/3-targets/6-adapters/sqlite/src/exports/adapter.tspackages/3-targets/6-adapters/sqlite/src/exports/codec-types.tspackages/3-targets/6-adapters/sqlite/src/exports/column-types.tspackages/3-targets/6-adapters/sqlite/src/exports/control.tspackages/3-targets/6-adapters/sqlite/src/exports/runtime.tspackages/3-targets/6-adapters/sqlite/src/exports/types.tspackages/3-targets/6-adapters/sqlite/test/adapter.test.tspackages/3-targets/6-adapters/sqlite/test/codecs.test.tspackages/3-targets/6-adapters/sqlite/tsconfig.jsonpackages/3-targets/6-adapters/sqlite/tsconfig.prod.jsonpackages/3-targets/6-adapters/sqlite/tsdown.config.tspackages/3-targets/6-adapters/sqlite/vitest.config.tspackages/3-targets/7-drivers/sqlite/README.mdpackages/3-targets/7-drivers/sqlite/package.jsonpackages/3-targets/7-drivers/sqlite/src/core/control-driver.tspackages/3-targets/7-drivers/sqlite/src/core/descriptor-meta.tspackages/3-targets/7-drivers/sqlite/src/core/runtime-driver.tspackages/3-targets/7-drivers/sqlite/src/exports/control.tspackages/3-targets/7-drivers/sqlite/src/exports/runtime.tspackages/3-targets/7-drivers/sqlite/src/normalize-error.tspackages/3-targets/7-drivers/sqlite/src/sqlite-driver.tspackages/3-targets/7-drivers/sqlite/test/control-driver.test.tspackages/3-targets/7-drivers/sqlite/test/runtime-driver.test.tspackages/3-targets/7-drivers/sqlite/test/sqlite-driver.test.tspackages/3-targets/7-drivers/sqlite/tsconfig.jsonpackages/3-targets/7-drivers/sqlite/tsconfig.prod.jsonpackages/3-targets/7-drivers/sqlite/tsdown.config.tspackages/3-targets/7-drivers/sqlite/vitest.config.ts
✅ Files skipped from review due to trivial changes (57)
- packages/3-targets/3-targets/sqlite/src/exports/control.ts
- examples/prisma-next-demo/src/prisma/contract.json
- packages/3-targets/6-adapters/sqlite/src/exports/types.ts
- packages/3-targets/3-targets/sqlite/tsconfig.json
- packages/3-targets/3-targets/sqlite/tsconfig.prod.json
- packages/3-targets/7-drivers/sqlite/tsconfig.json
- .gitignore
- packages/3-extensions/sqlite/tsconfig.prod.json
- packages/3-extensions/sqlite/tsconfig.json
- packages/3-extensions/sqlite/tsdown.config.ts
- packages/2-sql/5-runtime/src/sql-runtime.ts
- packages/3-targets/6-adapters/sqlite/tsconfig.prod.json
- packages/3-targets/6-adapters/postgres/src/core/descriptor-meta.ts
- packages/3-targets/3-targets/sqlite/src/exports/runtime.ts
- packages/3-targets/3-targets/sqlite/tsdown.config.ts
- packages/2-sql/5-runtime/test/sql-runtime.test.ts
- packages/3-targets/7-drivers/sqlite/src/exports/control.ts
- packages/3-targets/7-drivers/sqlite/src/exports/runtime.ts
- packages/3-targets/6-adapters/sqlite/src/exports/codec-types.ts
- packages/3-targets/6-adapters/sqlite/src/exports/column-types.ts
- packages/3-targets/7-drivers/sqlite/tsdown.config.ts
- packages/3-targets/6-adapters/sqlite/tsdown.config.ts
- packages/3-targets/6-adapters/sqlite/tsconfig.json
- packages/3-targets/3-targets/sqlite/src/core/control-target.ts
- packages/3-targets/3-targets/sqlite/src/core/descriptor-meta.ts
- packages/3-targets/6-adapters/sqlite/vitest.config.ts
- packages/3-targets/6-adapters/sqlite/src/exports/control.ts
- packages/3-targets/7-drivers/sqlite/tsconfig.prod.json
- packages/3-targets/6-adapters/sqlite/src/core/types.ts
- packages/3-targets/6-adapters/sqlite/src/core/control-adapter.ts
- packages/3-targets/3-targets/sqlite/src/exports/pack.ts
- packages/3-targets/6-adapters/sqlite/src/exports/adapter.ts
- packages/3-extensions/sqlite/README.md
- packages/3-extensions/sql-orm-client/test/query-plan-mutations.test.ts
- packages/3-targets/3-targets/sqlite/src/core/runtime-target.ts
- packages/3-extensions/sqlite/src/exports/runtime.ts
- packages/3-targets/6-adapters/sqlite/src/core/column-types.ts
- packages/2-sql/2-authoring/contract-ts/src/contract-types.ts
- packages/3-targets/7-drivers/sqlite/test/runtime-driver.test.ts
- packages/3-targets/7-drivers/sqlite/README.md
- packages/3-targets/6-adapters/sqlite/src/core/descriptor-meta.ts
- packages/3-targets/7-drivers/sqlite/test/control-driver.test.ts
- packages/3-targets/6-adapters/sqlite/src/core/sql-utils.ts
- packages/3-targets/7-drivers/sqlite/vitest.config.ts
- packages/3-targets/3-targets/sqlite/package.json
- packages/3-targets/3-targets/sqlite/README.md
- packages/3-extensions/sqlite/package.json
- packages/3-targets/6-adapters/sqlite/test/codecs.test.ts
- packages/3-targets/6-adapters/sqlite/src/exports/runtime.ts
- architecture.config.json
- packages/3-targets/7-drivers/sqlite/package.json
- packages/3-targets/6-adapters/sqlite/src/core/codec-ids.ts
- packages/3-targets/7-drivers/sqlite/test/sqlite-driver.test.ts
- packages/3-targets/6-adapters/sqlite/README.md
- packages/3-extensions/sqlite/src/runtime/binding.ts
- packages/3-extensions/sql-orm-client/test/collection-mutation-dispatch.test.ts
- packages/3-targets/6-adapters/sqlite/package.json
🚧 Files skipped from review as they are similar to previous changes (15)
- packages/3-extensions/sql-orm-client/src/query-plan.ts
- packages/2-sql/5-runtime/test/execution-stack.test.ts
- packages/2-sql/5-runtime/src/sql-family-adapter.ts
- packages/3-extensions/sqlite/vitest.config.ts
- packages/3-targets/3-targets/sqlite/vitest.config.ts
- packages/2-sql/4-lanes/relational-core/src/ast/adapter-types.ts
- packages/3-targets/7-drivers/sqlite/src/core/descriptor-meta.ts
- package.json
- packages/3-extensions/sql-orm-client/test/collection-fixtures.ts
- packages/3-targets/6-adapters/sqlite/src/core/runtime-adapter.ts
- packages/3-extensions/sql-orm-client/test/collection.state.test.ts
- packages/3-extensions/sql-orm-client/src/query-plan-mutations.ts
- packages/3-targets/7-drivers/sqlite/src/normalize-error.ts
- packages/3-extensions/sql-orm-client/src/collection-mutation-dispatch.ts
- packages/3-extensions/sqlite/src/runtime/sqlite.ts
| const defaultCapabilities = Object.freeze({ | ||
| sql: { | ||
| orderBy: true, | ||
| limit: true, | ||
| lateral: false, | ||
| jsonAgg: true, | ||
| returning: true, | ||
| enums: false, | ||
| }, |
There was a problem hiding this comment.
Advertise sql.defaultInInsert explicitly on the SQLite profile.
This PR adds sql.defaultInInsert as a stable capability, but the SQLite adapter never reports it here. Leaving the key out means consumers see “not reported” instead of “explicitly unsupported”, which can skew capability negotiation once emitted contracts start pinning this key.
Suggested fix
const defaultCapabilities = Object.freeze({
sql: {
orderBy: true,
limit: true,
lateral: false,
jsonAgg: true,
returning: true,
enums: false,
+ defaultInInsert: false,
},
});🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/3-targets/6-adapters/sqlite/src/core/adapter.ts` around lines 34 -
42, The SQLite adapter's exported defaultCapabilities object (constant
defaultCapabilities in adapter.ts) must explicitly include sql.defaultInInsert
set to false so consumers see it as explicitly unsupported; update the sql block
inside defaultCapabilities to add the key "defaultInInsert: false" and keep the
object frozen (Object.freeze) behavior unchanged so capability negotiation
reports an explicit false instead of "not reported".
| // ilike is not supported by SQLite — waiting for prisma/prisma-next#277 | ||
| // to move ilike into an extension so it can be properly capability-gated. | ||
| if (expr.op === 'ilike') { | ||
| throw new Error('SQLite does not support ILIKE. Use LIKE for case-sensitive matching.'); | ||
| } |
There was a problem hiding this comment.
The ILIKE error text points callers at the wrong workaround.
Rejecting ILIKE is fine, but LIKE is not a case-sensitive replacement here, so this message is misleading.
Suggested fix
if (expr.op === 'ilike') {
- throw new Error('SQLite does not support ILIKE. Use LIKE for case-sensitive matching.');
+ throw new Error('SQLite does not support ILIKE.');
}🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/3-targets/6-adapters/sqlite/src/core/adapter.ts` around lines 322 -
326, The error thrown when expr.op === 'ilike' in adapter.ts points callers to
the wrong workaround; update the error text in the ilike branch to say that
SQLite does not support ILIKE and recommend correct alternatives such as using
LIKE with COLLATE NOCASE or comparing LOWER(column) to LOWER(value) (or using a
case-insensitive collation), so replace the current message in the ilike check
with one that lists these valid SQLite workarounds.
| function toSqliteParams(params: readonly unknown[] | undefined): SQLInputValue[] { | ||
| return (params ?? []) as SQLInputValue[]; | ||
| } |
There was a problem hiding this comment.
Replace blind parameter cast with validation.
Same issue as in control-driver.ts: the cast (params ?? []) as SQLInputValue[] bypasses type safety. Consider validating parameters before use.
Proposed fix
+function isSqliteInputValue(value: unknown): value is SQLInputValue {
+ return (
+ value === null ||
+ typeof value === 'string' ||
+ typeof value === 'number' ||
+ typeof value === 'bigint' ||
+ value instanceof Uint8Array
+ );
+}
+
function toSqliteParams(params: readonly unknown[] | undefined): SQLInputValue[] {
- return (params ?? []) as SQLInputValue[];
+ return (params ?? []).map((value, index) => {
+ if (!isSqliteInputValue(value)) {
+ throw new TypeError(`Invalid SQLite bind parameter at index ${index}`);
+ }
+ return value;
+ });
}🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/3-targets/7-drivers/sqlite/src/sqlite-driver.ts` around lines 53 -
55, The toSqliteParams function currently unsafely casts (params ?? []) as
SQLInputValue[], bypassing type checks; replace the blind cast with explicit
validation and conversion: iterate over (params ?? []), check each item against
allowed SQLInputValue types (e.g., number, string, null, Buffer/Uint8Array if
supported, boolean if allowed), convert/coerce where appropriate, and collect
into a new SQLInputValue[]; if any parameter is of an unsupported type, throw a
clear error that includes the offending index/value; keep the function signature
and return an empty array when params is undefined.
closes TML-2167
Intent
Add SQLite as the second concrete target in Prisma Next, validating the multi-target adapter architecture. Four new packages (driver, adapter, target, extension) follow the Postgres 4-tier pattern. All dialect differences are handled through adapters, capabilities, and codecs — no target-name conditionals anywhere in shared code. This covers milestones 1–3 of the project plan: driver + codecs, AST→SQL lowering, and end-to-end integration through
sql-builder-newand ORM.Change map
node:sqlitedriversqlite()factory + integration testsreadMarkerStatement()onAdapterProfileThe story
Driver and codec foundation — A
node:sqliteDatabaseSyncdriver wraps synchronous APIs in the asyncSqlDriverinterface, with foreign keys enabled by default. Eight codecs handle SQLite's type system (TEXT, INTEGER, REAL, BLOB, plus semantic codecs for boolean→0/1, datetime→ISO8601, JSON→TEXT, bigint→INTEGER).AST→SQL lowering — The SQLite adapter lowers the shared
AnyQueryAstto valid SQLite SQL:?positional params instead of$1,CAST()instead of::type,json_object()/json_group_array()instead of Postgres JSON functions, andON CONFLICTupsert support. Golden tests lock every AST node type.Target-aware marker reader — The runtime's contract verification previously hardcoded Postgres SQL (
prisma_contract.markerwith$1). Marker reading is moved toAdapterProfileso each target provides its own SQL. This is the only cross-cutting change to shared framework code.Extension + integration tests — The
sqlite()factory composes driver, adapter, and target into a lazy client withsql,schema,ormsurfaces. Integration tests exercise the full stack against real:memory:databases, withexpectTypeOfassertions proving that codec output types flow correctly through the contract type system.Codec type preservation — Column type descriptors and codec definitions are fixed to preserve literal
codecIdtypes through the TypeScript type system, enablingDb<Contract>to resolve row types to concrete JS types (e.g.boolean,Date,JsonValue) rather thanunknown.Behavior changes & evidence
Adds SQLite driver wrapping
node:sqliteDatabaseSyncProvides
connect(),execute()(async iterable),query(),close(), transaction support, andPRAGMA foreign_keys = ONon connect.Adds SQLite adapter that lowers
AnyQueryAstto SQLite SQLSELECT, INSERT (with ON CONFLICT), UPDATE, DELETE, RETURNING, JOINs, subqueries, JSON aggregation, parameterized queries with
?placeholders,CAST()syntax.Moves marker reader from hardcoded Postgres SQL to
AdapterProfileBefore:
SqlFamilyAdapterhardcodedreadContractMarker()which producedSELECT ... FROM prisma_contract.marker WHERE id = $1. This failed on SQLite (no schema support, wrong placeholder syntax).After:
AdapterProfile.readMarkerStatement()lets each adapter provide target-specific marker SQL.SqlFamilyAdapterdelegates to the adapter profile. Postgres usesprisma_contract.markerwith$1; SQLite usesprisma_contract_markerwith?.MarkerStatementinterface +readMarkerStatement()onAdapterProfileadapter.profileAdds
sqlite()factory with lazy client compositionMirrors
postgres(): accepts contract/contractJson + path, creates execution stack, returnsSqliteClientwithsql,schema,orm,context,connect(),runtime().Fixes codec type preservation so
Db<Contract>resolves row typesTwo root causes made all sql-builder row fields resolve to
unknown:integerColumn) had explicit: ColumnTypeDescriptorannotation, wideningcodecIdfrom literal'sqlite/integer@1'tostring.codec<Id, number, number>wherenumbermapped toTTraitsnotTWire), breaking type inference.Both are fixed by removing explicit annotations and letting TypeScript infer literals from
as constand typed encode/decode signatures.: ColumnTypeDescriptorannotationsexpectTypeOfassertions verify{ id: number; name: string },{ active: boolean },{ created_at: Date },{ metadata: JsonValue | null }expectTypeOfassertions on ORM row typesCapability gating verified at type level and runtime
lateralJoinanddistinctOnare unavailable for SQLite contracts — verified by@ts-expect-error(type gate) andexpect(...).toThrow()(runtime gate with specific error message).Compatibility / migration / risk
AdapterProfilebreaking change: AllAdapterProfileimplementations must now providereadMarkerStatement(). Updated for Postgres adapter and all test stubs.: ColumnTypeDescriptorfrom column type exports narrows the inferred type. This is a type-level improvement (more precise), not a runtime change.Follow-ups / open questions
projectionTypeson its query plans, so codec decoding (e.g. INTEGER 0/1 → boolean) does not apply to ORM read results. Pre-existing cross-target limitation.selectIncludeStrategybug: Readscapabilities['lateral']at top level but capabilities are nested undersql.*. Lateral/correlated strategies unreachable for any target. Pre-existing.ilikenot feature-gated: The ORM exposesilike()on text fields for SQLite, but the adapter silently maps it toLIKE. Should be properly gated in a follow-up.Non-goals / intentionally out of scope
sql-lane(legacy) andkysely-laneSQLite supportSummary by CodeRabbit
Release Notes
New Features
sql.defaultInInsertcapability for DEFAULT values in multi-row INSERT statementsDocumentation
Chores