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

TML-2668: rawSql in the typed builder (Postgres + SQLite) - #594

Merged
SevInf merged 42 commits into
mainfrom
tml-2668-core-rawexpr-substrate-factory-primitives
May 29, 2026
Merged

SevInf merged 42 commits into
mainfrom
tml-2668-core-rawexpr-substrate-factory-primitives

Conversation

@SevInf

@SevInf SevInf commented May 26, 2026 •

Copy link
Copy Markdown
Contributor

Linked issue

Refs TML-2668, TML-2671, TML-2669 — bundled per-slice work shipping in a single PR (the three slices were sequenced as one project per the prior project plan).

At a glance

A real usage from the live-Postgres integration test (test/integration/test/sql-builder/raw-sql.integration.test.ts):

const db = sql({ context, rawCodecInferer: postgresRawCodecInferer });

// posts.views values: 100, 50, 200, 10 — doubled they become 200, 100, 400, 20.
const rows = await runtime.execute(
  db.posts
    .select('id')
    .select('doubled', (f, fns) => fns.raw`${f.views} * 2`.returns('pg/int4@1'))
    .orderBy('id')
    .build(),
);

expect(rows.map((r) => r.doubled)).toEqual([200, 100, 400, 20]);

fns.raw\...`(inside any builder callback) anddb.raw`...`(on the facade-returned client) are tagged-template functions backed by the sameRawCodecInferer contributed by the target's adapter descriptor. They accept three interpolation shapes: typed-builder expressions (f.views, fns.eq(...), nested raw — anything Expression<…>), explicit param(value, { codecId })overrides, and bare values from a closedRawSqlLiteral = number | bigint | string | boolean | Uint8Arrayunion (each routed throughinferCodec` to a target codec id).

Values outside the union must go through param(value, { codecId }) — Date, null, undefined, plain objects, and arrays are deliberately type errors at the call site and a runtime throw if cast in.

Decision

