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

feat(sqlite): add SQLite target (milestones 1–3) - #274

Merged
SevInf merged 27 commits into
mainfrom
worktree/sqlite
Apr 9, 2026
Merged

SevInf merged 27 commits into
mainfrom
worktree/sqlite

Conversation

@SevInf

@SevInf SevInf commented Mar 31, 2026 •

Copy link
Copy Markdown
Contributor

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-new and ORM.

Change map

The story

  1. Driver and codec foundation — A node:sqlite DatabaseSync driver wraps synchronous APIs in the async SqlDriver interface, 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).

  2. AST→SQL lowering — The SQLite adapter lowers the shared AnyQueryAst to valid SQLite SQL: ? positional params instead of $1, CAST() instead of ::type, json_object()/json_group_array() instead of Postgres JSON functions, and ON CONFLICT upsert support. Golden tests lock every AST node type.

  3. Target-aware marker reader — The runtime's contract verification previously hardcoded Postgres SQL (prisma_contract.marker with $1). Marker reading is moved to AdapterProfile so each target provides its own SQL. This is the only cross-cutting change to shared framework code.

  4. Extension + integration tests — The sqlite() factory composes driver, adapter, and target into a lazy client with sql, schema, orm surfaces. Integration tests exercise the full stack against real :memory: databases, with expectTypeOf assertions proving that codec output types flow correctly through the contract type system.

  5. Codec type preservation — Column type descriptors and codec definitions are fixed to preserve literal codecId types through the TypeScript type system, enabling Db<Contract> to resolve row types to concrete JS types (e.g. boolean, Date, JsonValue) rather than unknown.

Behavior changes & evidence

Adds SQLite driver wrapping node:sqlite DatabaseSync

Provides connect(), execute() (async iterable), query(), close(), transaction support, and PRAGMA foreign_keys = ON on connect.

Adds SQLite adapter that lowers AnyQueryAst to SQLite SQL

SELECT, 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 AdapterProfile

Before: SqlFamilyAdapter hardcoded readContractMarker() which produced SELECT ... 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. SqlFamilyAdapter delegates to the adapter profile. Postgres uses prisma_contract.marker with $1; SQLite uses prisma_contract_marker with ?.

Adds sqlite() factory with lazy client composition

Mirrors postgres(): accepts contract/contractJson + path, creates execution stack, returns SqliteClient with sql, schema, orm, context, connect(), runtime().

Fixes codec type preservation so Db<Contract> resolves row types

Two root causes made all sql-builder row fields resolve to unknown:

  1. Column type descriptors (e.g. integerColumn) had explicit : ColumnTypeDescriptor annotation, widening codecId from literal 'sqlite/integer@1' to string.
  2. Codec definitions used incorrect explicit generic params (codec<Id, number, number> where number mapped to TTraits not TWire), breaking type inference.

Both are fixed by removing explicit annotations and letting TypeScript infer literals from as const and typed encode/decode signatures.

Capability gating verified at type level and runtime

lateralJoin and distinctOn are unavailable for SQLite contracts — verified by @ts-expect-error (type gate) and expect(...).toThrow() (runtime gate with specific error message).

Compatibility / migration / risk

  • AdapterProfile breaking change: All AdapterProfile implementations must now provide readMarkerStatement(). Updated for Postgres adapter and all test stubs.
  • Codec type narrowing: Removing : ColumnTypeDescriptor from column type exports narrows the inferred type. This is a type-level improvement (more precise), not a runtime change.

Follow-ups / open questions

  • ORM codec decoding: The ORM does not populate projectionTypes on its query plans, so codec decoding (e.g. INTEGER 0/1 → boolean) does not apply to ORM read results. Pre-existing cross-target limitation.
  • ORM selectIncludeStrategy bug: Reads capabilities['lateral'] at top level but capabilities are nested under sql.*. Lateral/correlated strategies unreachable for any target. Pre-existing.
  • ilike not feature-gated: The ORM exposes ilike() on text fields for SQLite, but the adapter silently maps it to LIKE. Should be properly gated in a follow-up.
  • Milestone 4 (contract authoring, migrations, introspection) and Milestone 5 (E2E) not yet started.

Non-goals / intentionally out of scope

  • sql-lane (legacy) and kysely-lane SQLite support
  • SQLite migration planner/runner (Milestone 4)
  • FTS5, WAL mode, ATTACH DATABASE support

Summary by CodeRabbit

Release Notes

  • New Features

    • Added SQLite runtime support with complete adapter and driver implementation
    • Added sql.defaultInInsert capability for DEFAULT values in multi-row INSERT statements
    • Implemented automatic INSERT splitting by column signature when DEFAULT is unavailable
  • Documentation

    • Added comprehensive guides for SQLite packages (runtime, adapter, driver, target)
  • Chores

    • Added SQLite package infrastructure and configuration files
    • Updated contract capability definitions and architecture metadata

@coderabbitai

coderabbitai Bot commented Mar 31, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This 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 sql.defaultInInsert capability and implements fallback split-insert logic that groups rows by column signature when the capability is absent.

