Repository navigation
feat(sql-builder): type-level query builder prototype - #242
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdded queryOperationTypeImports support through emission, tooling, and family wiring; extended TypeMaps and SQL contract types with QueryOperationTypes; added pgvector query operation signatures; and introduced a new type-level SQL builder package with types, fixtures, and many compile-time tests. Changes
Sequence DiagramsequenceDiagram
participant Descriptors as Descriptors
participant Assembly as Assembly
participant Control as ControlInstance
participant Emitter as Emitter
participant Generated as GeneratedTypes
participant Builder as SQLBuilderTypes
Descriptors->>Assembly: provide descriptors (include types.queryOperationTypes?)
Assembly->>Control: return collected queryOperationTypeImports
Control->>Emitter: call emitContract(...) with queryOperationTypeImports
Emitter->>Emitter: merge & dedupe allImports (incl. queryOperationTypeImports)
Emitter->>Generated: emit "export type QueryOperationTypes = ..." and extend TypeMaps generic
Generated->>Builder: QueryOperationTypes become available in QueryContext for builder types
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
@prisma-next/runtime-executor
@prisma-next/sql-runtime
@prisma-next/extension-paradedb
@prisma-next/extension-pgvector
@prisma-next/postgres
@prisma-next/sql-orm-client
@prisma-next/contract-authoring
@prisma-next/contract-ts
@prisma-next/ids
@prisma-next/psl-parser
@prisma-next/cli
@prisma-next/emitter
@prisma-next/eslint-plugin
@prisma-next/migration-tools
@prisma-next/vite-plugin-contract-emit
@prisma-next/sql-contract
@prisma-next/sql-errors
@prisma-next/sql-operations
@prisma-next/sql-schema-ir
@prisma-next/sql-contract-psl
@prisma-next/sql-contract-ts
@prisma-next/sql-contract-emitter
@prisma-next/family-sql
@prisma-next/sql-kysely-lane
@prisma-next/sql-lane-query-builder
@prisma-next/sql-relational-core
@prisma-next/sql-lane-sql-builder-new
@prisma-next/sql-lane
@prisma-next/target-postgres
@prisma-next/adapter-postgres
@prisma-next/driver-postgres
@prisma-next/core-control-plane
@prisma-next/core-execution-plane
@prisma-next/config
@prisma-next/contract
@prisma-next/operations
@prisma-next/plan
@prisma-next/utils
commit: |
wmadden
left a comment
There was a problem hiding this comment.
Non-blocking concerns from local review
Two general concerns that aren't tied to a specific file:
NB-F04: No negative capability-gating tests
The tests prove lateralJoin and distinctOn work when capabilities are present, but no test verifies they're absent when capabilities are missing. A second contract fixture (e.g., contract-no-caps.ts) with sql.lateral: false and postgres.distinctOn: false, plus @ts-expect-error tests on the resulting types, would strengthen confidence in the gating mechanism.
NB-F07: Package naming — sql-builder-new
The -new suffix signals prototype/exploration. Before this stabilizes, the name should be resolved (merge with or replace query-builder, or give it a permanent name). The overlap with existing query-builder and sql-lane packages could confuse contributors.
See inline comments for file-specific concerns. All non-blocking — this is a clean, well-structured PR.
There was a problem hiding this comment.
Actionable comments posted: 8
🧹 Nitpick comments (4)
packages/2-sql/1-core/contract/src/types.ts (1)
219-219: Consider addingResolveQueryOperationTypesfor consistency.
ExtractCodecTypesandExtractOperationTypeshave correspondingResolveCodecTypes/ResolveOperationTypeshelpers (lines 221-227) that handle both contract extraction and explicit TypeMaps. The newExtractQueryOperationTypeslacks an equivalentResolveQueryOperationTypes.If query operation types will be used in contexts where TypeMaps may be passed explicitly (emitted workflow), a resolver helper would maintain API symmetry.
♻️ Optional: Add resolver helper
export type ResolveOperationTypes<TContract, TTypeMaps> = [TTypeMaps] extends [never] ? ExtractOperationTypes<TContract> : OperationTypesOf<TTypeMaps>; + +export type ResolveQueryOperationTypes<TContract, TTypeMaps> = [TTypeMaps] extends [never] + ? ExtractQueryOperationTypes<TContract> + : QueryOperationTypesOf<TTypeMaps>;🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/2-sql/1-core/contract/src/types.ts` at line 219, Add a resolver alias ResolveQueryOperationTypes to mirror the existing pattern used by ResolveCodecTypes/ResolveOperationTypes: it should accept either a contract or an explicit TypeMaps and resolve to the concrete query operation types by delegating to QueryOperationTypesOf plus ExtractTypeMapsFromContract when given a contract; implement ResolveQueryOperationTypes<T> as a conditional/alias that uses QueryOperationTypesOf<ExtractTypeMapsFromContract<T>> for contract inputs and returns QueryOperationTypesOf<T> when T is already TypeMaps, referencing the existing helper ExtractTypeMapsFromContract and the type QueryOperationTypesOf to locate where to implement it.packages/2-sql/4-lanes/sql-builder-new/src/index.ts (1)
1-4: Consider avoiding pure barrel re-exports.This file consists entirely of
export *statements, which the coding guidelines discourage: "Never createindex.tsfiles that only containexport * from './other-module'."For a package entrypoint, consider either:
- Using explicit named exports to define a clear public API surface
- Having consumers import directly from submodules (e.g.,
import { Db } from '@prisma-next/sql-lane-sql-builder-new/builders')Given this is a prototype package under active development, this can be addressed in a follow-up.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/2-sql/4-lanes/sql-builder-new/src/index.ts` around lines 1 - 4, This entrypoint currently re-exports everything via four `export * from` statements (from './builders', './expression', './resolve', './scope'); replace the pure barrel with an explicit public API by exporting only the intended symbols (e.g., export { Builder, Db, createQuery } from './builders'; export { Expr, Literal } from './expression'; export { resolveSomething } from './resolve'; export { Scope } from './scope') or alternatively remove this index and require consumers to import directly from the submodules; update the exports in index.ts to list the named exports you want to expose instead of using `export *`.packages/2-sql/3-tooling/emitter/test/emitter-hook.generation.basic.test.ts (1)
858-885: Move this new query-operation test into a split test file.This file is already far beyond the 500-line ceiling; adding more cases here makes navigation and maintenance harder. Please place this block in a focused split (for example,
emitter-hook.generation.query-operations.test.ts).As per coding guidelines: "
**/*.test.ts: Keep test files under 500 lines to maintain readability and navigability. If a test file exceeds this limit, it should be split into multiple files."🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/2-sql/3-tooling/emitter/test/emitter-hook.generation.basic.test.ts` around lines 858 - 885, The new test case that verifies query operation type imports should be moved out of the large emitter-hook.generation.basic.test.ts into a focused split file (suggested name: emitter-hook.generation.query-operations.test.ts); copy the test block that uses createContractIR, queryOperationTypeImports, calls sqlTargetFamilyHook.generateContractTypes and asserts on the resulting types variable, and preserve any necessary imports/mocks (e.g., createContractIR, sqlTargetFamilyHook, testHashes, expect) and test setup so it runs independently; ensure the new file is added to the test suite and the original file no longer contains the moved test case.packages/2-sql/4-lanes/sql-builder-new/test/playground/joins.test-d.ts (1)
16-17: Add a reason to@ts-expect-errorannotation.Per coding guidelines,
@ts-expect-errorshould include a short reason explaining why the error is expected.📝 Suggested fix
- // `@ts-expect-error` f.id is not available without a namespace + // `@ts-expect-error`: conflicting column 'id' evicted from top-level scope; must use namespace .select((f) => ({ id: f.id, title: f.posts.title }))🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/2-sql/4-lanes/sql-builder-new/test/playground/joins.test-d.ts` around lines 16 - 17, Add a short reason to the `@ts-expect-error` comment above the .select((f) => ({ id: f.id, title: f.posts.title })) call explaining why the error is expected (e.g., "f.id not available without namespace" or similar); update the comment that precedes the select lambda so it documents that f.id is intentionally inaccessible while f.posts.title is used.
🤖 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/2-sql/4-lanes/sql-builder-new/src/builders.ts`:
- Line 148: When implementing TableProxy.as<NewAlias>, rebind the proxy's scope
so callbacks see the new alias key instead of the old table name: replace the
fourth generic type on the returned TableProxy from AvailableScope to a mapped
type that removes the original Name key and adds NewAlias with the same value
(e.g. use a utility type like RebindScope<AvailableScope, Name, NewAlias> or an
inline mapped type that copies all keys except Name and adds NewAlias:
AvailableScope & { [K in NewAlias]: AvailableScope[Name] } with Name excluded).
Update the as<NewAlias> signature to return TableProxy<C, Name, NewAlias,
RebindScope<AvailableScope, Name, NewAlias>> (and add the RebindScope type) so
db.users.as('u') types callbacks as f.u.* instead of f.users.*.
- Around line 183-192: The overloads for WithPagination.limit and .offset
currently accept Expression<ScopeField> which allows non-numeric types;
add/apply an integer codec type (e.g. create or reuse a IntegerCodecType
analogous to BooleanCodecType) and constrain the callback signatures to return
Expression<ScopeField, IntegerCodecType> (or the project’s equivalent generic
form) so the callbacks passed to limit(...) and offset(...) can only produce
integer-compatible expressions; update the two method overloads for limit and
offset in the WithPagination interface and any related type aliases (FieldProxy,
Functions) references to use that IntegerCodecType.
- Around line 101-117: The builder must prevent use of aggregates unless the
query is grouped and revalidate selected fields when groupBy changes: make
QueryContext carry a flag (e.g., allowAggregates or isGrouped) and update the
AggregateFunctions type to be conditional on that flag so the WithSelect.select
overload that accepts (fields, fns: AggregateFunctions<QC>) only exposes
aggregate helpers when QC.isGrouped is true; modify groupBy(...) so it returns a
new QueryContext with isGrouped=true and re-evaluates the current row type (the
SelectQuery/WithFields/WithField/ExtractScopeFields result) to ensure any
non-aggregated selected columns are either present in the groupBy list or cause
a type/error, and adjust the select overload resolution to reject mixing plain
column selects with aggregate uses when QC.isGrouped is false.
In `@packages/2-sql/4-lanes/sql-builder-new/src/expression.ts`:
- Around line 113-132: The scalar IN/NOT IN overloads accept
Subquery<Record<string,...>> allowing multi-column subqueries; change the
signature to require a single column key by adding a key generic (e.g., Key
extends string) and typing the subquery as Subquery<Record<Key, { codecId:
CodecId; nullable: boolean }>> so the subquery can only have one selected
column; apply this change to both overloads of in and notIn (referencing the
in/notIn overloads, Expression, Subquery, and the CodecId generic).
- Around line 143-148: sum() and avg() currently return Expression<{ codecId:
T['codecId']; nullable: true }>, which incorrectly reuses the input codec;
instead change their return codecs to database-specific types (like PostgreSQL
sum/int -> 'pg/int8@1' and avg/int -> 'pg/numeric@1') by mapping input
ScopeField codecId -> result codecId using the project's DB codec mapping
utility (the same pattern used for count()'s explicit codec and leaving
min()/max() as identity). Update the implementations of sum and avg in
expression.ts to look up the target codec based on the input T.codecId and
current DB target and return Expression<{ codecId: MAPPED_CODEC_ID; nullable:
true }>, ensuring numeric widenings for integer sums and numeric averages are
handled per-database.
In `@packages/2-sql/4-lanes/sql-builder-new/STATUS.md`:
- Around line 12-24: Update the STATUS.md entries for LATERAL and DISTINCT ON to
indicate they are capability-gated; specifically, modify the lines that list
"LATERAL, LATERAL LEFT" and "DISTINCT / DISTINCT ON (expr, ...)" so they read
something like "LATERAL (when capability enabled)" and "DISTINCT / DISTINCT ON
(expr, ...) (when capability enabled)" to avoid implying universal
availability—search for the exact strings "LATERAL" and "DISTINCT ON" in the
document and append the parenthetical qualifier where they appear.
In `@packages/2-sql/4-lanes/sql-builder-new/test/playground/exists-in.test-d.ts`:
- Around line 85-102: Add short explanatory reasons to each bare
`@ts-expect-error` in the tests to document the invariant being validated: update
the three occurrences before the fns.in calls (the single-column subquery, the
multi-column subquery with different types, and the literal-array vs
int-expression case) to include a one-line reason like "@ts-expect-error —
reason: <short explanation>" so future readers know why fns.in(f.users.id,
db.posts.select(...)) and fns.in(f.users.id, ['hello','world']) are expected to
fail; target the test blocks that call db.users.select('id') and use .where((f,
fns) => fns.in(...)) to locate and change each directive.
In `@packages/2-sql/4-lanes/sql-builder-new/vitest.config.ts`:
- Line 5: The Vitest config's include array currently only matches
'test/**/*.test.ts' and therefore excludes type-only tests with the '.test-d.ts'
extension; update the include entry in vitest.config.ts (the include symbol) to
also match those files — e.g. replace the single glob with ['test/**/*.test.ts',
'test/**/*.test-d.ts'] or a combined glob like 'test/**/*.test.{ts,d.ts}' so
both .test.ts and .test-d.ts files are discovered.
---
Nitpick comments:
In `@packages/2-sql/1-core/contract/src/types.ts`:
- Line 219: Add a resolver alias ResolveQueryOperationTypes to mirror the
existing pattern used by ResolveCodecTypes/ResolveOperationTypes: it should
accept either a contract or an explicit TypeMaps and resolve to the concrete
query operation types by delegating to QueryOperationTypesOf plus
ExtractTypeMapsFromContract when given a contract; implement
ResolveQueryOperationTypes<T> as a conditional/alias that uses
QueryOperationTypesOf<ExtractTypeMapsFromContract<T>> for contract inputs and
returns QueryOperationTypesOf<T> when T is already TypeMaps, referencing the
existing helper ExtractTypeMapsFromContract and the type QueryOperationTypesOf
to locate where to implement it.
In `@packages/2-sql/3-tooling/emitter/test/emitter-hook.generation.basic.test.ts`:
- Around line 858-885: The new test case that verifies query operation type
imports should be moved out of the large emitter-hook.generation.basic.test.ts
into a focused split file (suggested name:
emitter-hook.generation.query-operations.test.ts); copy the test block that uses
createContractIR, queryOperationTypeImports, calls
sqlTargetFamilyHook.generateContractTypes and asserts on the resulting types
variable, and preserve any necessary imports/mocks (e.g., createContractIR,
sqlTargetFamilyHook, testHashes, expect) and test setup so it runs
independently; ensure the new file is added to the test suite and the original
file no longer contains the moved test case.
In `@packages/2-sql/4-lanes/sql-builder-new/src/index.ts`:
- Around line 1-4: This entrypoint currently re-exports everything via four
`export * from` statements (from './builders', './expression', './resolve',
'./scope'); replace the pure barrel with an explicit public API by exporting
only the intended symbols (e.g., export { Builder, Db, createQuery } from
'./builders'; export { Expr, Literal } from './expression'; export {
resolveSomething } from './resolve'; export { Scope } from './scope') or
alternatively remove this index and require consumers to import directly from
the submodules; update the exports in index.ts to list the named exports you
want to expose instead of using `export *`.
In `@packages/2-sql/4-lanes/sql-builder-new/test/playground/joins.test-d.ts`:
- Around line 16-17: Add a short reason to the `@ts-expect-error` comment above
the .select((f) => ({ id: f.id, title: f.posts.title })) call explaining why the
error is expected (e.g., "f.id not available without namespace" or similar);
update the comment that precedes the select lambda so it documents that f.id is
intentionally inaccessible while f.posts.title is used.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: 8285e157-d589-494b-9e9b-4f0c2ea3161a
⛔ Files ignored due to path filters (3)
packages/2-sql/4-lanes/sql-builder-new/test/fixtures/generated/contract.d.tsis excluded by!**/generated/**packages/2-sql/4-lanes/sql-builder-new/test/fixtures/generated/contract.jsonis excluded by!**/generated/**pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (38)
packages/1-framework/1-core/migration/control-plane/src/emission/emit.tspackages/1-framework/1-core/migration/control-plane/src/emission/types.tspackages/1-framework/1-core/shared/contract/src/types.tspackages/2-sql/1-core/contract/src/exports/types.tspackages/2-sql/1-core/contract/src/types.tspackages/2-sql/3-tooling/emitter/src/index.tspackages/2-sql/3-tooling/emitter/test/emitter-hook.generation.basic.test.tspackages/2-sql/3-tooling/family/src/core/assembly.tspackages/2-sql/3-tooling/family/src/core/control-instance.tspackages/2-sql/3-tooling/family/src/exports/test-utils.tspackages/2-sql/4-lanes/sql-builder-new/README.mdpackages/2-sql/4-lanes/sql-builder-new/STATUS.mdpackages/2-sql/4-lanes/sql-builder-new/package.jsonpackages/2-sql/4-lanes/sql-builder-new/src/builders.tspackages/2-sql/4-lanes/sql-builder-new/src/expression.tspackages/2-sql/4-lanes/sql-builder-new/src/index.tspackages/2-sql/4-lanes/sql-builder-new/src/resolve.tspackages/2-sql/4-lanes/sql-builder-new/src/scope.tspackages/2-sql/4-lanes/sql-builder-new/test/fixtures/contract.tspackages/2-sql/4-lanes/sql-builder-new/test/fixtures/prisma-next.config.tspackages/2-sql/4-lanes/sql-builder-new/test/playground/distinct.test-d.tspackages/2-sql/4-lanes/sql-builder-new/test/playground/exists-in.test-d.tspackages/2-sql/4-lanes/sql-builder-new/test/playground/extension-functions.test-d.tspackages/2-sql/4-lanes/sql-builder-new/test/playground/group-by.test-d.tspackages/2-sql/4-lanes/sql-builder-new/test/playground/joins.test-d.tspackages/2-sql/4-lanes/sql-builder-new/test/playground/lateral-joins.test-d.tspackages/2-sql/4-lanes/sql-builder-new/test/playground/order-by.test-d.tspackages/2-sql/4-lanes/sql-builder-new/test/playground/pagination.test-d.tspackages/2-sql/4-lanes/sql-builder-new/test/playground/preamble.tspackages/2-sql/4-lanes/sql-builder-new/test/playground/select.test-d.tspackages/2-sql/4-lanes/sql-builder-new/tsconfig.jsonpackages/2-sql/4-lanes/sql-builder-new/tsconfig.prod.jsonpackages/2-sql/4-lanes/sql-builder-new/tsdown.config.tspackages/2-sql/4-lanes/sql-builder-new/vitest.config.tspackages/3-extensions/pgvector/src/core/descriptor-meta.tspackages/3-extensions/pgvector/src/exports/operation-types.tspackages/3-extensions/pgvector/src/types/operation-types.tstest/integration/test/authoring/parity/pgvector-named-type/expected.contract.json
wmadden
left a comment
There was a problem hiding this comment.
A few small comments. Please follow the exports/ vs src/ pattern present in other packages
- Align tsconfig.json and vitest.config.ts with sibling package patterns - Add reasons to bare @ts-expect-error directives - Note capability-gated features in STATUS.md - Replace star re-exports with curated public API in index.ts - Add exports/ directory following established package pattern
There was a problem hiding this comment.
🧹 Nitpick comments (1)
packages/2-sql/4-lanes/sql-builder-new/src/scope.ts (1)
7-7: LocalCodecTypesBaseis more restrictive than contract constraint.The local definition requires both
inputandoutput, whileTypeMapsin the contract only constrains{ output: unknown }. This is correct for the builder's needs (sinceExpressionOrValueusesinputfor raw value acceptance), but worth noting the intentional divergence.If a future consumer creates a TypeMaps with codec types lacking
input, theQueryContextwon't accept them. Consider documenting this requirement or eventually exporting a shared constraint from the contract.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/2-sql/4-lanes/sql-builder-new/src/scope.ts` at line 7, The local type CodecTypesBase currently requires both input and output whereas the upstream contract's TypeMaps only requires output, causing QueryContext (and ExpressionOrValue) to reject TypeMaps lacking an input field; update the code by either (A) adding a clear JSDoc comment above CodecTypesBase and QueryContext explaining the intentional stricter requirement (that codec entries must provide an input type) so callers know to include input, or (B) better yet, import/export a shared constraint from the contract (a common type like TypeMapsWithInput) and use that instead of the local CodecTypesBase so the contract and builder share the same constraint; reference CodecTypesBase, TypeMaps, QueryContext, and ExpressionOrValue when making the change.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@packages/2-sql/4-lanes/sql-builder-new/src/scope.ts`:
- Line 7: The local type CodecTypesBase currently requires both input and output
whereas the upstream contract's TypeMaps only requires output, causing
QueryContext (and ExpressionOrValue) to reject TypeMaps lacking an input field;
update the code by either (A) adding a clear JSDoc comment above CodecTypesBase
and QueryContext explaining the intentional stricter requirement (that codec
entries must provide an input type) so callers know to include input, or (B)
better yet, import/export a shared constraint from the contract (a common type
like TypeMapsWithInput) and use that instead of the local CodecTypesBase so the
contract and builder share the same constraint; reference CodecTypesBase,
TypeMaps, QueryContext, and ExpressionOrValue when making the change.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: e88cc191-4223-4b2b-9b64-a67d2bb71569
📒 Files selected for processing (5)
packages/2-sql/1-core/contract/src/exports/types.tspackages/2-sql/1-core/contract/src/types.tspackages/2-sql/4-lanes/sql-builder-new/src/expression.tspackages/2-sql/4-lanes/sql-builder-new/src/scope.tspackages/3-extensions/pgvector/src/types/operation-types.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- packages/2-sql/1-core/contract/src/exports/types.ts
- packages/3-extensions/pgvector/src/types/operation-types.ts
- Align tsconfig.json and vitest.config.ts with sibling package patterns - Add reasons to bare @ts-expect-error directives - Note capability-gated features in STATUS.md - Replace star re-exports with curated public API in index.ts - Add exports/ directory following established package pattern
6d72292 to
3fa4603
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
packages/2-sql/1-core/contract/src/types.ts (1)
228-236: Consider addingResolveQueryOperationTypesfor completeness.The file defines
ResolveCodecTypesandResolveOperationTypes(lines 230-236) to handle both emitted and no-emit workflows. A correspondingResolveQueryOperationTypeshelper would maintain consistency for consumers who need to resolve query operation types from either source.💡 Suggested addition
export type ResolveOperationTypes<TContract, TTypeMaps> = [TTypeMaps] extends [never] ? ExtractOperationTypes<TContract> : OperationTypesOf<TTypeMaps>; + +export type ResolveQueryOperationTypes<TContract, TTypeMaps> = [TTypeMaps] extends [never] + ? ExtractQueryOperationTypes<TContract> + : QueryOperationTypesOf<TTypeMaps>;🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/2-sql/1-core/contract/src/types.ts` around lines 228 - 236, Add a new type alias ResolveQueryOperationTypes to mirror ResolveCodecTypes/ResolveOperationTypes: when TTypeMaps is never, resolve to ExtractQueryOperationTypes<TContract>, otherwise resolve to QueryOperationTypesOf<TTypeMaps>; place it alongside ResolveCodecTypes and ResolveOperationTypes and reference ExtractQueryOperationTypes, QueryOperationTypesOf, and the same TContract/TTypeMaps generics so consumers can resolve query operation types from either emitted TypeMaps or the contract directly.
🤖 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/2-sql/4-lanes/sql-builder-new/test/fixtures/contract.ts`:
- Around line 60-66: The 1:1 relation declared as User.profile is not enforced
because profiles.user_id is only non-nullable but not unique; update the
profiles table definition (table('profiles')) to enforce uniqueness on user_id
(e.g., add a unique constraint/index on the 'user_id' column or make it part of
the primary key) so that profiles.user_id is uniquely constrained and truly
enforces a 1:1 relationship with User.profile.
---
Nitpick comments:
In `@packages/2-sql/1-core/contract/src/types.ts`:
- Around line 228-236: Add a new type alias ResolveQueryOperationTypes to mirror
ResolveCodecTypes/ResolveOperationTypes: when TTypeMaps is never, resolve to
ExtractQueryOperationTypes<TContract>, otherwise resolve to
QueryOperationTypesOf<TTypeMaps>; place it alongside ResolveCodecTypes and
ResolveOperationTypes and reference ExtractQueryOperationTypes,
QueryOperationTypesOf, and the same TContract/TTypeMaps generics so consumers
can resolve query operation types from either emitted TypeMaps or the contract
directly.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: f9e88533-a691-4e9a-9658-72acd77d7c4a
⛔ Files ignored due to path filters (3)
packages/2-sql/4-lanes/sql-builder-new/test/fixtures/generated/contract.d.tsis excluded by!**/generated/**packages/2-sql/4-lanes/sql-builder-new/test/fixtures/generated/contract.jsonis excluded by!**/generated/**pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (39)
packages/1-framework/1-core/migration/control-plane/src/emission/emit.tspackages/1-framework/1-core/migration/control-plane/src/emission/types.tspackages/1-framework/1-core/shared/contract/src/types.tspackages/2-sql/1-core/contract/src/exports/types.tspackages/2-sql/1-core/contract/src/types.tspackages/2-sql/3-tooling/emitter/src/index.tspackages/2-sql/3-tooling/emitter/test/emitter-hook.generation.basic.test.tspackages/2-sql/3-tooling/family/src/core/assembly.tspackages/2-sql/3-tooling/family/src/core/control-instance.tspackages/2-sql/3-tooling/family/src/exports/test-utils.tspackages/2-sql/4-lanes/sql-builder-new/README.mdpackages/2-sql/4-lanes/sql-builder-new/STATUS.mdpackages/2-sql/4-lanes/sql-builder-new/package.jsonpackages/2-sql/4-lanes/sql-builder-new/src/builders.tspackages/2-sql/4-lanes/sql-builder-new/src/exports/types.tspackages/2-sql/4-lanes/sql-builder-new/src/expression.tspackages/2-sql/4-lanes/sql-builder-new/src/index.tspackages/2-sql/4-lanes/sql-builder-new/src/resolve.tspackages/2-sql/4-lanes/sql-builder-new/src/scope.tspackages/2-sql/4-lanes/sql-builder-new/test/fixtures/contract.tspackages/2-sql/4-lanes/sql-builder-new/test/fixtures/prisma-next.config.tspackages/2-sql/4-lanes/sql-builder-new/test/playground/distinct.test-d.tspackages/2-sql/4-lanes/sql-builder-new/test/playground/exists-in.test-d.tspackages/2-sql/4-lanes/sql-builder-new/test/playground/extension-functions.test-d.tspackages/2-sql/4-lanes/sql-builder-new/test/playground/group-by.test-d.tspackages/2-sql/4-lanes/sql-builder-new/test/playground/joins.test-d.tspackages/2-sql/4-lanes/sql-builder-new/test/playground/lateral-joins.test-d.tspackages/2-sql/4-lanes/sql-builder-new/test/playground/order-by.test-d.tspackages/2-sql/4-lanes/sql-builder-new/test/playground/pagination.test-d.tspackages/2-sql/4-lanes/sql-builder-new/test/playground/preamble.tspackages/2-sql/4-lanes/sql-builder-new/test/playground/select.test-d.tspackages/2-sql/4-lanes/sql-builder-new/tsconfig.jsonpackages/2-sql/4-lanes/sql-builder-new/tsconfig.prod.jsonpackages/2-sql/4-lanes/sql-builder-new/tsdown.config.tspackages/2-sql/4-lanes/sql-builder-new/vitest.config.tspackages/3-extensions/pgvector/src/core/descriptor-meta.tspackages/3-extensions/pgvector/src/exports/operation-types.tspackages/3-extensions/pgvector/src/types/operation-types.tstest/integration/test/authoring/parity/pgvector-named-type/expected.contract.json
✅ Files skipped from review due to trivial changes (20)
- packages/2-sql/4-lanes/sql-builder-new/tsconfig.prod.json
- packages/2-sql/4-lanes/sql-builder-new/test/playground/preamble.ts
- packages/2-sql/4-lanes/sql-builder-new/tsconfig.json
- packages/2-sql/4-lanes/sql-builder-new/tsdown.config.ts
- packages/1-framework/1-core/shared/contract/src/types.ts
- packages/1-framework/1-core/migration/control-plane/src/emission/types.ts
- packages/2-sql/4-lanes/sql-builder-new/test/playground/lateral-joins.test-d.ts
- packages/2-sql/4-lanes/sql-builder-new/README.md
- packages/2-sql/4-lanes/sql-builder-new/src/resolve.ts
- packages/3-extensions/pgvector/src/types/operation-types.ts
- packages/2-sql/4-lanes/sql-builder-new/src/index.ts
- packages/2-sql/4-lanes/sql-builder-new/test/playground/order-by.test-d.ts
- packages/2-sql/4-lanes/sql-builder-new/vitest.config.ts
- packages/2-sql/4-lanes/sql-builder-new/src/exports/types.ts
- packages/2-sql/4-lanes/sql-builder-new/test/playground/pagination.test-d.ts
- packages/2-sql/4-lanes/sql-builder-new/test/playground/distinct.test-d.ts
- packages/2-sql/4-lanes/sql-builder-new/package.json
- packages/2-sql/4-lanes/sql-builder-new/test/playground/exists-in.test-d.ts
- packages/2-sql/4-lanes/sql-builder-new/test/playground/joins.test-d.ts
- packages/2-sql/4-lanes/sql-builder-new/src/scope.ts
🚧 Files skipped from review as they are similar to previous changes (12)
- packages/2-sql/3-tooling/family/src/exports/test-utils.ts
- packages/2-sql/3-tooling/family/src/core/control-instance.ts
- packages/1-framework/1-core/migration/control-plane/src/emission/emit.ts
- packages/2-sql/1-core/contract/src/exports/types.ts
- packages/3-extensions/pgvector/src/exports/operation-types.ts
- packages/2-sql/4-lanes/sql-builder-new/test/fixtures/prisma-next.config.ts
- test/integration/test/authoring/parity/pgvector-named-type/expected.contract.json
- packages/3-extensions/pgvector/src/core/descriptor-meta.ts
- packages/2-sql/4-lanes/sql-builder-new/test/playground/extension-functions.test-d.ts
- packages/2-sql/3-tooling/emitter/src/index.ts
- packages/2-sql/4-lanes/sql-builder-new/STATUS.md
- packages/2-sql/4-lanes/sql-builder-new/src/builders.ts
- Align tsconfig.json and vitest.config.ts with sibling package patterns - Add reasons to bare @ts-expect-error directives - Note capability-gated features in STATUS.md - Replace star re-exports with curated public API in index.ts - Add exports/ directory following established package pattern
Add RebindScope utility type so that TableProxy.as('u') remaps the
scope namespace from the original table name to the new alias,
ensuring callbacks see f.u.* instead of f.users.*.
3fa4603 to
6a50d3a
Compare
closes TML-2072
Key snippet (new capability)
Intent
Introduce a type-level-only SQL query builder (
sql-builder-new) that validates the entire fluent SELECT API surface through TypeScript's type system — without any runtime code. Alongside it, thread a newQueryOperationTypesconcept through the contract emission pipeline so that extension functions (like pgvector'scosineDistance) are available as first-class typed functions in the builder.Change map
The story
Define the scope system — Introduce
Scope(topLevel + namespaces) to track which columns are accessible at each point in a query chain. When tables are joined, overlapping column names are evicted fromtopLevel, forcing namespace-qualified access (f.users.idinstead off.id). This prevents ambiguous column references at the type level.Build the expression and function system — Layer
Expression<ScopeField>as a branded type that carries codec identity and nullability. DefineFunctions(comparison, logical,exists,in) andAggregateFunctions(extends withcount/sum/avg/min/max). The split ensures aggregates are only available where SQL semantics allow them (SELECT/HAVING, not WHERE).Compose the builder interfaces — Chain
TableProxy→JoinedTables→SelectQuery→GroupedQuery, each progressively narrowing the available methods. Threeselectoverloads (column names, aliased expression, callback-returning-record) accumulate the row type additively.GroupedQueryreplaceswherewithhavingand exposes aggregate functions inorderBy.Apply capability gating — Use
CapabilityGated<Caps, Required, T>(conditional type) to makelateralJoinavailable only whensql.lateralis true anddistinctOnonly whenpostgres.distinctOnis true. This mirrors real database feature availability in the type system.Add the
Db<Contract>entry point — A mapped type that creates aTableProxyper table in the contract's storage, providing thedb.users,db.postsAPI surface.Thread
QueryOperationTypesthrough the emission pipeline — Introduce a newqueryOperationTypesslot inTypeMaps, a parallel extraction path in the assembly/emitter, and a concreteQueryOperationTypesexport incontract.d.ts. This enables extension functions to be typed with flat{ args, returns }signatures (vs the nested lane-specificOperationTypes).Wire pgvector as the first extension — Add
QueryOperationTypesto pgvector's descriptor metadata and definecosineDistancewith its flat signature, proving the extension function plumbing works end-to-end.Behavior changes & evidence
Adds a type-level SQL query builder with full SELECT pipeline: Introduces
Db<Contract>→TableProxy→SelectQuery→GroupedQuerysupporting FROM, SELECT (3 overloads), WHERE, JOIN (inner/outer-left/outer-right/outer-full), ORDER BY, GROUP BY, HAVING, LIMIT/OFFSET, DISTINCT, DISTINCT ON, and subqueries as join sources.sql-builderpackage had a different design; this is a ground-up rethink of the type-safe query builder API, validating the API shape purely through types before committing to a runtime implementation.expectTypeOf:@ts-expect-error)Scope merging evicts conflicting column names from top-level access: When two joined tables share a column name (e.g.,
id),MergeScopesremoves it fromtopLevel, producing a@ts-expect-errorif accessed without a namespace.MergeScopesusesOmitto remove overlapping keys@ts-expect-erroronf.idafter joinOuter joins make the appropriate side(s) nullable: Left outer → right side nullable, right outer → left side nullable, full outer → both nullable, outer lateral → lateral side nullable.
NullableScope/NullableScopeTablestring | nullassertions for outer join columns; test/playground/lateral-joins.test-d.ts (L21–L34) —string | nullfor outer lateralAggregate functions are only available in appropriate contexts:
count/sum/avg/min/maxare exposed in SELECT and HAVING callbacks (AggregateFunctions), but not in WHERE callbacks (Functionsonly).AggregateFunctionsextendsFunctions@ts-expect-erroronfns.count()in WHERELateral joins and DISTINCT ON are capability-gated:
lateralJoin/outerLateralJoinrequiresql.lateral: true;distinctOnrequirespostgres.distinctOn: true.CapabilityGated; applied in builders.ts (L124–L132, L243–L252)Adds
QueryOperationTypesto the contract type system and emission pipeline: A new parallel toOperationTypeswith flat{ args: ScopeField[], returns: ScopeField }signatures, threaded throughTypeMaps, assembly extraction, emitter codegen, and the emission control plane.OperationTypesare nested by lane and use different type shapes. The new builder needs flat, codec-ID-based signatures to derive typed extension functions generically.TypeMapsgains third param,QueryOperationTypesOf/ExtractQueryOperationTypesextractorsQueryOperationTypestype alias incontract.d.tsextractQueryOperationTypeImportscosineDistanceused in select, orderBy, and where with correct type inferencepgvector exports
QueryOperationTypeswithcosineDistance: Flat signature(vector, vector) → float8added alongside the existing nestedOperationTypes.Compatibility / migration / risk
TypeMapsgains a third generic parameter (TQueryOperationTypes), defaulting toRecord<string, never>. Existing code passing 2 type args continues to work unchanged.QueryOperationTypesincontract.d.ts. Existing contracts will getRecord<string, never>(no-op).sql-builder-newpackage has no runtime — it cannot break anything at execution time. Risk is limited to type-checking regressions in downstream consumers.Follow-ups / open questions
cosineDistance) is wired; other pgvector operations and future extensions needQueryOperationTypesentries.Non-goals / intentionally out of scope
Summary by CodeRabbit
New Features
Public Types
Tests
Documentation