This PR ships the per-expression escape hatch for SQL functions the operation registry doesn't expose (extract(epoch from ...), strftime, coalesce, json_object, ts_rank, vendor extensions, …) so a user can drop down to literal SQL for that one expression without leaving the typed builder. Three substantive pieces land together:

  1. Core: RawExpr AST node + factory primitives (packages/2-sql/4-lanes/relational-core/src/ast/types.ts, expression.ts). New RawExpr class added to AnyExpression with kind: 'raw-expr' (distinct from the existing query-level RawSqlExpr's 'raw-sql' so isQueryAst keeps its semantics). New rawExpr arm on ExprVisitor / ExpressionRewriter / ExpressionFolder. Closed RawSqlLiteral union, free param(value, { codecId }) export, and createRawSql(inferer) factory whose .returns(spec) preserves literal codec types.

  2. Public RawCodecInferer contract on the adapter descriptor (packages/2-sql/5-runtime/src/sql-context.ts, packages/2-sql/4-lanes/relational-core/src/expression.ts). One-method interface (inferCodec(value: RawSqlLiteral): string) declared in relational-core. SqlRuntimeAdapterDescriptor requires it as a static contribution — every SQL adapter declares one statically rather than expressing it on the runtime adapter instance. Postgres and SQLite each export a postgresRawCodecInferer / sqliteRawCodecInferer constant that the adapter descriptor contributes.

  3. fns.raw as a regular builtin + facade wiring (packages/2-sql/4-lanes/sql-builder/src/expression.ts, runtime/functions.ts, packages/3-extensions/postgres/src/runtime/postgres.ts, packages/3-extensions/sqlite/src/runtime/sqlite.ts). BuiltinFunctions<CT> declares readonly raw: RawSqlTag alongside eq / gt / etc. — no generic threading, no special-case Proxy branch. createBuiltinFunctions(inferer) builds the tag ad-hoc inside the same factory that mints the other builtins. BuilderContext.rawCodecInferer: RawCodecInferer flows through to every callback dispatch site (createFunctions / createAggregateFunctions). Each facade reads stack.adapter.rawCodecInferer at construction time — no second adapter instance, no instance-level inferCodec method.

How it fits together

  1. Substrate first. RawExpr joins the AnyExpression discriminated union (ast/types.ts) with shape { kind: 'raw-expr', parts: readonly (string | AnyExpression)[], returns: ParamSpec }. The parts array interleaves string fragments with expression interpolations — the ordering is the structure, so there's no fragments.length === args.length + 1 invariant to maintain. The rawExpr arm joins ExprVisitor (required), ExpressionRewriter (optional), and ExpressionFolder (optional). Both adapter lowerers gain a small renderRawExpr walker that emits string parts verbatim and lowers expression parts through the existing renderParamRef path — so ParamRefs inside raw expressions are parameterised exactly like typed-builder params (NFR1: no string concatenation).

  2. Core public surface. RawSqlLiteral (closed union: number | bigint | string | boolean | Uint8Array), param(value, { codecId }) (free import; sugar over ParamRef.of), and createRawSql(inferer) (factory; returns a tagged-template RawSqlTag whose .returns(spec) produces an Expression<{ codecId, nullable }>). .returns is generic — .returns('pg/int4@1') preserves the literal type so downstream operations get Expression<{ codecId: 'pg/int4@1', nullable: false }> not the widened form.

  3. RawCodecInferer as a public contract. One-method interface in relational-core (expression.ts). Required on SqlRuntimeAdapterDescriptor as a static contribution — the facade reads it off the adapter descriptor at client-construction time without instantiating the runtime adapter. Postgres and SQLite each export a standalone postgresRawCodecInferer / sqliteRawCodecInferer const that the descriptor contributes (adapter.ts, adapter.ts). The integer/float boundary for bare number uses Number.isSafeInteger(value) && value % 1 === 0; MAX_SAFE_INTEGER + 1 routes to the float codec rather than silently truncating. Off-union values throw unsupported JS value type for raw-SQL interpolation: wrap this value in \param(...)` with an explicit codec`.

  4. fns.raw is a regular builtin. BuiltinFunctions<CT> declares readonly raw: RawSqlTag next to eq / gt / and / etc. (expression.ts). createBuiltinFunctions(inferer) constructs the tag inline; the Proxy dispatch in createFunctions / createAggregateFunctions treats raw like any other builtin lookup. No RS type parameter on Functions / Db / SelectQuery / etc. — the contract is concrete because every SQL adapter provides an inferer.

  5. Facade wiring. Each facade composes the standard pieces: build the execution stack, read stack.adapter.rawCodecInferer, hand it to both createRawSql(...) (for the top-level db.raw) and sqlBuilder({ context, rawCodecInferer }) (for callback-level fns.raw). The two closures are functionally equivalent (same inferer); reference equality is not contracted.

Reviewer notes

  • The largest single concern is BuiltinFunctions / Functions<QC> reshaping in sql-builder. Earlier iterations threaded an RS extends RawSqlTag | undefined generic through Functions / Db / SelectQuery / GroupedQuery / TableProxy to type-narrow fns.rawSql. The current design drops the generic entirely — BuiltinFunctions<CT> declares raw: RawSqlTag as a concrete member, createBuiltinFunctions(inferer) constructs it inline, and the facade requires the inferer at construction. Spot-check that the 130 sql-builder tests still pass on the rebased HEAD.

  • The visitor-arm additions in sql-orm-client (where-binding.ts and query-plan-aggregate.ts) were originally outside the slice spec's enumerated file list — the workspace typecheck surfaced them when ExprVisitor.rawExpr became a required arm. Each is a single-line forward to a reasonable default for that visitor's semantics: pass-through in where-binding; reject-via-rejectHavingExpr in query-plan-aggregate, consistent with that file's treatment of all unsupported aggregate kinds.

  • Manual QA surfaced an undefined-silent-swallow bug (factory loop skipped the interpolation slot when the value was undefined). The fix removes the if (interpolation !== undefined) guard, aligns the factory throw's wording with the spec's verbatim phrase, and expands the off-union runtime-throw test from 1 case to 6 (Date / null / undefined / object / array / class instance).

  • Codec ID format differs between adapters. Postgres uses unversioned ids (pg/int4, pg/text); SQLite uses versioned ids (sqlite/integer@1, sqlite/text@1). This reflects each adapter's pre-existing codec naming convention — both inferCodec impls return ids that already exist in the target's codec registry. Not introduced by this PR.

  • Project artefacts on disk. projects/raw-sql-in-builder/ carries the spec, slice specs, slice plans, dispatch-level code-review log, manual-QA script, and manual-QA report. These are transient — drive-close-project migrates long-lived methodology and deletes the workspace at project close.

Compatibility / migration / risk

SqlRuntimeAdapterDescriptor now requires a rawCodecInferer slot. Existing custom SQL adapters (rare; internal pattern) must add one — typically a 10-line file declaring an object that implements RawCodecInferer.inferCodec. Postgres and SQLite ship theirs in this PR.

SqlOptions.rawCodecInferer (the parameter to sql({...})) is required. Real facade flows wire it automatically from stack.adapter.rawCodecInferer; direct callers (tests, internal scaffolding) must pass one explicitly.

No runtime breaking changes for user-facing flows that go through postgres({...}) / sqlite({...}) — the facades plug rawCodecInferer in for the user.

SqliteClient<TContract>.sql and PostgresClient<TContract>.sql are typed Db<TContract> (no generic widening). The prepare callback's db argument matches.

Testing performed

Workspace-wide:

  • pnpm typecheck — clean across 137 tasks (full turbo).
  • pnpm lint:deps — clean (981 modules, 2028 deps).
  • pnpm build — clean (66/66 tasks).

Package + integration:

  • pnpm --filter @prisma-next/sql-relational-core test — 287/287 pass.
  • pnpm --filter @prisma-next/sql-builder test — 130/130 pass.
  • pnpm --filter @prisma-next/sql-runtime test — 269/269 pass.
  • pnpm --filter @prisma-next/sql-orm-client test — 501/501 pass (+3 skipped).
  • pnpm --filter @prisma-next/adapter-postgres test — 537 pass + 4 expected-fail.
  • pnpm --filter @prisma-next/adapter-sqlite test — 150/150 pass.
  • pnpm --filter @prisma-next/postgres test — 93/93 pass.
  • pnpm --filter @prisma-next/sqlite test — 35/35 pass.
  • pnpm test:integration — passes for the new test/integration/test/sql-builder/raw-sql.integration.test.ts (PGlite-backed, 4 tests covering end-to-end execution + middleware-seam param walks).
  • pnpm test:e2e — passes for the new test/e2e/framework/test/sqlite/raw-sql.test.ts (node:sqlite :memory:, 4 tests covering the same shapes against SQLite).

Alternatives considered

  • Reusing OperationExpr instead of a new RawExpr node. OperationExpr's required self slot is a positional convention that doesn't fit raw expressions — there's no natural receiver, and the zero-interpolation case (rawSql\now()``) becomes awkward. A new AST node is mechanically bounded (one new entry in the discriminated union, one new arm in each visitor / rewriter / folder / lowerer) and semantically honest. Decision pinned in the project spec's "Resolved decisions" section.

  • Sharing the 'raw-sql' kind discriminant between RawExpr (expression-level) and RawSqlExpr (query-level). First-pass implementation did exactly this. isQueryAst ended up returning true for any RawExpr because queryAstKinds is a set-based lookup and the discriminant matched. Distinct discriminants ('raw-expr' vs 'raw-sql') keep the family check honest.

  • Parallel fragments + args arrays inside RawExpr instead of a single mixed parts array. Parallel arrays carry a fragments.length === args.length + 1 invariant that's just bookkeeping once inside the AST. A single mixed array makes the ordering be the structure, removes the invariant, and matches the lowerer's one-line parts.map(p => typeof p === 'string' ? p : lower(p)).join('') shape.

  • Adapter-extensible RawSqlLiteral union. Would re-introduce the coordination cost moving the union to core was meant to eliminate. The set of universally-bindable JS primitives is small and stable; per-adapter or per-extension union extension is rejected — extensions that want a non-primitive JS type accepted ship users through param(value, { codecId }).

  • Including bare Date in RawSqlLiteral. SQL targets have multiple plausible datetime codecs (pg/timestamptz vs pg/timestamp vs pg/date vs pg/time); there's no single default that is right often enough to justify automatic inference. Users always go through param(date, { codecId: '<chosen codec>' }).

  • Threading an RS extends RawSqlTag | undefined generic through Functions<QC, RS> / Db<C, RS> / etc. Earlier iterations did this to type-narrow fns.rawSql between the facade flow (where it's bound) and test scaffolding (where it could be absent). The current design drops the generic entirely by making rawCodecInferer a required descriptor slot — fns.raw is unconditionally a RawSqlTag because every SQL adapter contributes an inferer.

  • Carrying inferCodec as a method on the runtime adapter instance. First-pass implementation. The runtime adapter exists for query execution; coupling codec inference to it conflated two concerns and required threading the adapter instance to the facade ad-hoc. Static contribution on the descriptor lets the facade read stack.adapter.rawCodecInferer without instantiating anything.

  • Keeping db.rawSql === fns.rawSql (reference equality) as a contract. Earlier iterations threaded a single RawSqlTag instance through BuilderContext so that every callback site received the same closure. The current design constructs the tag where it's used (inside createBuiltinFunctions(inferer)) — db.raw and fns.raw are different closures over the same inferer, functionally equivalent. Reference equality was an implementation-detail invariant, not user-observable; dropping it cleaned up the threading.

  • Building separate SQLite integration infrastructure under test/integration/. No existing SQLite harness lives there (PGlite-only). The existing test/e2e/framework/test/sqlite/ setup using Node's built-in node:sqlite was the better-fitting infrastructure — file-backed DatabaseSync, full facade, no new dependency.

Checklist

  • All commits are signed off (git commit -s) per the DCO. The DCO status check will block merge if any commit is missing a Signed-off-by: trailer.
  • I read CONTRIBUTING.md and the change is scoped to one logical concern (the bundled rawSql-in-builder project; three slices co-shipped per the operator-recorded stacked-PR decision).
  • Tests are updated. New: 287 relational-core tests, 130 sql-builder tests, 93 postgres-extension tests, 35 sqlite-extension tests, 537 adapter-postgres tests, 150 adapter-sqlite tests, 4 live-Postgres integration tests, 4 live-SQLite e2e tests, plus 6-case off-union runtime-throw test in relational-core.
  • The PR title is in TML-NNNN: <sentence-case title> form.

@SevInf
SevInf requested a review from a team as a code owner May 26, 2026 15:58
@coderabbitai

coderabbitai Bot commented May 26, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

<review_stack_artifact>

</review_stack_artifact>

Walkthrough

Adds a typed RawExpr AST node and RawSqlLiteral, a tagged-template factory (createRawSql) and param helper, adapter inferCodec implementations, renderer lowering for Postgres/SQLite, builder/runtime wiring to expose a raw tag, validation updates, and comprehensive unit/type/integration/e2e tests exercising the full flow.

Changes

Raw SQL Expression Feature

Layer / File(s) Summary
AST RawExpr node and visitor contracts
packages/2-sql/4-lanes/relational-core/src/ast/types.ts
Adds RawSqlLiteral and RawExpr (kind: 'raw-sql') with parts and returns, extends visitor/rewriter/folder contracts, and includes RawExpr in AnyExpression.
Expression factory: param() and createRawSql()
packages/2-sql/4-lanes/relational-core/src/expression.ts, tests
Adds param(value,{codecId}), RawCodecInferer/RawSqlTag, and createRawSql(adapter) tag that wraps supported literals via adapter.inferCodec, passes through Expression/ParamRef, errors on unsupported types, and builds typed RawExpr via .returns().
Builder/runtime wiring
packages/2-sql/4-lanes/sql-builder/src/...
Threads rawCodecInferer through BuilderContext, createBuiltinFunctions/createFunctions/createAggregateFunctions; exposes raw builtin and updates call sites (select, where, having, orderBy, groupBy, distinctOn, joins, mutation paths).
Adapters: Postgres & SQLite
packages/3-targets/6-adapters/{postgres,sqlite}/src/*
Adds inferCodec(value: RawSqlLiteral) implementations mapping JS values to adapter codec IDs, treats raw-sql as atomic, and implements renderRawExpr to concatenate literal and rendered expression parts; includes adapter-specific tests.
Client integration
packages/3-extensions/{postgres,sqlite}/src/runtime/*
Clients derive rawCodecInferer from stack.adapter, construct raw tag with createRawSql, expose raw on the client, and pass rawCodecInferer into sqlBuilder for main and transaction contexts.
Validation and binding
packages/3-extensions/sql-orm-client/src/*
Where-binding preserves rawSql nodes; grouped-having validator rejects rawSql.
Tests: unit, type-level, integration, e2e
multiple test files across packages
Adds/updates tests verifying AST behavior, factory runtime/type behavior, adapter inference/lowering, composition/facade stability, integration flows, and e2e execution with middleware parameter capture.

🎯 4 (Complex) | ⏱️ ~60 minutes

Suggested reviewers

  • aqrln
  • saevarb

🐰 I stitched raw SQL from string and part,
codecs guessed by adapter's art,
builders threaded the tag through the flow,
renderers lowered fragments down below,
tests danced around — the feature's smart!

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch tml-2668-core-rawexpr-substrate-factory-primitives

@pkg-pr-new

pkg-pr-new Bot commented May 26, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@prisma-next/extension-author-tools

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

@prisma-next/mongo-runtime

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

@prisma-next/family-mongo

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

@prisma-next/sql-runtime

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

@prisma-next/family-sql

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

@prisma-next/extension-arktype-json

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

@prisma-next/extension-cipherstash

npm i https://pkg.pr.new/@prisma-next/extension-cipherstash@594

@prisma-next/middleware-cache

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

@prisma-next/mongo

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

@prisma-next/extension-paradedb

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

@prisma-next/extension-pgvector

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

@prisma-next/extension-postgis

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

@prisma-next/postgres

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

@prisma-next/sql-orm-client

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

@prisma-next/sqlite

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

@prisma-next/target-mongo

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

@prisma-next/adapter-mongo

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

@prisma-next/driver-mongo

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

@prisma-next/contract

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

@prisma-next/utils

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

@prisma-next/config

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

@prisma-next/errors

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

@prisma-next/framework-components

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

@prisma-next/operations

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

@prisma-next/ts-render

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

@prisma-next/contract-authoring

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

@prisma-next/ids

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

@prisma-next/psl-parser

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

@prisma-next/psl-printer

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

@prisma-next/cli

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

@prisma-next/cli-telemetry

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

@prisma-next/emitter

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

@prisma-next/migration-tools

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

prisma-next

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

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

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

@prisma-next/mongo-codec

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

@prisma-next/mongo-contract

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

@prisma-next/mongo-value

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

@prisma-next/mongo-contract-psl

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

@prisma-next/mongo-contract-ts

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

@prisma-next/mongo-emitter

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

@prisma-next/mongo-schema-ir

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

@prisma-next/mongo-query-ast

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

@prisma-next/mongo-orm

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

@prisma-next/mongo-query-builder

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

@prisma-next/mongo-lowering

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

@prisma-next/mongo-wire

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

@prisma-next/sql-contract

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

@prisma-next/sql-errors

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

@prisma-next/sql-operations

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

@prisma-next/sql-schema-ir

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

@prisma-next/sql-contract-psl

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

@prisma-next/sql-contract-ts

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

@prisma-next/sql-contract-emitter

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

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

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

@prisma-next/sql-relational-core

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

@prisma-next/sql-builder

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

@prisma-next/target-postgres

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

@prisma-next/target-sqlite

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

@prisma-next/adapter-postgres

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

@prisma-next/adapter-sqlite

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

@prisma-next/driver-postgres

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

@prisma-next/driver-sqlite

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

commit: e3fee04

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/2-sql/4-lanes/sql-builder/src/types/shared.ts (1)

37-42: ⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Propagate RS through join typings to avoid dropping fns.rawSql in join predicates.

RS is added to WithSelect, but WithJoin still uses ExpressionBuilder<..., QC> (defaulting RS to undefined). That causes join on(...) callbacks to lose raw-SQL typing even when the query chain is raw-enabled.

💡 Proposed type-threading fix
diff --git a/packages/2-sql/4-lanes/sql-builder/src/types/shared.ts b/packages/2-sql/4-lanes/sql-builder/src/types/shared.ts
@@
-export interface WithJoin<QC extends QueryContext, AvailableScope extends Scope, Capabilities> {
+export interface WithJoin<
+  QC extends QueryContext,
+  AvailableScope extends Scope,
+  Capabilities,
+  RS extends RawSqlTag | undefined = undefined,
+> {
@@
-    on: ExpressionBuilder<MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>, QC>,
+    on: ExpressionBuilder<MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>, QC, RS>,
@@
-    on: ExpressionBuilder<MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>, QC>,
+    on: ExpressionBuilder<MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>, QC, RS>,
@@
-    on: ExpressionBuilder<MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>, QC>,
+    on: ExpressionBuilder<MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>, QC, RS>,
@@
-    on: ExpressionBuilder<MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>, QC>,
+    on: ExpressionBuilder<MergeScopes<AvailableScope, Other[typeof JoinOuterScope]>, QC, RS>,
}
diff --git a/packages/2-sql/4-lanes/sql-builder/src/types/table-proxy.ts b/packages/2-sql/4-lanes/sql-builder/src/types/table-proxy.ts
@@
-    WithJoin<QC, AvailableScope, C['capabilities']> {
+    WithJoin<QC, AvailableScope, C['capabilities'], RS> {

Also applies to: 45-57

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/2-sql/4-lanes/sql-builder/src/types/shared.ts` around lines 37 - 42,
WithSelect introduced the RS generic but WithJoin (and the other related types
around the same area) still instantiates ExpressionBuilder as
ExpressionBuilder<..., QC> which defaults RS to undefined and strips fns.rawSql
typing in join on(...) callbacks; propagate the RS generic through these types
by adding RS to WithJoin and every type that constructs ExpressionBuilder (e.g.,
change ExpressionBuilder<..., QC> to ExpressionBuilder<..., QC, RS>) so join
predicates keep the raw-SQL capability (ensure all occurrences that reference
WithJoin/ExpressionBuilder are updated consistently, including the other block
noted around the same section).
🧹 Nitpick comments (2)
packages/2-sql/4-lanes/relational-core/test/ast/raw-expr.test.ts (1)

53-55: ⚡ Quick win

Avoid any in this freeze-invariant test.

Line 54 can use an unknown boundary (or Reflect.set) instead of any while preserving the same runtime assertion.

Possible change
-      // biome-ignore lint/suspicious/noExplicitAny: testing freeze invariant
-      (expr as any).parts = [];
+      Reflect.set(expr as unknown as object, 'parts', []);

As per coding guidelines: "Never use any in TypeScript." and "Prefer unknown over any in tests to keep the unsafe boundary explicit."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/2-sql/4-lanes/relational-core/test/ast/raw-expr.test.ts` around
lines 53 - 55, Replace the unsafe cast "(expr as any).parts = []" with a
controlled unknown boundary by using Reflect.set to mutate the property without
using any; e.g. call Reflect.set(expr as unknown as object, 'parts', []) inside
the same test/expect block so the runtime assertion stays identical while
removing the "any" usage and keeping the unsafe boundary explicit for the
variable "expr".
packages/2-sql/4-lanes/relational-core/test/ast/raw-sql-literal.test-d.ts (1)

4-27: ⚡ Quick win

Make positive type tests non-tautological.

These cases currently pre-annotate v as RawSqlLiteral, so toExtend<RawSqlLiteral>() can’t fail meaningfully. Prefer asserting directly on unannotated values.

As per coding guidelines: "Avoid tautological tests that only restate fixture input."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/2-sql/4-lanes/relational-core/test/ast/raw-sql-literal.test-d.ts`
around lines 4 - 27, The tests are tautological because each variable is
pre-annotated as RawSqlLiteral; remove the explicit type annotations on the test
values (e.g., in tests 'number satisfies RawSqlLiteral', 'string satisfies
RawSqlLiteral', etc.) so TypeScript infers the type (const v = 42, const v =
'hello', etc.), then assert with expectTypeOf(v).toExtend<RawSqlLiteral>();
update all cases (number, string, bigint, boolean, Uint8Array) to use
unannotated v so the assertion can fail if the value's inferred type does not
extend RawSqlLiteral.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/2-sql/4-lanes/relational-core/src/ast/types.ts`:
- Line 627: The `kind` discriminant "raw-sql" is shared by RawExpr and
RawSqlExpr which causes isQueryAst to misclassify RawExpr as a query node;
change RawExpr's readonly kind (the declaration at the current RawExpr
definition) to a distinct value (e.g. "raw-expr") and update all places that
target RawExpr (visitors, lowerers, and any checks) to check the new
discriminant; leave RawSqlExpr as the only query-level "raw-sql" so functions
like isQueryAst, Query visitors, and code paths that currently match "raw-sql"
continue to treat only RawSqlExpr as a query node. Ensure you update all
switch/case or equality checks (including any references in isQueryAst, visitor
functions, and lowerer methods) to use the new RawExpr kind symbol.

---

Outside diff comments:
In `@packages/2-sql/4-lanes/sql-builder/src/types/shared.ts`:
- Around line 37-42: WithSelect introduced the RS generic but WithJoin (and the
other related types around the same area) still instantiates ExpressionBuilder
as ExpressionBuilder<..., QC> which defaults RS to undefined and strips
fns.rawSql typing in join on(...) callbacks; propagate the RS generic through
these types by adding RS to WithJoin and every type that constructs
ExpressionBuilder (e.g., change ExpressionBuilder<..., QC> to
ExpressionBuilder<..., QC, RS>) so join predicates keep the raw-SQL capability
(ensure all occurrences that reference WithJoin/ExpressionBuilder are updated
consistently, including the other block noted around the same section).

---

Nitpick comments:
In `@packages/2-sql/4-lanes/relational-core/test/ast/raw-expr.test.ts`:
- Around line 53-55: Replace the unsafe cast "(expr as any).parts = []" with a
controlled unknown boundary by using Reflect.set to mutate the property without
using any; e.g. call Reflect.set(expr as unknown as object, 'parts', []) inside
the same test/expect block so the runtime assertion stays identical while
removing the "any" usage and keeping the unsafe boundary explicit for the
variable "expr".

In `@packages/2-sql/4-lanes/relational-core/test/ast/raw-sql-literal.test-d.ts`:
- Around line 4-27: The tests are tautological because each variable is
pre-annotated as RawSqlLiteral; remove the explicit type annotations on the test
values (e.g., in tests 'number satisfies RawSqlLiteral', 'string satisfies
RawSqlLiteral', etc.) so TypeScript infers the type (const v = 42, const v =
'hello', etc.), then assert with expectTypeOf(v).toExtend<RawSqlLiteral>();
update all cases (number, string, bigint, boolean, Uint8Array) to use
unannotated v so the assertion can fail if the value's inferred type does not
extend RawSqlLiteral.
🪄 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: 309b684a-fe26-4d15-87c9-38146758cafb

📥 Commits

Reviewing files that changed from the base of the PR and between 5b075bd and 48a70a3.

📒 Files selected for processing (39)
  • packages/2-sql/4-lanes/relational-core/src/ast/types.ts
  • packages/2-sql/4-lanes/relational-core/src/expression.ts
  • packages/2-sql/4-lanes/relational-core/test/ast/raw-expr.test.ts
  • packages/2-sql/4-lanes/relational-core/test/ast/raw-sql-literal.test-d.ts
  • packages/2-sql/4-lanes/relational-core/test/expression/create-raw-sql.test-d.ts
  • packages/2-sql/4-lanes/relational-core/test/expression/create-raw-sql.test.ts
  • packages/2-sql/4-lanes/relational-core/test/expression/param.test.ts
  • packages/2-sql/4-lanes/sql-builder/src/expression.ts
  • packages/2-sql/4-lanes/sql-builder/src/runtime/builder-base.ts
  • packages/2-sql/4-lanes/sql-builder/src/runtime/functions.ts
  • packages/2-sql/4-lanes/sql-builder/src/runtime/joined-tables-impl.ts
  • packages/2-sql/4-lanes/sql-builder/src/runtime/mutation-impl.ts
  • packages/2-sql/4-lanes/sql-builder/src/runtime/query-impl.ts
  • packages/2-sql/4-lanes/sql-builder/src/runtime/sql.ts
  • packages/2-sql/4-lanes/sql-builder/src/runtime/table-proxy-impl.ts
  • packages/2-sql/4-lanes/sql-builder/src/types/db.ts
  • packages/2-sql/4-lanes/sql-builder/src/types/grouped-query.ts
  • packages/2-sql/4-lanes/sql-builder/src/types/select-query.ts
  • packages/2-sql/4-lanes/sql-builder/src/types/shared.ts
  • packages/2-sql/4-lanes/sql-builder/src/types/table-proxy.ts
  • packages/3-extensions/postgres/src/runtime/postgres.ts
  • packages/3-extensions/postgres/test/raw-sql-composition.test.ts
  • packages/3-extensions/postgres/test/raw-sql-facade.test.ts
  • packages/3-extensions/postgres/test/raw-sql.test-d.ts
  • packages/3-extensions/sql-orm-client/src/query-plan-aggregate.ts
  • packages/3-extensions/sql-orm-client/src/where-binding.ts
  • packages/3-extensions/sqlite/src/runtime/sqlite.ts
  • packages/3-extensions/sqlite/test/raw-sql-composition.test.ts
  • packages/3-extensions/sqlite/test/raw-sql-facade.test.ts
  • packages/3-extensions/sqlite/test/raw-sql.test-d.ts
  • packages/3-targets/6-adapters/postgres/src/core/adapter.ts
  • packages/3-targets/6-adapters/postgres/src/core/sql-renderer.ts
  • packages/3-targets/6-adapters/postgres/test/infer-codec.test.ts
  • packages/3-targets/6-adapters/postgres/test/raw-expr-lowering.test.ts
  • packages/3-targets/6-adapters/sqlite/src/core/adapter.ts
  • packages/3-targets/6-adapters/sqlite/test/infer-codec.test.ts
  • packages/3-targets/6-adapters/sqlite/test/raw-expr-lowering.test.ts
  • test/e2e/framework/test/sqlite/raw-sql.test.ts
  • test/integration/test/sql-builder/raw-sql.integration.test.ts

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

🧹 Nitpick comments (1)
packages/2-sql/4-lanes/relational-core/test/expression/param.test.ts (1)

8-10: ⚡ Quick win

Use an object matcher for related result fields

These assertions check one object outcome; prefer a single object matcher for consistency.

Proposed change
     expect(result).toBeInstanceOf(ParamRef);
-    expect(result.value).toBe('hello');
-    expect(result.codec).toEqual({ codecId: 'pg/text' });
+    expect(result).toMatchObject({
+      value: 'hello',
+      codec: { codecId: 'pg/text' },
+    });

As per coding guidelines: "Prefer object matchers (toMatchObject) over multiple individual expect().toBe() calls when checking 2 or more related values in tests."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/2-sql/4-lanes/relational-core/test/expression/param.test.ts` around
lines 8 - 10, Replace the three separate assertions that check the ParamRef
instance and its fields with a single object matcher: assert the result is an
instance of ParamRef and then use toMatchObject (or toEqual with a shape)
against { value: 'hello', codec: { codecId: 'pg/text' } } to verify related
fields in one assertion; target the test that constructs result and references
ParamRef to update expect(result.value) and expect(result.codec) into one
expect(result).toMatchObject(...) while keeping the instance check
(expect(result).toBeInstanceOf(ParamRef)).
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@packages/2-sql/4-lanes/relational-core/test/expression/param.test.ts`:
- Around line 8-10: Replace the three separate assertions that check the
ParamRef instance and its fields with a single object matcher: assert the result
is an instance of ParamRef and then use toMatchObject (or toEqual with a shape)
against { value: 'hello', codec: { codecId: 'pg/text' } } to verify related
fields in one assertion; target the test that constructs result and references
ParamRef to update expect(result.value) and expect(result.codec) into one
expect(result).toMatchObject(...) while keeping the instance check
(expect(result).toBeInstanceOf(ParamRef)).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: 335fd56a-dc17-4670-bba6-1e3d7bf33ee9

📥 Commits

Reviewing files that changed from the base of the PR and between 48a70a3 and 8af8b86.

📒 Files selected for processing (3)
  • packages/2-sql/4-lanes/relational-core/src/expression.ts
  • packages/2-sql/4-lanes/relational-core/test/ast/raw-expr.test.ts
  • packages/2-sql/4-lanes/relational-core/test/expression/param.test.ts

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

🧹 Nitpick comments (1)
packages/2-sql/4-lanes/sql-builder/src/runtime/sql.ts (1)

10-14: 🏗️ Heavy lift

Preserve compile-time gating for raw SQL capability.

adapter being optional here means code can typecheck with fns.rawSql available but still fail at runtime through RUNTIME.RAW_SQL_NO_ADAPTER. Consider encoding adapter presence in the sql() type surface (overload/conditional return type) so unsupported rawSql flows fail at compile time instead of runtime.

Also applies to: 16-23, 51-51

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/2-sql/4-lanes/sql-builder/src/runtime/sql.ts` around lines 10 - 14,
SqlOptions currently makes adapter optional which allows fns.rawSql to typecheck
but fail at runtime; change the type surface so adapter presence is encoded: add
a second variant/overload or conditional return for sql() (e.g.,
SqlOptionsWithoutAdapter vs SqlOptionsWithAdapter or SqlOptions<C, HasAdapter>)
and provide two sql() signatures — one accepting options with adapter that
returns a runtime type exposing fns.rawSql, and one without adapter that returns
a type where fns.rawSql is absent/typed as never (so calls fail at compile
time). Update the related declarations referenced in the diff (SqlOptions, the
sql() function overloads/returns and any places around lines 16-23 and 51) to
use these discriminated/conditional types and keep RUNTIME.RAW_SQL_NO_ADAPTER
behavior for runtime safety.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@packages/2-sql/4-lanes/sql-builder/src/runtime/sql.ts`:
- Around line 10-14: SqlOptions currently makes adapter optional which allows
fns.rawSql to typecheck but fail at runtime; change the type surface so adapter
presence is encoded: add a second variant/overload or conditional return for
sql() (e.g., SqlOptionsWithoutAdapter vs SqlOptionsWithAdapter or SqlOptions<C,
HasAdapter>) and provide two sql() signatures — one accepting options with
adapter that returns a runtime type exposing fns.rawSql, and one without adapter
that returns a type where fns.rawSql is absent/typed as never (so calls fail at
compile time). Update the related declarations referenced in the diff
(SqlOptions, the sql() function overloads/returns and any places around lines
16-23 and 51) to use these discriminated/conditional types and keep
RUNTIME.RAW_SQL_NO_ADAPTER behavior for runtime safety.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: e69cb81d-df3b-4947-ad38-7e8cefc3167d

📥 Commits

Reviewing files that changed from the base of the PR and between 2033d52 and 98ff9d9.

📒 Files selected for processing (24)
  • packages/2-sql/4-lanes/relational-core/src/expression.ts
  • packages/2-sql/4-lanes/sql-builder/src/expression.ts
  • packages/2-sql/4-lanes/sql-builder/src/runtime/builder-base.ts
  • packages/2-sql/4-lanes/sql-builder/src/runtime/functions.ts
  • packages/2-sql/4-lanes/sql-builder/src/runtime/joined-tables-impl.ts
  • packages/2-sql/4-lanes/sql-builder/src/runtime/mutation-impl.ts
  • packages/2-sql/4-lanes/sql-builder/src/runtime/query-impl.ts
  • packages/2-sql/4-lanes/sql-builder/src/runtime/sql.ts
  • packages/2-sql/4-lanes/sql-builder/src/runtime/table-proxy-impl.ts
  • packages/2-sql/4-lanes/sql-builder/src/types/db.ts
  • packages/2-sql/4-lanes/sql-builder/src/types/table-proxy.ts
  • packages/2-sql/4-lanes/sql-builder/test/runtime/functions.test.ts
  • packages/3-extensions/postgres/src/runtime/postgres-serverless.ts
  • packages/3-extensions/postgres/src/runtime/postgres.ts
  • packages/3-extensions/postgres/test/raw-sql-composition.test.ts
  • packages/3-extensions/postgres/test/raw-sql-facade.test.ts
  • packages/3-extensions/postgres/test/raw-sql.test-d.ts
  • packages/3-extensions/sqlite/src/runtime/sqlite.ts
  • packages/3-extensions/sqlite/test/raw-sql-composition.test.ts
  • packages/3-extensions/sqlite/test/raw-sql-facade.test.ts
  • packages/3-extensions/sqlite/test/raw-sql.test-d.ts
  • test/e2e/framework/test/sqlite/raw-sql.test.ts
  • test/integration/test/sql-builder/raw-sql.integration.test.ts
  • test/integration/test/sql-builder/setup.ts
💤 Files with no reviewable changes (2)
  • packages/3-extensions/postgres/test/raw-sql-facade.test.ts
  • packages/3-extensions/sqlite/test/raw-sql-facade.test.ts
🚧 Files skipped from review as they are similar to previous changes (5)
  • packages/2-sql/4-lanes/sql-builder/src/runtime/query-impl.ts
  • packages/2-sql/4-lanes/relational-core/src/expression.ts
  • test/e2e/framework/test/sqlite/raw-sql.test.ts
  • packages/2-sql/4-lanes/sql-builder/src/runtime/table-proxy-impl.ts
  • test/integration/test/sql-builder/raw-sql.integration.test.ts

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/3-extensions/postgres/test/raw-sql-facade.test.ts (1)

66-85: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Add adapter.create() to the stack mock.

postgres({ contract }) now calls stack.adapter.create(stack). At Line 74, the mocked adapter only has id, so tests fail before Line 92/98/103 assertions run.

💡 Suggested fix
 function setupMocks() {
   mocks.createExecutionContext.mockReturnValue({
@@
   mocks.createSqlExecutionStack.mockReturnValue({
     target: { id: 'target-postgres' },
-    adapter: { id: 'adapter-postgres' },
+    adapter: {
+      id: 'adapter-postgres',
+      create: vi.fn(() => ({ inferCodec: () => 'pg/text' })),
+    },
     driver: { create: mocks.driverCreate },
     extensionPacks: [],
   });

Also applies to: 90-103

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/3-extensions/postgres/test/raw-sql-facade.test.ts` around lines 66 -
85, The failing tests are because setupMocks's createSqlExecutionStack mock
returns an adapter object that lacks a create method, but postgres({ contract })
now calls stack.adapter.create(stack); update the mock returned by
mocks.createSqlExecutionStack inside setupMocks so the adapter includes a create
property (e.g., adapter: { id: 'adapter-postgres', create: mocks.adapterCreate }
or adapter: { id: 'adapter-postgres', create: jest.fn().mockReturnValue(/*
appropriate value or Promise */) }), and ensure you define mocks.adapterCreate
(or use an existing mock) to return the expected value so the rest of the test
assertions after stack.adapter.create run correctly.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@packages/3-extensions/postgres/test/raw-sql-facade.test.ts`:
- Around line 66-85: The failing tests are because setupMocks's
createSqlExecutionStack mock returns an adapter object that lacks a create
method, but postgres({ contract }) now calls stack.adapter.create(stack); update
the mock returned by mocks.createSqlExecutionStack inside setupMocks so the
adapter includes a create property (e.g., adapter: { id: 'adapter-postgres',
create: mocks.adapterCreate } or adapter: { id: 'adapter-postgres', create:
jest.fn().mockReturnValue(/* appropriate value or Promise */) }), and ensure you
define mocks.adapterCreate (or use an existing mock) to return the expected
value so the rest of the test assertions after stack.adapter.create run
correctly.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: a1079c87-d429-4ef3-9295-b4132725a589

📥 Commits

Reviewing files that changed from the base of the PR and between 98ff9d9 and cebd98a.

📒 Files selected for processing (45)
  • packages/2-sql/4-lanes/relational-core/src/expression.ts
  • packages/2-sql/4-lanes/sql-builder/src/expression.ts
  • packages/2-sql/4-lanes/sql-builder/src/runtime/builder-base.ts
  • packages/2-sql/4-lanes/sql-builder/src/runtime/functions.ts
  • packages/2-sql/4-lanes/sql-builder/src/runtime/joined-tables-impl.ts
  • packages/2-sql/4-lanes/sql-builder/src/runtime/mutation-impl.ts
  • packages/2-sql/4-lanes/sql-builder/src/runtime/query-impl.ts
  • packages/2-sql/4-lanes/sql-builder/src/runtime/sql.ts
  • packages/2-sql/4-lanes/sql-builder/src/runtime/table-proxy-impl.ts
  • packages/2-sql/4-lanes/sql-builder/test/runtime/annotate.test.ts
  • packages/2-sql/4-lanes/sql-builder/test/runtime/builders.test.ts
  • packages/2-sql/4-lanes/sql-builder/test/runtime/functions.test.ts
  • packages/2-sql/5-runtime/src/sql-context.ts
  • packages/2-sql/5-runtime/test/execution-stack.test.ts
  • packages/2-sql/5-runtime/test/intercept-decoding.test.ts
  • packages/2-sql/5-runtime/test/marker-verification.test.ts
  • packages/2-sql/5-runtime/test/marker-vs-intercept-ordering.test.ts
  • packages/2-sql/5-runtime/test/runtime-ctx-passthrough.test.ts
  • packages/2-sql/5-runtime/test/sql-runtime-abort.test.ts
  • packages/2-sql/5-runtime/test/sql-runtime.test.ts
  • packages/2-sql/5-runtime/test/utils.ts
  • packages/3-extensions/postgres/src/runtime/postgres-serverless.ts
  • packages/3-extensions/postgres/src/runtime/postgres.ts
  • packages/3-extensions/postgres/test/raw-sql-composition.test.ts
  • packages/3-extensions/postgres/test/raw-sql-facade.test.ts
  • packages/3-extensions/postgres/test/raw-sql.test-d.ts
  • packages/3-extensions/sqlite/src/runtime/sqlite.ts
  • packages/3-extensions/sqlite/test/raw-sql-composition.test.ts
  • packages/3-extensions/sqlite/test/raw-sql-facade.test.ts
  • packages/3-extensions/sqlite/test/raw-sql.test-d.ts
  • packages/3-targets/6-adapters/postgres/src/exports/runtime.ts
  • test/e2e/framework/test/sqlite/raw-sql.test.ts
  • test/integration/test/cli-journeys/data-transform-enum-rebuild.e2e.test.ts
  • test/integration/test/cli-journeys/data-transform-not-null-backfill.e2e.test.ts
  • test/integration/test/cli-journeys/data-transform-nullable-tightening.e2e.test.ts
  • test/integration/test/cli-journeys/data-transform-type-change.e2e.test.ts
  • test/integration/test/cli-journeys/invariant-routing.e2e.test.ts
  • test/integration/test/contract-builder.test.ts
  • test/integration/test/contract-builder.types.test-d.ts
  • test/integration/test/cross-package/middleware-cache.test.ts
  • test/integration/test/dsl-type-inference.test-d.ts
  • test/integration/test/rewriting-middleware.integration.test.ts
  • test/integration/test/runtime.verify-marker.missing-table.integration.test.ts
  • test/integration/test/sql-builder/raw-sql.integration.test.ts
  • test/integration/test/sql-builder/setup.ts
✅ Files skipped from review due to trivial changes (5)
  • test/integration/test/cli-journeys/data-transform-nullable-tightening.e2e.test.ts
  • test/integration/test/cli-journeys/data-transform-not-null-backfill.e2e.test.ts
  • test/integration/test/cli-journeys/data-transform-type-change.e2e.test.ts
  • packages/3-targets/6-adapters/postgres/src/exports/runtime.ts
  • test/integration/test/cli-journeys/data-transform-enum-rebuild.e2e.test.ts
🚧 Files skipped from review as they are similar to previous changes (12)
  • test/integration/test/sql-builder/setup.ts
  • packages/2-sql/4-lanes/sql-builder/src/runtime/joined-tables-impl.ts
  • packages/2-sql/4-lanes/sql-builder/src/expression.ts
  • packages/3-extensions/postgres/test/raw-sql.test-d.ts
  • packages/2-sql/4-lanes/sql-builder/test/runtime/functions.test.ts
  • test/e2e/framework/test/sqlite/raw-sql.test.ts
  • packages/2-sql/4-lanes/relational-core/src/expression.ts
  • packages/3-extensions/sqlite/test/raw-sql.test-d.ts
  • packages/3-extensions/sqlite/test/raw-sql-composition.test.ts
  • packages/3-extensions/postgres/test/raw-sql-composition.test.ts
  • packages/3-extensions/sqlite/test/raw-sql-facade.test.ts
  • test/integration/test/sql-builder/raw-sql.integration.test.ts

@SevInf
SevInf force-pushed the tml-2668-core-rawexpr-substrate-factory-primitives branch 5 times, most recently from 3237463 to 246880d Compare May 29, 2026 15:19
@github-actions

github-actions Bot commented May 29, 2026 •

Copy link
Copy Markdown

size-limit report 📦

Path Size
postgres / no-emit 135.07 KB (+0.46% 🔺)
postgres / emit 124.86 KB (+0.47% 🔺)
mongo / no-emit 73.92 KB (0%)
mongo / emit 68.7 KB (0%)

SevInf and others added 17 commits May 29, 2026 17:22
Add the RawExpr class to ast/types.ts — a new discriminated-union member
of AnyExpression with kind 'raw-sql'. Shape: parts: ReadonlyArray<string |
AnyExpression> and returns: ParamSpec. Constructor calls frozenArrayCopy
on parts then this.freeze() to match the OperationExpr pattern.

Visitor arm rawSql(expr: RawExpr): R is required on ExprVisitor so
exhaustiveness checks in adapter renderExpr switches break at typecheck
time if the arm is missing. Rewriter arm rawSql?(expr) and folder arm
rawSql?(expr) are optional, following the existing convention for list and
select arms. The fold fallback walks expression elements in parts and
combines them, mirroring ListExpression.fold so collectParamRefs traverses
nested ParamRefs correctly.

baseColumnRef() is not overridden; the base Expression class throws
'RawExpr does not expose a base column reference', matching the
AggregateExpr.count() precedent.

Tests cover: zero-interpolation shape, mixed parts, freeze invariant,
baseColumnRef throw, ExprVisitor dispatch, rewriter arm (with and without
rawSql), folder arm (with and without rawSql), collectParamRefs traversal,
back-to-back empty-string parts preservation.

Refs: TML-2668

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Signed-off-by: Serhii Tatarintsev <[email protected]>
Add case 'raw-sql' to the Postgres renderExpr switch before the
assertNever default. The arm delegates to a new renderRawExpr helper that
maps each RawExpr.parts element: string parts are emitted verbatim;
AnyExpression parts are recursed through the existing renderExpr path.
Positional $N accounting for any ParamRef elements in parts flows through
the existing renderParamRef path unchanged.

Also extend isAtomicExpressionKind to handle 'raw-sql' (returns false,
treating a raw expression as composite for IS NULL / binary grouping).

Tests cover: zero-interpolation verbatim emission, single ParamRef with
$1 index, two ParamRefs with sequential $1/$2 indices, back-to-back
empty-string parts (no-op), nested column ref, LiteralExpr element.

Refs: TML-2668

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Signed-off-by: Serhii Tatarintsev <[email protected]>
Add case 'raw-sql' to the SQLite renderExpr switch before the default
throw. The arm delegates to a new renderRawExpr helper that maps each
RawExpr.parts element: string parts are emitted verbatim; AnyExpression
parts are recursed through the existing renderExpr path.

The SQLite renderer differs from Postgres in that it does not carry a
ParamIndexMap — param-refs render as bare '?' placeholders and values are
collected separately via collectParamRefs(). The renderRawExpr helper
mirrors this: it passes the existing contract argument through and lets the
existing renderExpr cases handle each expression element.

Tests cover: zero-interpolation verbatim emission, single ParamRef with '?'
placeholder, two ParamRefs each becoming '?', back-to-back empty-string
parts (no-op, yields '??'), nested column ref, LiteralExpr element.

Refs: TML-2668

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Signed-off-by: Serhii Tatarintsev <[email protected]>
ExprVisitor.rawSql is required on all ExprVisitor<R> implementations.
Two consumers in sql-orm-client were not updated in the substrate commit
because they live in a different package:

- where-binding.ts: bindWhereExprNode passes RawExpr through unchanged;
  the expression carries its own parts and does not require codec binding.
- query-plan-aggregate.ts: validateGroupedHavingExpr rejects raw-sql with
  the same rejectHavingExpr handler used for other unsupported kinds.

Refs: TML-2668

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Signed-off-by: Serhii Tatarintsev <[email protected]>
Add the closed `RawSqlLiteral` union type to `ast/types.ts` as the set of JS
scalar values that can appear as bare raw-SQL interpolations. `Date` is
excluded — it must be routed through `param(date, { codecId })` to select the
target codec (timestamp vs. timestamptz, precision, timezone semantics).

Add the `param<T>(value, { codecId })` helper to `expression.ts` as a thin
convenience wrapper over `ParamRef.of`. Constructs the `CodecRef` inline as
`{ codecId: opts.codecId }` (no factory helper exists; `CodecRef` is a plain
structural type).

Both exports flow automatically through the existing `export *` barrels in
`exports/ast.ts` and `exports/expression.ts` → `index.ts`.

Type-level tests in `test/ast/raw-sql-literal.test-d.ts` cover all five positive
members (number, bigint, string, boolean, Uint8Array) and six negative cases
(Date, null, undefined, plain object, array, custom class instance).

Runtime tests in `test/expression/param.test.ts` verify value preservation,
codec stamping, structural equivalence with `ParamRef.of`, and codec-agnosticity
across four codec IDs.

Refs: TML-2668

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Signed-off-by: Serhii Tatarintsev <[email protected]>
…ate interpolation

Adds the `createRawSql(adapter)` factory that returns a tagged-template
function accepting SQL string fragments interleaved with typed interpolations
(Expression, ParamRef, or bare RawSqlLiteral). Calling `.returns(spec)` on
the result produces a typed `Expression` whose `buildAst()` returns a RawExpr.

Interpolation resolution:
- Expression-like (has buildAst) → unwrapped via buildAst()
- ParamRef instance → passed through unchanged
- Bare RawSqlLiteral → wrapped as ParamRef with codec from adapter.inferCodec()
- Anything else → defence-in-depth throw (type system normally prevents this)

Also exports RawSqlTag and RawSqlBuilder interfaces for consumer use.

Tests: 21 new runtime tests in create-raw-sql.test.ts covering zero-interpolation,
back-to-back interpolations, all RawSqlLiteral member types, ParamRef pass-through,
Expression unwrapping, number boundary cases, param() override, .returns()
normalization, nested RawExpr, and defence-in-depth throw. Type-level tests in
create-raw-sql.test-d.ts verify positive interpolation types and negative rejection
of Date/null/undefined/object/array/class interpolations.

Refs: TML-2668

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Signed-off-by: Serhii Tatarintsev <[email protected]>
…urns()

Addresses F1 from D3 R1. Refs: TML-2668.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Signed-off-by: Serhii Tatarintsev <[email protected]>
…e mapping

Adds `inferCodec(value: RawSqlLiteral): string` as a public method on
`PostgresAdapterImpl`. The method maps JS value types to canonical Postgres
codec IDs:
  - number (safe integer, divisible by 1) → pg/int4
  - number (fractional or beyond MAX_SAFE_INTEGER) → pg/float8
  - bigint → pg/int8
  - string → pg/text
  - boolean → pg/bool
  - Uint8Array → pg/bytea
  - all other types → defence-in-depth throw

The method is slotted before `lower()` on the class. No changes to the
`Adapter` interface in relational-core; the method is matched structurally
by the private `RawSqlAdapter` duck-type interface from slice 1.
`Object.freeze` in `createPostgresAdapter` picks up the new method
automatically.

Unit tests cover all mapping cases, boundary values (-0, MAX_SAFE_INTEGER+1,
empty string, empty Uint8Array), and five defence-in-depth throw paths.
Negative-path tests use `as unknown as { inferCodec(v: unknown): string }`
to reach the runtime guard from TypeScript-land without suppression.

Refs: TML-2671

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Signed-off-by: Serhii Tatarintsev <[email protected]>
…postgres facade

Bind createRawSql(adapter) once at postgres({...}) construction time.
Expose the bound RawSqlTag as db.rawSql on PostgresClient<TContract>.
Thread the tag through BuilderContext.rawSqlTag so every createFunctions /
createAggregateFunctions dispatch site can return it via fns.rawSql.

- Add rawSqlTag: RawSqlTag | undefined to BuilderContext
- Extend SqlOptions with optional rawSqlTag; pass it into BuilderContext
- createFunctions / createAggregateFunctions accept optional rawSqlTag
- Proxy get trap returns rawSqlTag for the 'rawSql' key (before builtins)
- Functions<QC> and AggregateFunctions<QC> types gain rawSql: RawSqlTag
- All call sites in builder-base, query-impl, joined-tables-impl,
  mutation-impl, table-proxy-impl pass ctx.rawSqlTag
- postgres.ts: createPostgresAdapter() → createRawSql() once per client;
  sqlBuilder receives rawSqlTag; PostgresClient exposes rawSql field
- Transaction sqlBuilder also receives the same rawSqlTag reference

Refs: TML-2671
Signed-off-by: Serhii Tatarintsev <[email protected]>
…Sql facade

Verify the bound RawSqlTag flows through the Proxy as a single reference:
- fns.rawSql === tag for createFunctions dispatch (where, groupBy, orderBy,
  distinctOn, join on)
- fns.rawSql === tag for createAggregateFunctions dispatch (select aliased,
  select bulk-object, having)
- All six callback dispatch sites return the same tag reference
- Graceful degradation: rawSql is undefined when no tag is provided
- postgres client: rawSql is a function; stable across accesses; distinct
  clients get distinct tags
- AC12: bare number goes through adapter inferCodec; param() override
  threads an explicit codecId through the RawExpr parts

Refs: TML-2671
Signed-off-by: Serhii Tatarintsev <[email protected]>
…ess)

Use typed helper rawSqlOf() instead of casting to Record<string, unknown>
to avoid noPropertyAccessFromIndexSignature errors when accessing rawSql.

Refs: TML-2671
Signed-off-by: Serhii Tatarintsev <[email protected]>
Rename describe blocks to use property-oriented descriptions rather than
planning artifact IDs, per no-transient-project-ids rule.

Refs: TML-2671
Signed-off-by: Serhii Tatarintsev <[email protected]>
The Proxy returns undefined when BuilderContext.rawSqlTag is absent (e.g. test
scaffolding without adapter wiring). The previous type claimed RawSqlTag (non-
optional), which was a lie the compiler could not catch. Aligning the type with
the runtime behavior.

Refs: TML-2671

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Signed-off-by: Serhii Tatarintsev <[email protected]>
…rawSql tests

AC12 tests now assert the concrete codec ids on both interpolation paths:
- bare number (safe integer) → pg/int4 (adapter inferCodec)
- param() with explicit codecId → pg/int8 (override path)

Two end-to-end chain tests drive rawSql through the typed builder surface and
assert reference equality inside .where and .select(alias, cb) callbacks.
These close the integration loop from the facade rawSqlTag through
createFunctions / createAggregateFunctions to the fns argument received
by builder callbacks.

Refs: TML-2671

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Signed-off-by: Serhii Tatarintsev <[email protected]>
Addresses F5 from D2 R2 review. Refs: TML-2671.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Signed-off-by: Serhii Tatarintsev <[email protected]>
…uilder

Add raw-sql-composition.test.ts covering:
- aliased single-column .select emitting RawExpr in the projection list
- aliased .select with field interpolation producing correct RawExpr parts
- bulk-object .select carrying IdentifierRef and RawExpr entries
- .where with fns.gt(rawSql, literal) producing BinaryExpr with RawExpr left operand
- fns.count(rawSql) producing AggregateExpr whose argument is a RawExpr
- nested rawSql inside rawSql: outer parts contain inner RawExpr (AST assertion)
- nested rawSql: inner IdentifierRef accessible at depth 2 through outer RawExpr

Add raw-sql.test-d.ts covering:
- field reference Expression<T> typechecks as rawSql interpolation
- typed Expression from a builder function typechecks as rawSql interpolation
- fns.count(fns.rawSql`...`.returns(...)) aggregate composition typechecks

All tests are pure unit-level (no live database). Source files unchanged.

Refs: TML-2671
Signed-off-by: Serhii Tatarintsev <[email protected]>
…el tests

Addresses F6 from D3 R1 review. Refs: TML-2671.

Signed-off-by: Serhii Tatarintsev <[email protected]>
SevInf and others added 24 commits May 29, 2026 17:22
… narrowing

Add RS (RawSqlTag | undefined, default undefined) to Functions, AggregateFunctions,
ExpressionBuilder, WithSelect, SelectQuery, GroupedQuery, TableProxy, and Db so
the postgres-facade flow can expose fns.rawSql: RawSqlTag (non-optional) while
test-scaffolding paths without a tag keep fns.rawSql: undefined.

createFunctions / createAggregateFunctions gain overloads:
  - (ops, tag: RawSqlTag) => Functions<QC, RawSqlTag>
  - (ops, tag?: undefined) => Functions<QC, undefined>
  - (ops, tag: RawSqlTag | undefined) => Functions<QC, RawSqlTag | undefined>

The third overload is picked at internal call sites that pass ctx.rawSqlTag
(RawSqlTag | undefined). Internal cast sites updated to AggregateFunctions<QC, RawSqlTag | undefined>.

postgres.ts: PostgresClient.sql, .prepare callback, and .transaction callback now
typed as Db<TContract, RawSqlTag> so callbacks receive fns.rawSql: RawSqlTag.

Refs: TML-2671
Signed-off-by: Serhii Tatarintsev <[email protected]>
…Tag | undefined>

Internal expression-builder dispatch sites that pass ctx.rawSqlTag
(RawSqlTag | undefined) now get Functions<QC, RawSqlTag | undefined> back from
createFunctions/createAggregateFunctions. Update cast types in builder-base.ts
and cast fns at the call site in query-impl.ts + joined-tables-impl.ts to
maintain structural compatibility with existing callback signatures.

table-proxy-impl: as() return type explicitly includes QC to match the
updated TableProxy interface's type parameter ordering.

Refs: TML-2671
Signed-off-by: Serhii Tatarintsev <[email protected]>
…e fns.rawSql directly

- raw-sql.test-d.ts: add assertType<Db<C, RawSqlTag>> gate; replace inline fns stubs
  ({ rawSql: typeof tag }) with AggregateFunctions<QueryContext, RawSqlTag>; update
  comments to reflect that fns.rawSql is non-optional when sql() receives rawSqlTag
- raw-sql.integration.test.ts: replace closure-captured rawSqlTag`...` calls with
  fns.rawSql`...` in all four sites (aliased select, literal select, where gt/0 pair)

Refs: TML-2671

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Signed-off-by: Serhii Tatarintsev <[email protected]>
…tion test

In createAggregateFunctions, the implementation signature already accepts
RawSqlTag | undefined, making the 'as RawSqlTag' cast on the createFunctions
call redundant. Removed.

In the fourth integration test (param-count-capture middleware), the where
callback was capturing rawSqlTag from the enclosing closure instead of
using fns.rawSql. Updated to fns.rawSql`...` directly, consistent with
the other three tests in the suite.

Refs: TML-2671

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Signed-off-by: Serhii Tatarintsev <[email protected]>
…dec end-to-end

Adds six end-to-end tests that close the verification loop between the
Postgres adapter's inferCodec (in @prisma-next/adapter-postgres) and the
ParamRef codec stamped by createRawSql. Each test builds an expression
using a real Postgres-bound RawSqlTag, then inspects RawExpr.parts to
assert the ParamRef.codec.codecId matches the canonical Postgres mapping:

  safe integer → pg/int4
  fractional number → pg/float8
  string → pg/text
  bigint → pg/int8
  boolean → pg/bool
  Uint8Array → pg/bytea

Codec IDs are unversioned (no @1 suffix) — inferCodec returns the plain
form; versioned forms (pg/int4@1 etc.) are used in contract storage codecs
and param() overrides, but not in the inferred path.

Refs: TML-2671

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Signed-off-by: Serhii Tatarintsev <[email protected]>
Map JS value types to SQLite codec IDs for raw-SQL interpolation.
Mirrors PostgresAdapterImpl.inferCodec shape: switch on typeof,
with number → sqlite/integer@1 or sqlite/real@1 (safe-int check),
bigint → sqlite/bigint@1 (distinct codec, operator-resolved),
string → sqlite/text@1, boolean → sqlite/integer@1 (no native bool),
Uint8Array → sqlite/blob@1. Runtime guard throws for unsupported types.

Refs: TML-2669
Signed-off-by: Serhii Tatarintsev <[email protected]>
Bind createRawSql(createSqliteAdapter()) once at sqlite({...}) client
construction. Expose rawSql: RawSqlTag on SqliteClient<TContract> and
pass rawSqlTag into sqlBuilder<TContract, RawSqlTag>({ context, rawSqlTag })
so db.sql is narrowed to Db<TContract, RawSqlTag>.

Also updates prepare() callback type from Db<TContract> to
Db<TContract, RawSqlTag> for consistency.

Refs: TML-2669
Co-Authored-By: Claude Opus 4.7 <[email protected]>
Signed-off-by: Serhii Tatarintsev <[email protected]>
…l facade

Adds raw-sql-facade.test.ts covering:
- rawSql surface reachability (callable function, per-client binding, stability)
- fns.rawSql reference equality via createFunctions / createAggregateFunctions
  for every callback dispatch site: .where, aliased .select, bulk .select,
  .groupBy, .orderBy, .having, join on
- AC12 param() override: bare 42 → sqlite/integer@1; param(42, { codecId:
  'sqlite/real@1' }) → sqlite/real@1 (override beats adapter default)
- fns.rawSql reference equality through real builder chain (.where + aliased .select)

Refs: TML-2669
Co-Authored-By: Claude Opus 4.7 <[email protected]>
Signed-off-by: Serhii Tatarintsev <[email protected]>
…or rawSql facade

Add unit tests covering rawSql composition with the typed builder (AC21–AC25
aliased select, bulk-object select, where+gt, count, nested), type-level
assertType tests for AC18 (Db<C, RawSqlTag> and field reference as rawSql
interpolation through createSqliteAdapter), and 6 end-to-end codec inference
tests (AC6–AC11) verifying each RawSqlLiteral member type resolves to the
correct sqlite/* codec through createSqliteAdapter() → createRawSql() →
tag`...`.buildAst() → ParamRef.codec.codecId.

Refs: TML-2669

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Signed-off-by: Serhii Tatarintsev <[email protected]>
Add raw-sql.test.ts covering AC26 (rawSql against a real file-backed SQLite
database returns expected computed rows) and NFR3 (ParamRef instances from
rawSql interpolations surface in beforeExecute params.entries() walk).

Tests use an inline buildHarness helper that seeds posts rows, wires
createRawSql(createSqliteAdapter()) into sql<Contract, RawSqlTag>(), and
passes optional middleware to createRuntime(). No changes to withSqliteTestRuntime
or any source package.

Refs: TML-2669

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Signed-off-by: Serhii Tatarintsev <[email protected]>
…fence-in-depth message with spec FR10

Addresses F-1 + F-2 from manual-QA report 2026-05-26. Refs: TML-2668, TML-2671, TML-2669.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Signed-off-by: Serhii Tatarintsev <[email protected]>
…ion on raw-SQL interpolation guard

Address inline review comments:

- expression.ts: add `value satisfies never` before the defence-in-depth
  throw in `resolveInterpolation` so future additions to the
  `RawSqlInterpolation` union surface as a compile-time exhaustiveness
  failure instead of going to the runtime fallthrough.
- raw-expr.test.ts: remove three property-assignment smoke tests and one
  duplicate `Object.freeze` assertion; the remaining cases cover the
  load-bearing AST contract (parts freeze, baseColumnRef throw, visitor
  dispatch, rewrite, fold, collectParamRefs, empty-string parts).
- raw-expr.test.ts: include `windowFunc` arm in the test ExprVisitor
  (post-rebase ExprVisitor requires it).
- param.test.ts: collapse 8 redundant cases into one smoke test;
  `param()` is a one-line forwarder over `ParamRef.of`.
- raw-sql-literal.test-d.ts: deleted; the closed union's positive +
  negative coverage already lives in
  `test/expression/create-raw-sql.test-d.ts` at the factory level
  (which is the user-reachable surface).

Refs: TML-2668, TML-2671, TML-2669
Signed-off-by: Serhii Tatarintsev <[email protected]>
`rawSql` was carried as a separate field on `Functions<QC, RS>` via a
trailing intersection, with the runtime `createFunctions` /
`createAggregateFunctions` Proxies special-casing the `'rawSql'`
property. It is conceptually another non-operation member of `fns`
alongside `eq` / `gt` / `and` / etc., so put it on
`BuiltinFunctions<CT, RS>` and let the regular builtin-lookup path
handle it.

Drops the special-case branches in both Proxies. Switches the lookup
to `Object.hasOwn(builtins, prop)` so the `rawSql: undefined` case is
covered uniformly with the function-valued builtins instead of leaking
into the operation-lookup path.

Signed-off-by: Serhii Tatarintsev <[email protected]>
…BuiltinFunctions

`rawSql` was threaded as an `RS extends RawSqlTag | undefined` generic
through 11 declaration sites — BuiltinFunctions, Functions,
AggregateFunctions, ExpressionBuilder, Db, SelectQuery, GroupedQuery,
WithSelect, TableProxy, the sql() factory. The runtime threaded the
prebuilt tag through `BuilderContext.rawSqlTag?` across 13 dispatch
sites with three-overload narrowing on createFunctions /
createAggregateFunctions.

`rawSql` is conceptually another builtin alongside eq / gt / etc.
Declare it concretely on `BuiltinFunctions<CT>` as
`readonly rawSql: RawSqlTag` and let `createBuiltinFunctions(adapter)`
construct it ad-hoc via `createRawSql(adapter)`. BuilderContext now
carries the adapter, not the tag; all dispatch sites pass
`ctx.adapter` through.

`SqlOptions.adapter` is optional with a no-op default that throws
RUNTIME.RAW_SQL_NO_ADAPTER if `fns.rawSql` is invoked without adapter
wiring. Test scaffolding that never touches raw SQL stays ergonomic;
real facades wire the adapter explicitly.

Tradeoff: `db.rawSql !== fns.rawSql` by reference (each closure is
constructed where used). Functionally equivalent — AC27 dropped along
with its reference-equality tests.

26 files changed, +214 / -531 LoC.

Signed-off-by: Serhii Tatarintsev <[email protected]>
…rer; reuse stack adapter

Three coupled changes addressing inline review feedback on the
slice-2/3 rawSql wiring:

1. Public API: `db.rawSql` / `fns.rawSql` → `db.raw` / `fns.raw`.
   `rawSql` was reading as a method ("raw SQL"); `raw` is the natural
   builtin name alongside `eq` / `gt` / `count`.

2. Type rename: `RawSqlAdapter` → `RawCodecInferer`. The interface has
   one method (`inferCodec`) and exists to look up a codec id for a
   bare-literal interpolation — calling it "adapter" overloaded the
   term used by the execution stack. `SqlOptions.adapter?` becomes
   `SqlOptions.rawCodecInferer` and is now required (no throwing
   default).

3. Adapter reuse: the postgres / sqlite facades now derive the
   inferer from `stack.adapter.create(stack)` instead of separately
   importing `createPostgresAdapter()` / `createSqliteAdapter()`.
   `SqlRuntimeAdapterInstance` (and the target-specific
   `SqlRuntimeAdapter` in the postgres exports) extends
   `RawCodecInferer`, so the same adapter instance the execution
   stack uses also satisfies the raw-SQL contract.

Test scaffolding that constructs `sql({ context })` directly now
declares a minimal stub inferer; the runtime test stubs that mock
`SqlRuntimeAdapterInstance` declare `inferCodec` on their stub
adapters.

Signed-off-by: Serhii Tatarintsev <[email protected]>
…r in new test scaffolds

Post-rebase against origin/main: two upstream changes hit my code:

1. `CreateRuntimeOptions.verify` was renamed to `verifyMarker` (with a
   simplified `false | VerifyMarkerOption` shape) — update the two
   raw-SQL tests that opted out of marker verification.

2. New test scaffolds landed upstream that construct `sql({ context })`
   without a `rawCodecInferer`: `test/e2e/framework/test/utils.ts`,
   `test/e2e/framework/test/sqlite/{utils,raw-sql,runtime.verify-marker.missing-table}.test.ts`,
   and the prisma-next-demo example's no-emit context + integration
   tests. Wire each one through:
   - postgres e2e: pass `rawCodecInferer: { inferCodec: () => 'pg/text' }`
     inline (the StubAdapter from sql-runtime test utils does not flow
     `inferCodec` through TypeScript's structural check cleanly enough
     for the assignment to typecheck — falling back to an inline stub).
   - sqlite e2e: extend `createSqliteRuntime` to return the
     stack-instance adapter and thread it through as `rawCodecInferer`.
   - demo: minimal inline stub (read-only contexts that never invoke
     `fns.raw`).

Also: declare `inferCodec` on the `StubAdapter` type in
`packages/2-sql/5-runtime/test/utils.ts` for symmetry with the new
`SqlRuntimeAdapterInstance` contract.

Signed-off-by: Serhii Tatarintsev <[email protected]>
…ite tests

The postgres + sqlite facades now derive the raw-SQL inferer from
`stack.adapter.create(stack)` (per the rawCodecInferer refactor),
so the test mocks for `createSqlExecutionStack` must return an
`adapter` shape that actually exposes a `create()` method returning
something with `inferCodec`. Update all 6 mock setups
(postgres.test, postgres-close.test, postgres-serverless.test,
postgres/raw-sql-facade.test, sqlite-close.test,
sqlite/raw-sql-facade.test).

Signed-off-by: Serhii Tatarintsev <[email protected]>
…or.rawCodecInferer

The raw-SQL codec inferer was an instance-level concern (a method on
PostgresAdapterImpl / SqliteAdapterImpl reached through the runtime
adapter instance). Move it to a static contribution on the adapter
descriptor, required for every SQL adapter:

```ts
export interface SqlRuntimeAdapterDescriptor<...>
  extends RuntimeAdapterDescriptor<...>, SqlStaticContributions {
  readonly rawCodecInferer: RawCodecInferer;
}
```

- Postgres + sqlite descriptors now contribute exported
  `postgresRawCodecInferer` / `sqliteRawCodecInferer` constants (the
  same `typeof` switch that used to live as an instance method).
- Facades (`postgres.ts`, `postgres-serverless.ts`, `sqlite.ts`) read
  `stack.adapter.rawCodecInferer` at construction time — no second
  adapter instance to dispose of.
- `SqlRuntimeAdapterInstance` no longer extends `RawCodecInferer`;
  the inferer is decoupled from the runtime adapter's execution
  shape.
- Test stubs across `@prisma-next/sql-runtime`, the postgres + sqlite
  facade mocks, and the test-utils helper contribute a minimal
  `rawCodecInferer` slot on their stub descriptors.
- `infer-codec.test.ts` for both adapters now exercises the
  standalone `*RawCodecInferer` constant directly.

Signed-off-by: Serhii Tatarintsev <[email protected]>
…ter, and with typed-expression interpolation

Single query that hits all three places `fns.raw` is meant to be
useful when the stock operators don't cover the SQL:

1. Projection: `select('upper_email', (f, fns) =>
   fns.raw\`UPPER(${f.email})\`.returns('pg/text@1'))` — aliased
   column added to the row type with the declared codec.
2. Filter: `where((f, fns) =>
   fns.raw\`LENGTH(${f.email}) > 10\`.returns('pg/bool@1'))` — raw
   fragment as a `WHERE` predicate.
3. Typed-expression substitution: `${f.email}` inside the template
   lowers to the column's `IdentifierRef` (not a string splice); the
   contract-bound codec stays intact through the AST.

Run: `pnpm start -- raw-sql-demo [limit]`.
Signed-off-by: Serhii Tatarintsev <[email protected]>
… field reference

`${fns.eq(f.kind, 'admin')}` interpolates a `BinaryExpr` AST node into
the raw template — showing that any `Expression<…>` (aggregate
results, builder-operator output, nested raw fragments) flows through
unchanged, not just bare field references.

The new projection emits

```sql
CASE WHEN user.kind = $1 THEN 'admin' ELSE 'regular user' END AS kind_label
```

with the `fns.eq` result becoming a bound `BinaryExpr(eq)` between
`ColumnRef(user.kind)` and `ParamRef('admin')`, both carrying their
contract-bound codecs through to render.

Signed-off-by: Serhii Tatarintsev <[email protected]>
…filter

- Rename `upper_email` / `kind_label` to `upperEmail` / `kindLabel`
  for JS-friendly row keys.
- Filter via `fns.gt(fns.raw\`LENGTH(...)\`.returns('pg/int4@1'), 10)`
  instead of a fully-raw boolean: the raw fragment now contributes
  just the integer subexpression, and the comparison comes from the
  stock `fns.gt` operator. Better demonstrates composition between
  raw fragments and typed builder operators.

Signed-off-by: Serhii Tatarintsev <[email protected]>
… isQueryAst misclassification

RawExpr (expression-level) and RawSqlExpr (query-level) both declared
`readonly kind = 'raw-sql' as const`. `queryAstKinds` lists `'raw-sql'`
to recognise the query-level node, but the shared discriminant means
`isQueryAst(rawExpr)` returns `true` for an expression — a real false
positive at every site that dispatches off the set.

Rename `RawExpr.kind` to `'raw-expr'`. RawSqlExpr stays as the only
`'raw-sql'`, so `queryAstKinds`, `isQueryAst`, the lints middleware,
the codec-decoder's projection lookup, and the postgres `renderQuery`
switch keep their semantics. Update the three expression-level
switches that used to match `RawExpr` under `'raw-sql'`:

- `sqlite/core/adapter.ts` `renderExpr` switch (expression-level)
- `postgres/core/sql-renderer.ts` `renderExpr` switch (expression-level)
- `postgres/core/sql-renderer.ts` `isAtomicExpressionKind` switch
  (composite-vs-atomic parens decision; enumerates `AnyExpression['kind']`)

No test asserts `kind === 'raw-sql'` on a RawExpr directly; visitor
dispatch uses the `rawSql` method name (unchanged); only switch/case
on the discriminant needed updating.

Signed-off-by: Serhii Tatarintsev <[email protected]>
Renames + cleanup driven by inline REVIEW comments:

- Drop 5 raw-SQL tests from the postgres/sqlite extension packages —
  they duplicated coverage that already lives in
  `@prisma-next/sql-relational-core` (factory shape, AST surface,
  type-level interpolation contract). The extension-level coverage
  was end-to-end via the integration test, not unit-level repetition.

- `Db<C>` in sql-builder: collapse the explicit `TableProxy<C, Name,
  Name, DefaultScope<...>, ContractToQC<C, Name>>` instantiation to
  `TableProxy<C, Name>`, since every argument matches TableProxy's
  default generics.

- `RawExpr` visitor / rewriter / folder arms renamed from `rawSql`
  to `rawExpr` to match the AST kind discriminant (`'raw-expr'`).
  Updates `RawExpr.accept` / `.rewrite` / `.fold` plus the two
  call sites in `@prisma-next/sql-orm-client`
  (`where-binding.ts`, `query-plan-aggregate.ts`) and the relevant
  test arm names.

- `RawCodecInferer` JSDoc rewritten as public-API documentation —
  explains the contract implementers fulfil and how the runtime
  consumes it, without linking to internal symbols.

- `RawSqlLiteral` JSDoc no longer calls out Date specifically; the
  rule is generic: anything outside the literal union is routed
  through `param(value, { codecId })`.

- `create-raw-sql.test.ts`: `stubAdapter` → `stubInferer`; test
  titles + comments use "inferer" terminology to match the renamed
  interface; "defence-in-depth" describe renamed to plain language.

- Drop a tautological test in `raw-expr.test.ts` that asserted
  `RawExpr.baseColumnRef` shares an error message with
  `AggregateExpr.count()` — the wording is not load-bearing.

Signed-off-by: Serhii Tatarintsev <[email protected]>
CI lint:casts reported +5 net new bare casts vs merge-base:
- 3 in relational-core/src/expression.ts (createRawSql factory)
- 1 in sql-builder/src/runtime/joined-tables-impl.ts (#addJoin)
- 1 in sql-builder/src/runtime/query-impl.ts (having())

Refactor each site to remove the cast without weakening typing:
- expression.ts: rewrite createRawSql to use values.forEach (eliminates
  the values[i] cast and preserves the defence-in-depth throw on
  undefined interpolations); move the builder into a RawSqlBuilderImpl
  class so the overloaded returns() signatures live next to the wider
  implementation signature (no per-call casts needed).
- joined-tables-impl.ts: drop the redundant 'fns as Functions<QC>' cast
  (createFunctions<QC>() already returns the exact type) and prune the
  now-unused Functions import.
- query-impl.ts: pass <QC> explicitly to createAggregateFunctions so its
  return type is AggregateFunctions<QC> without needing a cast.

Signed-off-by: Serhii Tatarintsev <[email protected]>
@SevInf
SevInf force-pushed the tml-2668-core-rawexpr-substrate-factory-primitives branch from 246880d to e3fee04 Compare May 29, 2026 15:22
@SevInf
SevInf merged commit ab6eaaa into main May 29, 2026
20 checks passed
@SevInf
SevInf deleted the tml-2668-core-rawexpr-substrate-factory-primitives branch May 29, 2026 15:33
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.

1 participant