Changes

Cohort / File(s) Summary
SQLite Adapter Implementation
packages/3-targets/6-adapters/sqlite/src/core/adapter.ts, codecs.ts, codec-ids.ts, column-types.ts, types.ts, sql-utils.ts, descriptor-meta.ts, control-adapter.ts, runtime-adapter.ts
Complete SQLite SQL dialect implementation with AST lowering for SELECT/INSERT/UPDATE/DELETE, eight codec definitions (text, integer, real, blob, boolean, datetime, json, bigint), column descriptors, error normalization, and adapter profile/descriptor metadata.
SQLite Driver Implementation
packages/3-targets/7-drivers/sqlite/src/sqlite-driver.ts, normalize-error.ts, core/control-driver.ts, core/runtime-driver.ts, core/descriptor-meta.ts
Runtime and control drivers implementing connection management (using node:sqlite), transaction support, query execution, error normalization with SQLite extended error codes mapped to SQLSTATE, and descriptor factories.
SQLite Target Package
packages/3-targets/3-targets/sqlite/src/core/runtime-target.ts, control-target.ts, descriptor-meta.ts, exports/pack.ts, exports/runtime.ts, exports/control.ts, package.json, README.md, tsconfig*.json, tsdown.config.ts, vitest.config.ts
Target descriptor, pack reference for contract authoring, metadata, exports, configuration, and documentation.
SQLite Extension Runtime
packages/3-extensions/sqlite/src/runtime/sqlite.ts, runtime/binding.ts, exports/runtime.ts, package.json, README.md, tsconfig*.json, tsdown.config.ts, vitest.config.ts
SQLite factory composition, binding input resolution, lazy driver initialization, optional pre-configured path binding, and memoized runtime instances.
ORM Split-Insert Support
packages/3-extensions/sql-orm-client/src/collection.ts, collection-mutation-dispatch.ts, query-plan-mutations.ts, query-plan.ts
Split-insert logic that groups rows by column signature when defaultInInsert capability is absent; includes dispatchSplitMutationRows, compileInsertReturningSplit, compileInsertCountSplit, and helper functions for signature grouping.
Adapter Capability Extension
packages/3-targets/6-adapters/postgres/src/core/adapter.ts, descriptor-meta.ts
Postgres adapter extended with readMarkerStatement() method and defaultInInsert: true capability flag.
Core Relational Types
packages/2-sql/4-lanes/relational-core/src/ast/adapter-types.ts, test/utils.ts
Added MarkerStatement interface and readMarkerStatement() method to AdapterProfile for contract marker SQL generation.
Runtime Adapter Integration
packages/2-sql/5-runtime/src/sql-family-adapter.ts, sql-runtime.ts, test/sql-family-adapter.test.ts, test/utils.ts, test/sql-runtime.test.ts, test/execution-stack.test.ts
Updated SqlFamilyAdapter to accept adapterProfile parameter; injected into runtime initialization; test stubs updated with readMarkerStatement() implementations.
Contract & Test Fixtures
examples/prisma-next-demo/src/prisma/contract.d.ts, contract.json, test/integration/test/fixtures/contract.d.ts, contract.json, test/integration/test/authoring/parity/*/expected.contract.json (15 files), test/integration/test/fixtures/contract.d.ts
Updated contracts with defaultInInsert: true capability; reorganized JSON field structure (moved nullable property placement); updated type definitions.
Configuration & Metadata
architecture.config.json, .gitignore, package.json, packages/2-sql/2-authoring/contract-ts/src/contract-types.ts
Added architecture package mappings for SQLite components; updated build scripts for fixture generation; refined relation type constraints.
Documentation & Tests
docs/reference/capabilities.md, packages/3-targets/6-adapters/sqlite/test/adapter.test.ts, test/codecs.test.ts, packages/3-targets/7-drivers/sqlite/test/control-driver.test.ts, runtime-driver.test.ts, sqlite-driver.test.ts, packages/3-extensions/sqlite/, packages/3-extensions/sql-orm-client/test/collection-mutation-dispatch.test.ts, collection.state.test.ts, query-plan-mutations.test.ts, collection-fixtures.ts
Added capability documentation; comprehensive test suites for adapter (AST lowering, codecs, literal handling), driver (connection, transaction, error handling), ORM split-insert behavior; test utilities and fixtures.

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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested reviewers

  • saevarb
  • wmadden

🐰 Hops excitedly with a bundle of SQLite schemas 🐇✨

SQLite support has sprouted up at last!
Adapters, drivers, splitting rows so fast—
Defaults in INSERT now have their own way,
This Prisma rabbit's hop-hop-hops with glee today! 🌱

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch worktree/sqlite

@SevInf
SevInf force-pushed the worktree/sqlite branch from 9839db8 to cee7574 Compare April 7, 2026 10:49
@pkg-pr-new

pkg-pr-new Bot commented Apr 7, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@prisma-next/mongo-runtime

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

@prisma-next/family-mongo

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

@prisma-next/sql-runtime

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

@prisma-next/family-sql

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

@prisma-next/extension-paradedb

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

@prisma-next/extension-pgvector

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

@prisma-next/postgres

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

@prisma-next/sql-orm-client

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

@prisma-next/sqlite

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

@prisma-next/target-mongo

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

@prisma-next/adapter-mongo

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

@prisma-next/driver-mongo

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

@prisma-next/contract

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

@prisma-next/utils

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

@prisma-next/config

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

@prisma-next/errors

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

@prisma-next/framework-components

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

@prisma-next/operations

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

@prisma-next/contract-authoring

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

@prisma-next/ids

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

@prisma-next/psl-parser

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

@prisma-next/psl-printer

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

@prisma-next/cli

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

@prisma-next/emitter

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

@prisma-next/migration-tools

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

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

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

@prisma-next/runtime-executor

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/runtime-executor@274

@prisma-next/mongo-codec

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

@prisma-next/mongo-contract

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

@prisma-next/mongo-value

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

@prisma-next/mongo-contract-psl

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

@prisma-next/mongo-emitter

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

@prisma-next/mongo-query-ast

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

@prisma-next/mongo-orm

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

@prisma-next/mongo-pipeline-builder

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-pipeline-builder@274

@prisma-next/mongo-lowering

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

@prisma-next/mongo-wire

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

@prisma-next/sql-contract

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

@prisma-next/sql-errors

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

@prisma-next/sql-operations

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

@prisma-next/sql-schema-ir

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

@prisma-next/sql-contract-psl

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

@prisma-next/sql-contract-ts

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

@prisma-next/sql-contract-emitter

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

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

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

@prisma-next/sql-relational-core

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

@prisma-next/sql-builder

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

@prisma-next/target-postgres

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

@prisma-next/target-sqlite

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

@prisma-next/adapter-postgres

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

@prisma-next/adapter-sqlite

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

@prisma-next/driver-postgres

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

@prisma-next/driver-sqlite

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

commit: 1bb34f5

@SevInf
SevInf force-pushed the worktree/sqlite branch from 60f9804 to 3c75e87 Compare April 8, 2026 13:26

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 13

🧹 Nitpick comments (11)
packages/3-targets/6-adapters/sqlite/README.md (2)

48-84: Add direction TB inside 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 TB inside Mermaid subgraph blocks 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 adding test/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 adding test/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, while quoteIdentifier() 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 of src/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 Date on line 157 is redundant since expectTypeOf(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.storageHash and profileHash are 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: Prefer expect().toThrow() pattern for error assertions.

The coding guidelines recommend using expect(() => ...).toThrow() instead of manual try/catch blocks. For checking additional error properties like sqlState, 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

📥 Commits

Reviewing files that changed from the base of the PR and between b37cddd and aa71a29.

⛔ Files ignored due to path filters (7)
  • packages/2-sql/4-lanes/sql-builder/test/fixtures/generated/contract.d.ts is excluded by !**/generated/**
  • packages/2-sql/4-lanes/sql-builder/test/fixtures/generated/contract.json is excluded by !**/generated/**
  • packages/3-extensions/sql-orm-client/test/fixtures/generated/contract.d.ts is excluded by !**/generated/**
  • packages/3-extensions/sql-orm-client/test/fixtures/generated/contract.json is excluded by !**/generated/**
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
  • test/e2e/framework/test/fixtures/generated/contract.d.ts is excluded by !**/generated/**
  • test/e2e/framework/test/fixtures/generated/contract.json is excluded by !**/generated/**
📒 Files selected for processing (94)
  • architecture.config.json
  • docs/reference/capabilities.md
  • examples/prisma-next-demo/src/prisma/contract.d.ts
  • examples/prisma-next-demo/src/prisma/contract.json
  • packages/2-sql/2-authoring/contract-ts/src/staged-contract-types.ts
  • packages/2-sql/4-lanes/relational-core/src/ast/adapter-types.ts
  • packages/2-sql/4-lanes/relational-core/src/types.ts
  • packages/2-sql/4-lanes/relational-core/test/utils.ts
  • packages/2-sql/5-runtime/src/sql-family-adapter.ts
  • packages/2-sql/5-runtime/src/sql-runtime.ts
  • packages/2-sql/5-runtime/test/execution-stack.test.ts
  • packages/2-sql/5-runtime/test/sql-family-adapter.test.ts
  • packages/2-sql/5-runtime/test/sql-runtime.test.ts
  • packages/2-sql/5-runtime/test/utils.ts
  • packages/3-extensions/sql-orm-client/src/collection-mutation-dispatch.ts
  • packages/3-extensions/sql-orm-client/src/collection.ts
  • packages/3-extensions/sql-orm-client/src/query-plan-mutations.ts
  • packages/3-extensions/sql-orm-client/src/query-plan.ts
  • packages/3-extensions/sql-orm-client/test/collection-fixtures.ts
  • packages/3-extensions/sql-orm-client/test/collection-mutation-dispatch.test.ts
  • packages/3-extensions/sql-orm-client/test/collection.state.test.ts
  • packages/3-extensions/sql-orm-client/test/query-plan-mutations.test.ts
  • packages/3-extensions/sqlite/README.md
  • packages/3-extensions/sqlite/package.json
  • packages/3-extensions/sqlite/src/exports/runtime.ts
  • packages/3-extensions/sqlite/src/runtime/binding.ts
  • packages/3-extensions/sqlite/src/runtime/sqlite.ts
  • packages/3-extensions/sqlite/test/integration/contract-type.ts
  • packages/3-extensions/sqlite/test/integration/contract.ts
  • packages/3-extensions/sqlite/test/integration/orm.test.ts
  • packages/3-extensions/sqlite/test/integration/setup.ts
  • packages/3-extensions/sqlite/test/integration/sql-builder.test.ts
  • packages/3-extensions/sqlite/tsconfig.json
  • packages/3-extensions/sqlite/tsconfig.prod.json
  • packages/3-extensions/sqlite/tsdown.config.ts
  • packages/3-extensions/sqlite/vitest.config.ts
  • packages/3-targets/3-targets/sqlite/README.md
  • packages/3-targets/3-targets/sqlite/package.json
  • packages/3-targets/3-targets/sqlite/src/core/descriptor-meta.ts
  • packages/3-targets/3-targets/sqlite/src/exports/pack.ts
  • packages/3-targets/3-targets/sqlite/src/exports/runtime.ts
  • packages/3-targets/3-targets/sqlite/tsconfig.json
  • packages/3-targets/3-targets/sqlite/tsconfig.prod.json
  • packages/3-targets/3-targets/sqlite/tsdown.config.ts
  • packages/3-targets/3-targets/sqlite/vitest.config.ts
  • packages/3-targets/6-adapters/postgres/src/core/adapter.ts
  • packages/3-targets/6-adapters/postgres/src/core/descriptor-meta.ts
  • packages/3-targets/6-adapters/sqlite/README.md
  • packages/3-targets/6-adapters/sqlite/package.json
  • packages/3-targets/6-adapters/sqlite/src/core/adapter.ts
  • packages/3-targets/6-adapters/sqlite/src/core/codec-ids.ts
  • packages/3-targets/6-adapters/sqlite/src/core/codecs.ts
  • packages/3-targets/6-adapters/sqlite/src/core/descriptor-meta.ts
  • packages/3-targets/6-adapters/sqlite/src/core/sql-utils.ts
  • packages/3-targets/6-adapters/sqlite/src/core/types.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/6-adapters/sqlite/src/exports/control.ts
  • packages/3-targets/6-adapters/sqlite/src/exports/runtime.ts
  • packages/3-targets/6-adapters/sqlite/src/exports/types.ts
  • packages/3-targets/6-adapters/sqlite/test/adapter.test.ts
  • packages/3-targets/6-adapters/sqlite/test/codecs.test.ts
  • packages/3-targets/6-adapters/sqlite/tsconfig.json
  • packages/3-targets/6-adapters/sqlite/tsconfig.prod.json
  • packages/3-targets/6-adapters/sqlite/tsdown.config.ts
  • packages/3-targets/6-adapters/sqlite/vitest.config.ts
  • packages/3-targets/7-drivers/sqlite/README.md
  • packages/3-targets/7-drivers/sqlite/package.json
  • packages/3-targets/7-drivers/sqlite/src/core/descriptor-meta.ts
  • packages/3-targets/7-drivers/sqlite/src/exports/control.ts
  • packages/3-targets/7-drivers/sqlite/src/exports/runtime.ts
  • packages/3-targets/7-drivers/sqlite/src/normalize-error.ts
  • packages/3-targets/7-drivers/sqlite/src/sqlite-driver.ts
  • packages/3-targets/7-drivers/sqlite/test/control-driver.test.ts
  • packages/3-targets/7-drivers/sqlite/test/runtime-driver.test.ts
  • packages/3-targets/7-drivers/sqlite/test/sqlite-driver.test.ts
  • packages/3-targets/7-drivers/sqlite/tsconfig.json
  • packages/3-targets/7-drivers/sqlite/tsconfig.prod.json
  • packages/3-targets/7-drivers/sqlite/tsdown.config.ts
  • packages/3-targets/7-drivers/sqlite/vitest.config.ts
  • test/integration/test/authoring/parity/core-surface/expected.contract.json
  • test/integration/test/authoring/parity/default-cuid-2/expected.contract.json
  • 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-nanoid/expected.contract.json
  • test/integration/test/authoring/parity/default-pack-slugid/expected.contract.json
  • test/integration/test/authoring/parity/default-ulid/expected.contract.json
  • test/integration/test/authoring/parity/default-uuid-v4/expected.contract.json
  • test/integration/test/authoring/parity/default-uuid-v7/expected.contract.json
  • test/integration/test/authoring/parity/map-attributes/expected.contract.json
  • test/integration/test/authoring/parity/pgvector-named-type/expected.contract.json
  • test/integration/test/authoring/parity/relation-backrelation-list/expected.contract.json
  • test/integration/test/fixtures/contract.d.ts
  • test/integration/test/fixtures/contract.json

Comment thread architecture.config.json Resolved
Comment on lines +170 to +190
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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

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.

Suggested change
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.

@SevInf
SevInf force-pushed the worktree/sqlite branch 2 times, most recently from 1c0b962 to 1baf7fe Compare April 8, 2026 16:16
@SevInf
SevInf marked this pull request as ready for review April 8, 2026 16:19

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

♻️ 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 (connectPromise is truthy but driverConnected is 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: Prefer pathe over node:path for cross-platform consistency.

Based on learnings, this repo prefers pathe over node:path for 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: Use pathe for path helpers in this test.

This repo standardizes on pathe in TypeScript files, so pulling dirname/resolve from node:path drifts 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}: Use pathe instead of node:path for 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: Use pathe for path helpers in this test.

This repo standardizes on pathe in TypeScript files, so pulling dirname/resolve from node:path drifts 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}: Use pathe instead of node:path for 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

📥 Commits

Reviewing files that changed from the base of the PR and between aa71a29 and 1baf7fe.

⛔ Files ignored due to path filters (9)
  • packages/2-sql/4-lanes/sql-builder/test/fixtures/generated/contract.d.ts is excluded by !**/generated/**
  • packages/2-sql/4-lanes/sql-builder/test/fixtures/generated/contract.json is excluded by !**/generated/**
  • packages/3-extensions/sql-orm-client/test/fixtures/generated/contract.d.ts is excluded by !**/generated/**
  • packages/3-extensions/sql-orm-client/test/fixtures/generated/contract.json is excluded by !**/generated/**
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
  • test/e2e/framework/test/fixtures/generated/contract.d.ts is excluded by !**/generated/**
  • test/e2e/framework/test/fixtures/generated/contract.json is excluded by !**/generated/**
  • test/e2e/sqlite/test/fixtures/generated/contract.d.ts is excluded by !**/generated/**
  • test/e2e/sqlite/test/fixtures/generated/contract.json is excluded by !**/generated/**
📒 Files selected for processing (101)
  • .gitignore
  • architecture.config.json
  • docs/reference/capabilities.md
  • examples/prisma-next-demo/src/prisma/contract.d.ts
  • examples/prisma-next-demo/src/prisma/contract.json
  • package.json
  • packages/2-sql/2-authoring/contract-ts/src/contract-types.ts
  • 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/src/sql-family-adapter.ts
  • packages/2-sql/5-runtime/src/sql-runtime.ts
  • packages/2-sql/5-runtime/test/execution-stack.test.ts
  • packages/2-sql/5-runtime/test/sql-family-adapter.test.ts
  • packages/2-sql/5-runtime/test/sql-runtime.test.ts
  • packages/2-sql/5-runtime/test/utils.ts
  • packages/3-extensions/sql-orm-client/src/collection-mutation-dispatch.ts
  • packages/3-extensions/sql-orm-client/src/collection.ts
  • packages/3-extensions/sql-orm-client/src/query-plan-mutations.ts
  • packages/3-extensions/sql-orm-client/src/query-plan.ts
  • packages/3-extensions/sql-orm-client/test/collection-fixtures.ts
  • packages/3-extensions/sql-orm-client/test/collection-mutation-dispatch.test.ts
  • packages/3-extensions/sql-orm-client/test/collection.state.test.ts
  • packages/3-extensions/sql-orm-client/test/query-plan-mutations.test.ts
  • packages/3-extensions/sqlite/README.md
  • packages/3-extensions/sqlite/package.json
  • packages/3-extensions/sqlite/src/exports/runtime.ts
  • packages/3-extensions/sqlite/src/runtime/binding.ts
  • packages/3-extensions/sqlite/src/runtime/sqlite.ts
  • packages/3-extensions/sqlite/tsconfig.json
  • packages/3-extensions/sqlite/tsconfig.prod.json
  • packages/3-extensions/sqlite/tsdown.config.ts
  • packages/3-extensions/sqlite/vitest.config.ts
  • packages/3-targets/3-targets/sqlite/README.md
  • packages/3-targets/3-targets/sqlite/package.json
  • packages/3-targets/3-targets/sqlite/src/core/descriptor-meta.ts
  • packages/3-targets/3-targets/sqlite/src/exports/control.ts
  • packages/3-targets/3-targets/sqlite/src/exports/pack.ts
  • packages/3-targets/3-targets/sqlite/src/exports/runtime.ts
  • packages/3-targets/3-targets/sqlite/tsconfig.json
  • packages/3-targets/3-targets/sqlite/tsconfig.prod.json
  • packages/3-targets/3-targets/sqlite/tsdown.config.ts
  • packages/3-targets/3-targets/sqlite/vitest.config.ts
  • packages/3-targets/6-adapters/postgres/src/core/adapter.ts
  • packages/3-targets/6-adapters/postgres/src/core/descriptor-meta.ts
  • packages/3-targets/6-adapters/sqlite/README.md
  • packages/3-targets/6-adapters/sqlite/package.json
  • packages/3-targets/6-adapters/sqlite/src/core/adapter.ts
  • packages/3-targets/6-adapters/sqlite/src/core/codec-ids.ts
  • packages/3-targets/6-adapters/sqlite/src/core/codecs.ts
  • packages/3-targets/6-adapters/sqlite/src/core/descriptor-meta.ts
  • packages/3-targets/6-adapters/sqlite/src/core/sql-utils.ts
  • packages/3-targets/6-adapters/sqlite/src/core/types.ts
  • packages/3-targets/6-adapters/sqlite/src/exports/adapter.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/6-adapters/sqlite/src/exports/control.ts
  • packages/3-targets/6-adapters/sqlite/src/exports/runtime.ts
  • packages/3-targets/6-adapters/sqlite/src/exports/types.ts
  • packages/3-targets/6-adapters/sqlite/test/adapter.test.ts
  • packages/3-targets/6-adapters/sqlite/test/codecs.test.ts
  • packages/3-targets/6-adapters/sqlite/tsconfig.json
  • packages/3-targets/6-adapters/sqlite/tsconfig.prod.json
  • packages/3-targets/6-adapters/sqlite/tsdown.config.ts
  • packages/3-targets/6-adapters/sqlite/vitest.config.ts
  • packages/3-targets/7-drivers/sqlite/README.md
  • packages/3-targets/7-drivers/sqlite/package.json
  • packages/3-targets/7-drivers/sqlite/src/core/descriptor-meta.ts
  • packages/3-targets/7-drivers/sqlite/src/exports/control.ts
  • packages/3-targets/7-drivers/sqlite/src/exports/runtime.ts
  • packages/3-targets/7-drivers/sqlite/src/normalize-error.ts
  • packages/3-targets/7-drivers/sqlite/src/sqlite-driver.ts
  • packages/3-targets/7-drivers/sqlite/test/control-driver.test.ts
  • packages/3-targets/7-drivers/sqlite/test/runtime-driver.test.ts
  • packages/3-targets/7-drivers/sqlite/test/sqlite-driver.test.ts
  • packages/3-targets/7-drivers/sqlite/tsconfig.json
  • packages/3-targets/7-drivers/sqlite/tsconfig.prod.json
  • packages/3-targets/7-drivers/sqlite/tsdown.config.ts
  • packages/3-targets/7-drivers/sqlite/vitest.config.ts
  • test/e2e/sqlite/biome.jsonc
  • test/e2e/sqlite/package.json
  • test/e2e/sqlite/test/fixtures/contract.ts
  • test/e2e/sqlite/test/fixtures/prisma-next.config.ts
  • test/e2e/sqlite/test/orm.test.ts
  • test/e2e/sqlite/test/sql-builder.test.ts
  • test/e2e/sqlite/test/utils.ts
  • test/e2e/sqlite/tsconfig.json
  • test/e2e/sqlite/vitest.config.ts
  • test/integration/test/authoring/parity/core-surface/expected.contract.json
  • test/integration/test/authoring/parity/default-cuid-2/expected.contract.json
  • 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-nanoid/expected.contract.json
  • test/integration/test/authoring/parity/default-pack-slugid/expected.contract.json
  • test/integration/test/authoring/parity/default-ulid/expected.contract.json
  • test/integration/test/authoring/parity/default-uuid-v4/expected.contract.json
  • test/integration/test/authoring/parity/default-uuid-v7/expected.contract.json
  • test/integration/test/authoring/parity/map-attributes/expected.contract.json
  • test/integration/test/authoring/parity/pgvector-named-type/expected.contract.json
  • test/integration/test/authoring/parity/relation-backrelation-list/expected.contract.json
  • test/integration/test/fixtures/contract.d.ts
  • test/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 wmadden left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 codecId types flow correctly via as const
  • Split-insert logic — groupRowsByColumnSignature with 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 expectTypeOf assertions proving type flow

Six inline findings (F01–F06) are posted below.

Comment on lines +178 to +185
async connect(binding: SqliteBinding): Promise<void> {
if (this.#state.kind !== 'connected') {
this.#state = {
kind: 'connected',
path: binding.path,
conn: new SqliteConnectionImpl(openConnection(binding.path)),
};
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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;
  // ...
}

Comment on lines +102 to +123
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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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:

  1. sqlite({ path: '/bad' }) — creates client
  2. runtime() — creates runtime, triggers background connect which fails
  3. runtime() — throws stored backgroundConnectError
  4. connect({ path: '/good' }) — throws because runtimeInstance exists

Suggestion: allow connect() after a failed background connect by checking whether the driver is actually connected, not just whether a runtime exists.

Comment thread test/e2e/sqlite/test/utils.ts Resolved
Comment thread architecture.config.json Resolved
SevInf added a commit that referenced this pull request Apr 9, 2026
- 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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 5

🧹 Nitpick comments (1)
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 multiple toBe(...) 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 individual expect().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

📥 Commits

Reviewing files that changed from the base of the PR and between 1baf7fe and 52b07fe.

📒 Files selected for processing (20)
  • architecture.config.json
  • package.json
  • packages/3-targets/3-targets/sqlite/src/core/control-target.ts
  • packages/3-targets/3-targets/sqlite/src/core/runtime-target.ts
  • packages/3-targets/3-targets/sqlite/src/exports/control.ts
  • packages/3-targets/3-targets/sqlite/src/exports/runtime.ts
  • packages/3-targets/6-adapters/sqlite/src/core/adapter.ts
  • packages/3-targets/6-adapters/sqlite/src/core/column-types.ts
  • packages/3-targets/6-adapters/sqlite/src/core/control-adapter.ts
  • packages/3-targets/6-adapters/sqlite/src/core/runtime-adapter.ts
  • packages/3-targets/6-adapters/sqlite/src/exports/column-types.ts
  • packages/3-targets/6-adapters/sqlite/src/exports/control.ts
  • packages/3-targets/6-adapters/sqlite/src/exports/runtime.ts
  • packages/3-targets/7-drivers/sqlite/src/core/control-driver.ts
  • packages/3-targets/7-drivers/sqlite/src/core/runtime-driver.ts
  • packages/3-targets/7-drivers/sqlite/src/exports/control.ts
  • packages/3-targets/7-drivers/sqlite/src/exports/runtime.ts
  • test/e2e/sqlite/test/orm.test.ts
  • test/e2e/sqlite/test/sql-builder.test.ts
  • test/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

Comment on lines +34 to +43
const defaultCapabilities = Object.freeze({
sql: {
orderBy: true,
limit: true,
lateral: false,
jsonAgg: true,
returning: true,
enums: false,
},
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

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.

Comment on lines +17 to +24
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 };

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 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' packages

Repository: prisma/prisma-next

Length of output: 738


🏁 Script executed:

# Find SQLInputValue type definition
rg -n 'type\s+SQLInputValue|interface\s+SQLInputValue' packages --type ts

Repository: 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 -100

Repository: 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 -60

Repository: 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 -n

Repository: 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.

SevInf added 18 commits April 9, 2026 12:26
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/
SevInf added 8 commits April 9, 2026 12:26
…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).
@SevInf
SevInf force-pushed the worktree/sqlite branch from 80d3eba to 3156f56 Compare April 9, 2026 10:35
@SevInf
SevInf enabled auto-merge (squash) April 9, 2026 10:38

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (1)
packages/3-targets/7-drivers/sqlite/src/sqlite-driver.ts (1)

68-187: Consider extracting shared query logic.

SqliteConnectionImpl and SqliteTransactionImpl have identical implementations for execute(), explain(), and query(). 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

📥 Commits

Reviewing files that changed from the base of the PR and between 52b07fe and 3156f56.

⛔ Files ignored due to path filters (5)
  • packages/2-sql/4-lanes/sql-builder/test/fixtures/generated/contract.d.ts is excluded by !**/generated/**
  • packages/2-sql/4-lanes/sql-builder/test/fixtures/generated/contract.json is excluded by !**/generated/**
  • packages/3-extensions/sql-orm-client/test/fixtures/generated/contract.d.ts is excluded by !**/generated/**
  • packages/3-extensions/sql-orm-client/test/fixtures/generated/contract.json is excluded by !**/generated/**
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (85)
  • .gitignore
  • architecture.config.json
  • docs/reference/capabilities.md
  • examples/prisma-next-demo/src/prisma/contract.d.ts
  • examples/prisma-next-demo/src/prisma/contract.json
  • package.json
  • packages/2-sql/2-authoring/contract-ts/src/contract-types.ts
  • 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/src/sql-family-adapter.ts
  • packages/2-sql/5-runtime/src/sql-runtime.ts
  • packages/2-sql/5-runtime/test/execution-stack.test.ts
  • packages/2-sql/5-runtime/test/sql-family-adapter.test.ts
  • packages/2-sql/5-runtime/test/sql-runtime.test.ts
  • packages/2-sql/5-runtime/test/utils.ts
  • packages/3-extensions/sql-orm-client/src/collection-mutation-dispatch.ts
  • packages/3-extensions/sql-orm-client/src/collection.ts
  • packages/3-extensions/sql-orm-client/src/query-plan-mutations.ts
  • packages/3-extensions/sql-orm-client/src/query-plan.ts
  • packages/3-extensions/sql-orm-client/test/collection-fixtures.ts
  • packages/3-extensions/sql-orm-client/test/collection-mutation-dispatch.test.ts
  • packages/3-extensions/sql-orm-client/test/collection.state.test.ts
  • packages/3-extensions/sql-orm-client/test/query-plan-mutations.test.ts
  • packages/3-extensions/sqlite/README.md
  • packages/3-extensions/sqlite/package.json
  • packages/3-extensions/sqlite/src/exports/runtime.ts
  • packages/3-extensions/sqlite/src/runtime/binding.ts
  • packages/3-extensions/sqlite/src/runtime/sqlite.ts
  • packages/3-extensions/sqlite/tsconfig.json
  • packages/3-extensions/sqlite/tsconfig.prod.json
  • packages/3-extensions/sqlite/tsdown.config.ts
  • packages/3-extensions/sqlite/vitest.config.ts
  • packages/3-targets/3-targets/sqlite/README.md
  • packages/3-targets/3-targets/sqlite/package.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/3-targets/sqlite/src/core/runtime-target.ts
  • packages/3-targets/3-targets/sqlite/src/exports/control.ts
  • packages/3-targets/3-targets/sqlite/src/exports/pack.ts
  • packages/3-targets/3-targets/sqlite/src/exports/runtime.ts
  • packages/3-targets/3-targets/sqlite/tsconfig.json
  • packages/3-targets/3-targets/sqlite/tsconfig.prod.json
  • packages/3-targets/3-targets/sqlite/tsdown.config.ts
  • packages/3-targets/3-targets/sqlite/vitest.config.ts
  • packages/3-targets/6-adapters/postgres/src/core/adapter.ts
  • packages/3-targets/6-adapters/postgres/src/core/descriptor-meta.ts
  • packages/3-targets/6-adapters/sqlite/README.md
  • packages/3-targets/6-adapters/sqlite/package.json
  • packages/3-targets/6-adapters/sqlite/src/core/adapter.ts
  • packages/3-targets/6-adapters/sqlite/src/core/codec-ids.ts
  • packages/3-targets/6-adapters/sqlite/src/core/codecs.ts
  • packages/3-targets/6-adapters/sqlite/src/core/column-types.ts
  • packages/3-targets/6-adapters/sqlite/src/core/control-adapter.ts
  • packages/3-targets/6-adapters/sqlite/src/core/descriptor-meta.ts
  • packages/3-targets/6-adapters/sqlite/src/core/runtime-adapter.ts
  • packages/3-targets/6-adapters/sqlite/src/core/sql-utils.ts
  • packages/3-targets/6-adapters/sqlite/src/core/types.ts
  • packages/3-targets/6-adapters/sqlite/src/exports/adapter.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/6-adapters/sqlite/src/exports/control.ts
  • packages/3-targets/6-adapters/sqlite/src/exports/runtime.ts
  • packages/3-targets/6-adapters/sqlite/src/exports/types.ts
  • packages/3-targets/6-adapters/sqlite/test/adapter.test.ts
  • packages/3-targets/6-adapters/sqlite/test/codecs.test.ts
  • packages/3-targets/6-adapters/sqlite/tsconfig.json
  • packages/3-targets/6-adapters/sqlite/tsconfig.prod.json
  • packages/3-targets/6-adapters/sqlite/tsdown.config.ts
  • packages/3-targets/6-adapters/sqlite/vitest.config.ts
  • packages/3-targets/7-drivers/sqlite/README.md
  • packages/3-targets/7-drivers/sqlite/package.json
  • packages/3-targets/7-drivers/sqlite/src/core/control-driver.ts
  • packages/3-targets/7-drivers/sqlite/src/core/descriptor-meta.ts
  • packages/3-targets/7-drivers/sqlite/src/core/runtime-driver.ts
  • packages/3-targets/7-drivers/sqlite/src/exports/control.ts
  • packages/3-targets/7-drivers/sqlite/src/exports/runtime.ts
  • packages/3-targets/7-drivers/sqlite/src/normalize-error.ts
  • packages/3-targets/7-drivers/sqlite/src/sqlite-driver.ts
  • packages/3-targets/7-drivers/sqlite/test/control-driver.test.ts
  • packages/3-targets/7-drivers/sqlite/test/runtime-driver.test.ts
  • packages/3-targets/7-drivers/sqlite/test/sqlite-driver.test.ts
  • packages/3-targets/7-drivers/sqlite/tsconfig.json
  • packages/3-targets/7-drivers/sqlite/tsconfig.prod.json
  • packages/3-targets/7-drivers/sqlite/tsdown.config.ts
  • packages/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

Comment on lines +34 to +42
const defaultCapabilities = Object.freeze({
sql: {
orderBy: true,
limit: true,
lateral: false,
jsonAgg: true,
returning: true,
enums: false,
},

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

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

Comment on lines +322 to +326
// 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.');
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

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.

Comment on lines +53 to +55
function toSqliteParams(params: readonly unknown[] | undefined): SQLInputValue[] {
return (params ?? []) as SQLInputValue[];
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

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.

@SevInf
SevInf merged commit 8a275d5 into main Apr 9, 2026
22 of 23 checks passed
@SevInf
SevInf deleted the worktree/sqlite branch April 9, 2026 12:47
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants