Repository navigation
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:
📝 WalkthroughWalkthroughThis PR implements nested includes at depth ≥ 2 by refactoring include dispatch to detect complex descriptors anywhere in the include tree, adding recursive single-query decoding via decodeIncludePayload, and extending SQL plan generation to build nested aggregates for lateral and correlated strategies, with capability-driven unit and integration tests. ChangesNested includes at depth ≥ 2
🎯 4 (Complex) | ⏱️ ~60 minutes
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 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/extension-author-tools
@prisma-next/mongo-runtime
@prisma-next/family-mongo
@prisma-next/sql-runtime
@prisma-next/family-sql
@prisma-next/extension-arktype-json
@prisma-next/extension-cipherstash
@prisma-next/middleware-cache
@prisma-next/mongo
@prisma-next/extension-paradedb
@prisma-next/extension-pgvector
@prisma-next/extension-postgis
@prisma-next/postgres
@prisma-next/sql-orm-client
@prisma-next/sqlite
@prisma-next/target-mongo
@prisma-next/adapter-mongo
@prisma-next/driver-mongo
@prisma-next/contract
@prisma-next/utils
@prisma-next/config
@prisma-next/errors
@prisma-next/framework-components
@prisma-next/operations
@prisma-next/ts-render
@prisma-next/contract-authoring
@prisma-next/ids
@prisma-next/psl-parser
@prisma-next/psl-printer
@prisma-next/cli
@prisma-next/cli-telemetry
@prisma-next/emitter
@prisma-next/migration-tools
prisma-next
@prisma-next/vite-plugin-contract-emit
@prisma-next/mongo-codec
@prisma-next/mongo-contract
@prisma-next/mongo-value
@prisma-next/mongo-contract-psl
@prisma-next/mongo-contract-ts
@prisma-next/mongo-emitter
@prisma-next/mongo-schema-ir
@prisma-next/mongo-query-ast
@prisma-next/mongo-orm
@prisma-next/mongo-query-builder
@prisma-next/mongo-lowering
@prisma-next/mongo-wire
@prisma-next/sql-contract
@prisma-next/sql-errors
@prisma-next/sql-operations
@prisma-next/sql-schema-ir
@prisma-next/sql-contract-psl
@prisma-next/sql-contract-ts
@prisma-next/sql-contract-emitter
@prisma-next/sql-lane-query-builder
@prisma-next/sql-relational-core
@prisma-next/sql-builder
@prisma-next/target-postgres
@prisma-next/target-sqlite
@prisma-next/adapter-postgres
@prisma-next/adapter-sqlite
@prisma-next/driver-postgres
@prisma-next/driver-sqlite
commit: |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
packages/3-extensions/sql-orm-client/test/collection-dispatch.test.ts (1)
76-655: ⚖️ Poor tradeoffConsider splitting this test file to stay under the 500-line guideline.
The file is now 655 lines, which exceeds the 500-line soft guideline by 155 lines. While this isn't a blocker, consider splitting the dispatch tests into multiple files organized by feature area (e.g.,
collection-dispatch.single-query.test.ts,collection-dispatch.multi-query.test.ts,collection-dispatch.nested.test.ts) to improve navigability and align with the repo's test organization conventions.🤖 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/sql-orm-client/test/collection-dispatch.test.ts` around lines 76 - 655, The test file collection-dispatch.test.ts is over the 500-line guideline; split the large describe('collection-dispatch') suite into smaller, focused test files (for example: collection-dispatch.single-query.test.ts, collection-dispatch.multi-query.test.ts, collection-dispatch.nested.test.ts) by grouping related tests that exercise dispatchCollectionRows and stitchIncludes (e.g., single-query path tests that reference withSingleQueryCapabilities/getTestContract, multi-query path tests that reference withCapabilities/createCollectionFor, and nested include/regression guards that reference withEmittedSqlCapabilities). Move the corresponding it blocks (including tests that assert runtime.executions and include parsing/mapping behavior) into the new files and keep helper imports (createCollectionFor, dispatchCollectionRows, stitchIncludes, addConnection, createMockRuntime, etc.) at the top of each new file so each new test file remains self-contained and under 500 lines.packages/3-extensions/sql-orm-client/test/integration/nested-includes-helpers.ts (1)
26-35: 💤 Low valueConsider double casts for test fixture modifications.
The single casts on lines 32-33 could be strengthened to double casts (
as unknown as TestContractandas unknown as ExecutionContext<TestContract>) to align with the test code guideline for type assertions in test utilities. While these aren't traditional mocks or dynamic proxies, using double casts would make the type override more explicit and consistent with the repo's test patterns.♻️ Optional refactor for consistency
- const contract = { ...base, capabilities } as TestContract; - const context = { ...getTestContext(), contract } as ExecutionContext<TestContract>; + const contract = { ...base, capabilities } as unknown as TestContract; + const context = { ...getTestContext(), contract } as unknown as ExecutionContext<TestContract>;🤖 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/sql-orm-client/test/integration/nested-includes-helpers.ts` around lines 26 - 35, The test helper uses single TypeScript casts for modifying test fixtures (contract and context); update the casts to the repo's preferred double-cast pattern by changing the assignments that create contract and context to use "as unknown as TestContract" for contract (created from getTestContract() spread plus capabilities) and "as unknown as ExecutionContext<TestContract>" for context (created from getTestContext() spread plus contract) so the Collection instantiation still receives the same runtime/context but with the stronger double-cast type assertions on contract and context.
🤖 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/3-extensions/sql-orm-client/test/integration/nested-includes-strategy.test.ts`:
- Line 365: The test suite name in the describe call currently includes a
transient task ID ("TML-2595"); rename the describe label string in the file's
describe('coexistence with TML-2595 (scalar/combine still on multi-query)', ...)
to a stable, descriptive name without the task ID (for example "coexistence with
scalar/combine on multi-query" or "coexistence: scalar/combine on multi-query")
so the test name no longer references transient project artifacts; update only
the string argument to the describe invocation in
nested-includes-strategy.test.ts (leave the describe block and its tests
unchanged).
---
Nitpick comments:
In `@packages/3-extensions/sql-orm-client/test/collection-dispatch.test.ts`:
- Around line 76-655: The test file collection-dispatch.test.ts is over the
500-line guideline; split the large describe('collection-dispatch') suite into
smaller, focused test files (for example:
collection-dispatch.single-query.test.ts,
collection-dispatch.multi-query.test.ts, collection-dispatch.nested.test.ts) by
grouping related tests that exercise dispatchCollectionRows and stitchIncludes
(e.g., single-query path tests that reference
withSingleQueryCapabilities/getTestContract, multi-query path tests that
reference withCapabilities/createCollectionFor, and nested include/regression
guards that reference withEmittedSqlCapabilities). Move the corresponding it
blocks (including tests that assert runtime.executions and include
parsing/mapping behavior) into the new files and keep helper imports
(createCollectionFor, dispatchCollectionRows, stitchIncludes, addConnection,
createMockRuntime, etc.) at the top of each new file so each new test file
remains self-contained and under 500 lines.
In
`@packages/3-extensions/sql-orm-client/test/integration/nested-includes-helpers.ts`:
- Around line 26-35: The test helper uses single TypeScript casts for modifying
test fixtures (contract and context); update the casts to the repo's preferred
double-cast pattern by changing the assignments that create contract and context
to use "as unknown as TestContract" for contract (created from getTestContract()
spread plus capabilities) and "as unknown as ExecutionContext<TestContract>" for
context (created from getTestContext() spread plus contract) so the Collection
instantiation still receives the same runtime/context but with the stronger
double-cast type assertions on contract and context.
🪄 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: 156bca44-9cb6-480e-a5d4-d420627c1216
📒 Files selected for processing (8)
packages/3-extensions/sql-orm-client/src/collection-dispatch.tspackages/3-extensions/sql-orm-client/src/query-plan-select.tspackages/3-extensions/sql-orm-client/test/collection-dispatch.test.tspackages/3-extensions/sql-orm-client/test/integration/include.test.tspackages/3-extensions/sql-orm-client/test/integration/nested-includes-helpers.tspackages/3-extensions/sql-orm-client/test/integration/nested-includes-refinements.test.tspackages/3-extensions/sql-orm-client/test/integration/nested-includes-strategy.test.tspackages/3-extensions/sql-orm-client/test/integration/nested-includes.test.ts
…e rejection (PR #555 review) Apply both findings from the code review of PR #555 / TML-2594. F01: route non-leaf includes carrying `distinct()` to multi-query. Under the single-query strategies the child SELECT carries nested JSON aggregate columns, and `SELECT DISTINCT` over those fails on Postgres (`json` has no equality operator). The multi-query stitcher applies distinct to scalar-only rows before grandchildren are joined, which is the semantically correct behavior we preserve. `distinctOn` is intentionally excluded -- Postgres only compares the `ON (...)` expressions for equality. F02: make `compileSelectWithIncludeStrategy` reject scalar/combine descriptors at every depth, not just the top level. The dispatch path already gates these via `hasComplexIncludeDescriptors` recursively, but the planner is an exported helper called directly by tests and rich-plan callers, so it must enforce the same invariant or a nested `count()` inside a row include would silently produce a malformed plan instead of failing fast at the boundary. Tests: - query-plan-select.test.ts: add nested scalar + nested combine rejection cases mirroring the existing top-level rejection test. - nested-includes-strategy.test.ts: add the reviewers exact regression query under LATERAL_CAPABILITIES, the same shape under CORRELATED_CAPABILITIES, and a depth-2 recursive case.
…tural ScalarOrCombineIncludeDescriptors Apply the architect-review typology note from PR #555: `Complex` is a fuzzy qualifier, and the actual distinction the gate makes is structural (scalar reducer / combine() descriptor, regardless of where it sits in the include tree). Rename both parallel predicates -- the dispatch-side `hasComplexIncludeDescriptors` and the planner-side `hasScalarOrCombineIncludeAnywhere` -- to a single shared name `hasScalarOrCombineIncludeDescriptors`. Same name on both layers makes the parallel enforcement explicit; the boundary between dispatch policy and planner validity is preserved by their separate locations. Update inline comments in both source files and in the strategy / query-plan-select tests that referenced the old name. No behavior change.
There was a problem hiding this comment.
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/sql-orm-client/src/query-plan-select.ts (1)
547-578:⚠️ Potential issue | 🟠 Major | ⚡ Quick winMirror the non-leaf
distinct()gate in the exported planner.
dispatchWithIncludeStrategy()now routes non-leafdistinct()includes to multi-query, butcompileSelectWithIncludeStrategy()still accepts the same shape and can build a single-query plan directly. Because this helper is exported, direct callers can still hit the invalidSELECT DISTINCT ..., <nested json aggregate>path that this PR is trying to avoid.Suggested fix
+function hasNonLeafIncludeWithDistinct(includes: readonly IncludeExpr[]): boolean { + return includes.some( + (include) => + ((include.nested.distinct?.length ?? 0) > 0 && + include.nested.includes.length > 0) || + hasNonLeafIncludeWithDistinct(include.nested.includes), + ); +} + export function compileSelectWithIncludeStrategy( contract: Contract<SqlStorage>, tableName: string, state: CollectionState, strategy: 'lateral' | 'correlated', modelName?: string, ): SqlQueryPlan<Record<string, unknown>> { if (hasScalarOrCombineIncludeAnywhere(state.includes)) { throw new Error( 'single-query include strategy does not support scalar include selectors or combine()', ); } + if (hasNonLeafIncludeWithDistinct(state.includes)) { + throw new Error( + 'single-query include strategy does not support non-leaf distinct() includes', + ); + }🤖 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/sql-orm-client/src/query-plan-select.ts` around lines 547 - 578, The exported planner compileSelectWithIncludeStrategy can still build invalid single-query plans when a non-leaf distinct() appears in nested includes; mirror the dispatchWithIncludeStrategy behavior by rejecting any include that sets distinct on a non-leaf (i.e., distinct === true and include.nested.includes is non-empty). Add a check (either a new helper like hasNonLeafDistinctIncludeAnywhere or extend hasScalarOrCombineIncludeAnywhere) and throw a clear error inside compileSelectWithIncludeStrategy (similar to the existing scalar/combine check) so callers cannot produce a SELECT DISTINCT with nested JSON aggregates.
🤖 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/sql-orm-client/src/query-plan-select.ts`:
- Around line 547-578: The exported planner compileSelectWithIncludeStrategy can
still build invalid single-query plans when a non-leaf distinct() appears in
nested includes; mirror the dispatchWithIncludeStrategy behavior by rejecting
any include that sets distinct on a non-leaf (i.e., distinct === true and
include.nested.includes is non-empty). Add a check (either a new helper like
hasNonLeafDistinctIncludeAnywhere or extend hasScalarOrCombineIncludeAnywhere)
and throw a clear error inside compileSelectWithIncludeStrategy (similar to the
existing scalar/combine check) so callers cannot produce a SELECT DISTINCT with
nested JSON aggregates.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: e88b7d2d-a6d8-48a0-a1d2-b75a6c51391e
📒 Files selected for processing (4)
packages/3-extensions/sql-orm-client/src/collection-dispatch.tspackages/3-extensions/sql-orm-client/src/query-plan-select.tspackages/3-extensions/sql-orm-client/test/integration/nested-includes-strategy.test.tspackages/3-extensions/sql-orm-client/test/query-plan-select.test.ts
…e rejection (PR #555 review) Apply both findings from the code review of PR #555 / TML-2594. F01: route non-leaf includes carrying `distinct()` to multi-query. Under the single-query strategies the child SELECT carries nested JSON aggregate columns, and `SELECT DISTINCT` over those fails on Postgres (`json` has no equality operator). The multi-query stitcher applies distinct to scalar-only rows before grandchildren are joined, which is the semantically correct behavior we preserve. `distinctOn` is intentionally excluded -- Postgres only compares the `ON (...)` expressions for equality. F02: make `compileSelectWithIncludeStrategy` reject scalar/combine descriptors at every depth, not just the top level. The dispatch path already gates these via `hasComplexIncludeDescriptors` recursively, but the planner is an exported helper called directly by tests and rich-plan callers, so it must enforce the same invariant or a nested `count()` inside a row include would silently produce a malformed plan instead of failing fast at the boundary. Tests: - query-plan-select.test.ts: add nested scalar + nested combine rejection cases mirroring the existing top-level rejection test. - nested-includes-strategy.test.ts: add the reviewers exact regression query under LATERAL_CAPABILITIES, the same shape under CORRELATED_CAPABILITIES, and a depth-2 recursive case. Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…tural ScalarOrCombineIncludeDescriptors Apply the architect-review typology note from PR #555: `Complex` is a fuzzy qualifier, and the actual distinction the gate makes is structural (scalar reducer / combine() descriptor, regardless of where it sits in the include tree). Rename both parallel predicates -- the dispatch-side `hasComplexIncludeDescriptors` and the planner-side `hasScalarOrCombineIncludeAnywhere` -- to a single shared name `hasScalarOrCombineIncludeDescriptors`. Same name on both layers makes the parallel enforcement explicit; the boundary between dispatch policy and planner validity is preserved by their separate locations. Update inline comments in both source files and in the strategy / query-plan-select tests that referenced the old name. No behavior change. Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
93d086c to
5433ef7
Compare
|
Triage of CodeRabbit nitpick on This is a real but orthogonal concern. CodeRabbit itself tagged it If/when we want to schedule that split, it should land as a separate prep PR before further suite growth. |
|
Triage of CodeRabbit nitpick on This conflicts with the typesafety rule in our
The current CodeRabbit itself self-tagged this as |
|
Triage of CodeRabbit outside-diff comment on Good catch. Plan to address:
|
|
On it — lifting |
|
Done in 3ba642d.
|
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (1)
packages/3-extensions/sql-orm-client/src/collection-dispatch.ts (1)
481-494: ⚡ Quick winExtract the recursive scalar/combine gate into
include-tree-predicates.ts.This predicate now exists here and in
query-plan-select.ts. The non-leafdistinct()bug fixed in this PR is the same kind of planner/dispatcher drift this duplication can reintroduce, so I'd centralize it next tohasNonLeafIncludeWithDistinctand have both callers import the shared helper.🤖 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/sql-orm-client/src/collection-dispatch.ts` around lines 481 - 494, The predicate hasScalarOrCombineIncludeDescriptors is duplicated and should be extracted into a shared module (create include-tree-predicates.ts) so both collection-dispatch.ts and query-plan-select.ts import the same implementation; move the recursive function into that new file (exporting it by its existing name), update callers in collection-dispatch (hasScalarOrCombineIncludeDescriptors) and query-plan-select to import from include-tree-predicates, and ensure the new module sits alongside hasNonLeafIncludeWithDistinct so both predicates are co-located and maintained in one place.
🤖 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/3-extensions/sql-orm-client/test/collection-dispatch.test.ts`:
- Line 251: The test uses an extension-dependent field "embedding" in its
fixture/assertion object (the array entry [{ id: 10, title: 'Post A', user_id:
1, views: 1, embedding: null }]) even though this test is verifying
include-strategy fallback and not extension behavior; remove the embedding
property from both the test fixture and the matching expectation (the objects at
the two occurrences in collection-dispatch.test.ts) so the test only asserts id,
title, user_id, and views.
- Line 122: Three test titles include a ticket ID (TML-2594); update the
`it(...)` description strings to remove the ticket ID and keep them
behavior-focused. Locate the `it` declarations for the tests named like
"dispatchCollectionRows() depth-2 nested include with emitted-shape capabilities
fires a single SQL execution (TML-2594)" (and the two similar occurrences later
in the file) and edit the string arguments to remove "(TML-2594)" while
preserving the descriptive behavior text.
In `@packages/3-extensions/sql-orm-client/test/integration/include.test.ts`:
- Line 757: Remove the transient task ID from the test names that include
"(TML-2594)"; locate the two it(...) labels whose descriptions contain
"TML-2594" (e.g., "depth-2 include uses correlated subqueries when only jsonAgg
is enabled (TML-2594)") and edit the strings to omit the "(TML-2594)" suffix so
the descriptions read without the task ID. Ensure both occurrences are updated
(the one shown and the other at the later occurrence) and run tests to confirm
no other changes are needed.
---
Nitpick comments:
In `@packages/3-extensions/sql-orm-client/src/collection-dispatch.ts`:
- Around line 481-494: The predicate hasScalarOrCombineIncludeDescriptors is
duplicated and should be extracted into a shared module (create
include-tree-predicates.ts) so both collection-dispatch.ts and
query-plan-select.ts import the same implementation; move the recursive function
into that new file (exporting it by its existing name), update callers in
collection-dispatch (hasScalarOrCombineIncludeDescriptors) and query-plan-select
to import from include-tree-predicates, and ensure the new module sits alongside
hasNonLeafIncludeWithDistinct so both predicates are co-located and maintained
in one place.
🪄 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: e271c025-5856-45f6-afea-a70773608474
📒 Files selected for processing (10)
packages/3-extensions/sql-orm-client/src/collection-dispatch.tspackages/3-extensions/sql-orm-client/src/include-tree-predicates.tspackages/3-extensions/sql-orm-client/src/query-plan-select.tspackages/3-extensions/sql-orm-client/test/collection-dispatch.test.tspackages/3-extensions/sql-orm-client/test/integration/include.test.tspackages/3-extensions/sql-orm-client/test/integration/nested-includes-helpers.tspackages/3-extensions/sql-orm-client/test/integration/nested-includes-refinements.test.tspackages/3-extensions/sql-orm-client/test/integration/nested-includes-strategy.test.tspackages/3-extensions/sql-orm-client/test/integration/nested-includes.test.tspackages/3-extensions/sql-orm-client/test/query-plan-select.test.ts
|
Triage of CodeRabbit nitpick on Good call, and a natural follow-up to the A03a fix — that one lifted Plan to address:
|
|
Done — lifted
Validation:
|
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
packages/3-extensions/sql-orm-client/src/query-plan-select.ts (1)
271-324:⚠️ Potential issue | 🟠 Major | ⚡ Quick winRemap child
orderByto the self-relation alias before emitting the nested SELECT.When
childTableAliasis introduced for a self-relation,childState.orderBystill points atinclude.relatedTableName. The nested SELECT then orders by a table name that is no longer in scope, so single-query self-relations with nestedorderBywill emit invalid SQL.Suggested fix
const childState = include.nested; const childTableAlias = include.relatedTableName === parentTableName ? `${include.relationName}__child` : undefined; const childTableRef = childTableAlias ?? include.relatedTableName; const rowsAlias = `${include.relationName}__rows`; + const childOrderByInput = + childTableAlias && childState.orderBy + ? childState.orderBy.map( + (item) => + new OrderByItem( + item.expr.rewrite( + createTableRefRemapper(include.relatedTableName, childTableRef), + ), + item.dir, + ), + ) + : childState.orderBy; const scalarProjection = buildProjection( contract, include.relatedTableName, childState.selectedFields, childTableRef, ); const { childOrderBy, hiddenOrderProjection, aggregateOrderBy } = buildIncludeOrderArtifacts( include.relationName, rowsAlias, - childState.orderBy, + childOrderByInput, );🤖 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/sql-orm-client/src/query-plan-select.ts` around lines 271 - 324, The nested SELECT can reference an out-of-scope table name when a self-relation alias (childTableAlias) is used because childState.orderBy still points at include.relatedTableName; fix by remapping childState.orderBy to use childTableRef before calling buildIncludeOrderArtifacts (and before passing it into buildStateWhere if needed). Concretely, transform the orderBy entries on childState (or create a remapped copy) so their table identifiers equal childTableRef when childTableAlias is defined, then pass that remapped orderBy into buildIncludeOrderArtifacts (and ensure buildStateWhere/getters use childTableRef as the filterTableName as already done).packages/3-extensions/sql-orm-client/src/collection-dispatch.ts (1)
256-259:⚠️ Potential issue | 🟠 Major | ⚡ Quick winPreserve nested join keys on the multi-query fallback path.
stitchIncludes()reads each nested include'slocalColumnfromchild.raw, butresolveRowsByParent()only forcesinclude.targetColumnintoselectedForQuery. If a childselectomits a grandchild join key, the fallback sees onlyundefinedjoin values and silently returns empty nested results. That breaks the new depth-2+ parity whenever we route to multi-query for missing capabilities, nestedcombine(), or non-leafdistinct().Suggested fix
async function resolveRowsByParent( scope: RuntimeScope, contract: Contract<SqlStorage>, include: IncludeExpr, state: CollectionState, parentJoinValues: readonly unknown[], ): Promise<Map<unknown, Record<string, unknown>[]>> { + const nestedJoinColumns = collectNestedLocalJoinColumns(state.includes); const { selectedForQuery: childSelectedForQuery, hiddenColumns: hiddenChildColumns } = - augmentSelectionForJoinColumns(state.selectedFields, [include.targetColumn]); + augmentSelectionForJoinColumns(state.selectedFields, [ + include.targetColumn, + ...nestedJoinColumns, + ]); @@ return childByParentJoin; } + +function collectNestedLocalJoinColumns(includes: readonly IncludeExpr[]): string[] { + return [...new Set( + includes.flatMap((include) => [ + include.localColumn, + ...collectNestedLocalJoinColumns(include.nested.includes), + ]), + )]; +}Also applies to: 385-408
🤖 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/sql-orm-client/src/collection-dispatch.ts` around lines 256 - 259, resolveRowsByParent is only forcing include.targetColumn into selectedForQuery which drops nested join keys that stitchIncludes expects on child.raw; update resolveRowsByParent so that for each include you also ensure include.localColumn is selected (i.e., add include.localColumn to selectedForQuery or otherwise request both include.targetColumn and include.localColumn) so child.raw contains the nested join key used by stitchIncludes(), and apply the same change in the other multi-query fallback block (the similar logic around the 385-408 region).
🤖 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/sql-orm-client/src/collection-dispatch.ts`:
- Around line 256-259: resolveRowsByParent is only forcing include.targetColumn
into selectedForQuery which drops nested join keys that stitchIncludes expects
on child.raw; update resolveRowsByParent so that for each include you also
ensure include.localColumn is selected (i.e., add include.localColumn to
selectedForQuery or otherwise request both include.targetColumn and
include.localColumn) so child.raw contains the nested join key used by
stitchIncludes(), and apply the same change in the other multi-query fallback
block (the similar logic around the 385-408 region).
In `@packages/3-extensions/sql-orm-client/src/query-plan-select.ts`:
- Around line 271-324: The nested SELECT can reference an out-of-scope table
name when a self-relation alias (childTableAlias) is used because
childState.orderBy still points at include.relatedTableName; fix by remapping
childState.orderBy to use childTableRef before calling
buildIncludeOrderArtifacts (and before passing it into buildStateWhere if
needed). Concretely, transform the orderBy entries on childState (or create a
remapped copy) so their table identifiers equal childTableRef when
childTableAlias is defined, then pass that remapped orderBy into
buildIncludeOrderArtifacts (and ensure buildStateWhere/getters use childTableRef
as the filterTableName as already done).
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: 67e28bfc-5dbf-4e10-b02b-8bde054fb1a0
📒 Files selected for processing (7)
packages/3-extensions/sql-orm-client/src/collection-dispatch.tspackages/3-extensions/sql-orm-client/src/include-tree-predicates.tspackages/3-extensions/sql-orm-client/src/query-plan-select.tspackages/3-extensions/sql-orm-client/test/collection-dispatch.test.tspackages/3-extensions/sql-orm-client/test/integration/include.test.tsskills/extension-author/prisma-next-extension-upgrade/upgrades/0.10-to-0.11/instructions.mdskills/upgrade/prisma-next-upgrade/upgrades/0.10-to-0.11/instructions.md
✅ Files skipped from review due to trivial changes (2)
- skills/upgrade/prisma-next-upgrade/upgrades/0.10-to-0.11/instructions.md
- skills/extension-author/prisma-next-extension-upgrade/upgrades/0.10-to-0.11/instructions.md
…e rejection (PR #555 review) Apply both findings from the code review of PR #555 / TML-2594. F01: route non-leaf includes carrying `distinct()` to multi-query. Under the single-query strategies the child SELECT carries nested JSON aggregate columns, and `SELECT DISTINCT` over those fails on Postgres (`json` has no equality operator). The multi-query stitcher applies distinct to scalar-only rows before grandchildren are joined, which is the semantically correct behavior we preserve. `distinctOn` is intentionally excluded -- Postgres only compares the `ON (...)` expressions for equality. F02: make `compileSelectWithIncludeStrategy` reject scalar/combine descriptors at every depth, not just the top level. The dispatch path already gates these via `hasComplexIncludeDescriptors` recursively, but the planner is an exported helper called directly by tests and rich-plan callers, so it must enforce the same invariant or a nested `count()` inside a row include would silently produce a malformed plan instead of failing fast at the boundary. Tests: - query-plan-select.test.ts: add nested scalar + nested combine rejection cases mirroring the existing top-level rejection test. - nested-includes-strategy.test.ts: add the reviewers exact regression query under LATERAL_CAPABILITIES, the same shape under CORRELATED_CAPABILITIES, and a depth-2 recursive case. Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…tural ScalarOrCombineIncludeDescriptors Apply the architect-review typology note from PR #555: `Complex` is a fuzzy qualifier, and the actual distinction the gate makes is structural (scalar reducer / combine() descriptor, regardless of where it sits in the include tree). Rename both parallel predicates -- the dispatch-side `hasComplexIncludeDescriptors` and the planner-side `hasScalarOrCombineIncludeAnywhere` -- to a single shared name `hasScalarOrCombineIncludeDescriptors`. Same name on both layers makes the parallel enforcement explicit; the boundary between dispatch policy and planner validity is preserved by their separate locations. Update inline comments in both source files and in the strategy / query-plan-select tests that referenced the old name. No behavior change. Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
22a06e5 to
406b659
Compare
…WithIncludeStrategy Lift hasNonLeafIncludeWithDistinct from collection-dispatch.ts into a shared include-tree-predicates module, and apply the same recursive gate in the exported planner so direct callers (tests, rich-plan consumers) fail fast instead of building an invalid SELECT DISTINCT over a nested json_agg projection. Refs: TML-2594 Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…ludes single-query collapse Records the 0.10 → 0.11 upgrade-instructions directory in both the user-skill and extension-author-skill packages, so pnpm check:upgrade-coverage --mode pr passes on this PR. - skills/extension-author/prisma-next-extension-upgrade/upgrades/0.10-to-0.11/ carries the real entry describing the SQL ORM client behaviour shift (nested includes at depth ≥ 2 collapse to single-query on capable targets; non-leaf .distinct() with nested includes now throws). - skills/upgrade/prisma-next-upgrade/upgrades/0.10-to-0.11/ ships with changes: [] — the only examples/ diff in this branch is incidental devDep cleanup, no user-facing behaviour change. Refs: TML-2594 Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…patch test labels Renames three `it(...)` labels in collection-dispatch.test.ts so test titles stay behaviour-focused per the test-naming guideline (same rule we honoured in A01 for nested-includes-strategy.test.ts): - "...fires a single SQL execution (TML-2594)" → drop suffix - "...mixed cardinality (...) (TML-2594)" → drop suffix - "...stays on multi-query (TML-2594 fallback)" → drop suffix Forward-looking code comments that reference TML-2594/TML-2595 stay — the rule only forbids transient ticket ids in test names. Refs: TML-2594 Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…clude test labels Renames the two `it(...)` labels in test/integration/include.test.ts (lines 757 and 846) so test titles stay behaviour-focused per the test-naming guideline. Same shape as A05 on collection-dispatch.test.ts. The forward-looking code comment at line 747 stays — the rule only forbids transient ticket ids in test names. Refs: TML-2594 Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…uery-fallback fixture The multi-query-fallback test exercises include-strategy selection, not pgvector behaviour. The `embedding` column on the Post fixture row (and the matching `expect(...).toEqual` shape) is extension- dependent and has no bearing on what the test asserts (parent + posts + comments = 3 executions, irrespective of column shape). Drops `embedding: null` from both the `runtime.setNextResults(...)` row at line 251 and the corresponding expectation at line 276. The test still passes (13/13 in this file, 3 skipped). Refs: TML-2594 Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…o shared include-tree-predicates Both `dispatchWithIncludeStrategy` (in `collection-dispatch.ts`) and the exported `compileSelectWithIncludeStrategy` (in `query-plan-select.ts`) were carrying their own private copies of the same recursive predicate, with the same body. The symmetric tidy- up to A03a (which lifted `hasNonLeafIncludeWithDistinct` into `include-tree-predicates.ts`) — without it, future drift between the planner and the dispatcher could reintroduce a mismatch where one seam accepts a descriptor the other rejects. Moves the function (plus a merged doc-comment that covers both call sites) into `src/include-tree-predicates.ts` next to `hasNonLeafIncludeWithDistinct`, and imports it from both consumers. No behaviour change — the predicate body is identical to both prior copies. Validation (filtered to the affected suites): - pnpm --filter @prisma-next/sql-orm-client typecheck → clean - pnpm --filter @prisma-next/sql-orm-client lint → clean - vitest run test/collection-dispatch.test.ts test/query-plan-select.test.ts → 31 passed, 3 skipped Refs: TML-2594 Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…nt tests Replaces two projected-slice assertions with whole-result `expect(rows).toEqual([...])` blocks so the tests pin the entire stitched shape (ids, scalars, AND the nested include arrays), not just a sub-tree: - where() filter on depth-2 child (line 78-ish): was `expect(rows[0]?.posts).toEqual([...])` → now asserts the parent User shape too. - orderBy on parent and on depth-2 child (line 117-ish): was `expect(rows.map(r => r.id)).toEqual([1, 2])` plus `expect(rows[1]?.posts[0]?.comments.map(c => c.id))` → now asserts the full parent+posts+comments shape across both rows. Mirrors the whole-result style already used by the depth-2 edge-case tests further down in the same suite. Refs: TML-2594 Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
… scalar/combine tests
Replaces two projected-slice assertions in nested-includes-strategy.test.ts
with whole-result expect(rows).toEqual([...]) blocks so the tests pin
the entire stitched shape, not just one sub-tree value:
- top-level combine() stays on multi-query under lateral capabilities
(line 392-393): was expect(rows[0]?.posts.total) plus
expect(rows[0]?.posts.items).toHaveLength(2) → now asserts the
parent User row plus the combined { items: [...full posts...],
total: 2 } shape.
- nested scalar at depth 2 stays on multi-query (line 423): was
expect(rows[0]?.posts[0]?.comments).toBe(2) → now asserts the
parent row, the post row, and that the c.count() include slot
resolves to the scalar 2.
The execution-count guard (expect(runtime.executions.length)
.toBeGreaterThan(1)) is preserved unchanged on both — that pin is
what keeps the dispatch gate honest across future refactors.
A13/A14/A15 (the distinct()-on-non-leaf cases) will receive the
same whole-result treatment in a follow-up commit after A19b lands
the resolveRowsByParent fix that lets nested comments populate when
the parent .select(...) omits the join column.
Refs: TML-2594
Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
… per review Trims the sql-orm-client-nested-includes-single-query-at-depth-2 section in skills/extension-author/prisma-next-extension-upgrade/ upgrades/0.10-to-0.11/instructions.md per @aqrln review: - Drop the seam-internal bullet list (dispatchWithIncludeStrategy / compileSelectWithIncludeStrategy enumeration). Internal entry-point names are not part of the upgrade story for extension authors; the one consumer-relevant mention of compileSelectWithIncludeStrategy stays in Who is affected. (A16) - Drop the New safety gate / non-leaf .distinct() entry. That gate is a transitional measure scheduled to lift before 0.11 GA, so documenting it as a permanent migration step would mislead. The recursive scalar/combine generalisation, which is the load-bearing recursion change actually shipping, is kept under a smaller header with the gate description tightened. (A17) - Replace the verbose three-bullet Who is affected enumeration with a short note framing the change as a bugfix that aligns behaviour with the documented surface, and pointing the small subset of plan-shape-introspecting extensions at strategy pinning if a specific shape is needed. (A18) pnpm check:upgrade-coverage --mode pr remains green. Refs: TML-2594 Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…hildRowsSelect When `include.relatedTableName === parentTableName` (self-relations), `buildIncludeChildRowsSelect` already renames the inner FROM source via `childTableAlias` and remaps `state.filters` / `state.cursor` through `createTableRefRemapper(include.relatedTableName, childTableRef)` via the `filterTableName` option to `buildStateWhere`. The user-supplied `childState.orderBy` was missing from that remap, so the hidden order projection inside the inner rows-subselect emitted a ColumnRef against the original outer table name (`users`) that is no longer in scope. In a lateral / correlated subquery PG resolves the outer-scope name silently, which means ORDER BY correlates against the outer row (constant per parent) instead of the inner child rows — order becomes indeterminate within each parent group. Symptom: nested self-relation includes with an `orderBy(...)` clause return children in insertion order, not the requested order. Fix mirrors the existing `filterTableName` remap shape exactly: when `childTableAlias` is set, rewrite every `OrderByItem` in `childState.orderBy` through the same `createTableRefRemapper` before passing into `buildIncludeOrderArtifacts`. Regression test (`test/integration/self-relations.test.ts`): a self-relation include with `invitedUsers.orderBy(u => u.id.desc())` on out-of-id-order seeded children. Before the fix the children come back in insertion order [2, 4, 3]; after the fix in id-desc order [4, 3, 2]. The test also asserts the hidden order projection in the emitted SQL references `"invitedUsers__child"."id"`, not the outer `"users"."id"`. Refs: TML-2594 Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…selectedForQuery
In `resolveRowsByParent`, when `state.includes` is non-empty the
downstream `stitchIncludes(scope, contract, childRows, state.includes)`
call reads `child.raw[grandchildInclude.localColumn]` for every
immediate include to bucket children by join value. Until now the
augmented child `selectedForQuery` only forced `include.targetColumn`
in. So a user-supplied `.select(...)` on the child that omitted any
of those grandchild join keys silently yielded `undefined` for the
join value, and depth >= 2 nested arrays came back empty.
Collect every direct `state.includes[i].localColumn` and union them
with `include.targetColumn` into the required-columns set passed to
`augmentSelectionForJoinColumns`. The next level of recursion repeats
the same augmentation for its own children. `augmentSelectionForJoinColumns`
already handles the strip on the way out, so the user-visible mapped
shape stays exactly what `.select(...)` asked for.
Regression test (`test/integration/nested-includes-refinements.test.ts`):
depth-2 multi-query path (empty capabilities) with
`posts.select(\"title\").include(\"comments\")`. Before the fix
`comments: []` because `Post.id` is not in the child query`s SELECT;
after the fix `comments: [{ id: 100, body: \"hi\", postId: 10 }]`.
Verified the test fails on the unfixed substrate.
Refs: TML-2594
Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…ests
Replaces the projected-slice assertions in the three
non-leaf-distinct() tests with whole-result expect(rows).toEqual([...])
blocks now that A19b populates comments correctly when the parent
.select(...) omits the join key:
- distinct() on a non-leaf include stays on multi-query under lateral
capabilities (line 469-471): was three partial assertions
(toHaveLength + map+sort). Adds .orderBy((p) => p.title.asc()) to
the posts include to lock order, then asserts the parent row plus
posts [{title: A, comments: [...]}, {title: B, comments: []}].
- distinct() under correlated capabilities (line 498-499): was
toHaveLength(1) + toBe(A). Now asserts the parent and the single
post with its single comment.
- distinct() nested at depth 2 (line 529): was no row assertion at
all (just executions.length > 1). Adds .orderBy((u) => u.id.asc())
on the outer collection, then asserts the full two-row shape
including the empty invitedUsers for Child.
Each test keeps its expect(runtime.executions.length).toBeGreaterThan(1)
guard so the dispatch gate stays pinned.
Refs: TML-2594
Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
1030268 to
a8eca57
Compare
The `@prisma-next/sql-orm-client` package only exports `Collection`, `orm`, `all`/`and`/`not`/`or`, `GroupedCollection`, and a set of type-only surface types. The internal planner / dispatcher seams the removed entry documented (`compileSelectWithIncludeStrategy`, `dispatchWithIncludeStrategy`, the shared `include-tree-predicates` helpers) are not reachable from outside the package. No extension author can be affected by the strategy-selection or gate changes, so documenting them as a migration step is misleading. The directory still carries the three valid 0.10-to-0.11 entries (`namespace-kind-required-on-handcrafted-contract-literals`, `facade-add-close-and-async-dispose`, `mongo-close-ownership-rule`), so `pnpm check:upgrade-coverage --mode pr` continues to pass. Refs: TML-2594 Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
… + self-relation tests Four partial-result assertions left in this PR after the iter-4 sweep: - `nested-includes-refinements.test.ts:42` (orderBy + take on depth-2 child) asserted only on `rows[0]?.posts[0]?.comments`. Now asserts the full Alice row with the single post containing both ordered comments. - `nested-includes-refinements.test.ts:240` (depth-1 present but no depth-2 grandchildren) asserted only on `rows[0]?.posts`. Now asserts the full Alice row with the empty-comments post. - `nested-includes-refinements.test.ts:269` (descendant-localColumn regression test for A19b) asserted only on `rows[0]?.posts`. Now asserts the full Alice row with the selected `title` and the stitched depth-2 comment. - `self-relations.test.ts:101` (childTableRef-orderBy regression test for A19a) asserted only `rows[0]?.invitedUsers.map((u) => u.id)`. Now asserts the full Alice row with all three invitedUsers in desc-id order, each with every scalar column. The hidden-orderBy SQL assertion immediately below it is preserved. Refs: TML-2594 Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…e rejection (PR #555 review) Apply both findings from the code review of PR #555 / TML-2594. F01: route non-leaf includes carrying `distinct()` to multi-query. Under the single-query strategies the child SELECT carries nested JSON aggregate columns, and `SELECT DISTINCT` over those fails on Postgres (`json` has no equality operator). The multi-query stitcher applies distinct to scalar-only rows before grandchildren are joined, which is the semantically correct behavior we preserve. `distinctOn` is intentionally excluded -- Postgres only compares the `ON (...)` expressions for equality. F02: make `compileSelectWithIncludeStrategy` reject scalar/combine descriptors at every depth, not just the top level. The dispatch path already gates these via `hasComplexIncludeDescriptors` recursively, but the planner is an exported helper called directly by tests and rich-plan callers, so it must enforce the same invariant or a nested `count()` inside a row include would silently produce a malformed plan instead of failing fast at the boundary. Tests: - query-plan-select.test.ts: add nested scalar + nested combine rejection cases mirroring the existing top-level rejection test. - nested-includes-strategy.test.ts: add the reviewers exact regression query under LATERAL_CAPABILITIES, the same shape under CORRELATED_CAPABILITIES, and a depth-2 recursive case. Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…tural ScalarOrCombineIncludeDescriptors Apply the architect-review typology note from PR #555: `Complex` is a fuzzy qualifier, and the actual distinction the gate makes is structural (scalar reducer / combine() descriptor, regardless of where it sits in the include tree). Rename both parallel predicates -- the dispatch-side `hasComplexIncludeDescriptors` and the planner-side `hasScalarOrCombineIncludeAnywhere` -- to a single shared name `hasScalarOrCombineIncludeDescriptors`. Same name on both layers makes the parallel enforcement explicit; the boundary between dispatch policy and planner validity is preserved by their separate locations. Update inline comments in both source files and in the strategy / query-plan-select tests that referenced the old name. No behavior change. Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
Linked issue
Refs TML-2594
At a glance
Before this PR, depth-2+ includes always emitted one IN-batched SQL statement per depth level, regardless of what the contract advertised. After, the same query collapses to a single statement on Postgres (lateral) and SQLite (correlated):
The same shape works on SQLite via nested correlated subqueries. Targets advertising neither
lateralnorjsonAggretain today's IN-batched multi-query fallback.Decision
hasNestedIncludesarm ofdispatchWithIncludeStrategy. Nested row includes no longer force a fallback to multi-query — strategy selection now honours the contract's declared capabilities at any depth.IncludeExpr.nested.includes. Each depth contributes one nested artifact (LATERAL JOIN underlateral, correlated subquery undercorrelated) plus one entry in the parent's innerjson_object. The outer aggregate picks them up automatically; no changes were needed to the outer-builder callers beyond threading the strategy through.hasComplexIncludeDescriptorsnow catches nestedcount()/combine()at any depth, so the still-broken combine/scalar surface (sibling ticket TML-2595) stays on multi-query without leaking into the lateral builder's explicitthrow.How it fits together
src/collection-dispatch.ts).dispatchWithIncludeStrategyno longer short-circuits on nested row includes. The only remaining early-return ishasComplexIncludeDescriptors, which now recurses. After this gate,selectIncludeStrategy(contract)decides between'lateral','correlated', and'multiQuery'just as it does for depth-1 today.src/query-plan-select.ts). A newbuildNestedIncludeArtifacts(contract, parentTableRef, includes, strategy)walks the nested includes and returns{ joins, projections }shaped to match the strategy.buildIncludeChildRowsSelectnow takes astrategyparameter, calls the new helper againstchildTableRef, merges nested joins/projections into the inner SELECT, and exposes them onchildProjectionso the outer aggregate'sJsonObjectExprgains an entry per nested aggregate column without any caller change.src/collection-dispatch.ts).dispatchWithSingleQueryIncludesfactors child-row decode into a new recursivedecodeIncludePayloadhelper that walks the include tree in sync with the parsed JSON tree: parse the column,mapStorageRowToModelFieldsper child, recurse into nested aggregate columns, then coerce to to-one or to-many via the existingcoerceSingleQueryIncludeResult.${relationName}__childwhen the child table equals the parent) propagates per level because the recursion passeschildTableRefas the nextparentTableRef. The depth-2 self-relation integration tests pin this — bothinvitedUsers → invitedUsersandinvitedBy → invitedByresolve in one SQL execution.parseIncludedRowsrecognises both the top-level string form and the inner array form, so the recursion threads through transparently.Behavior changes & evidence
lateral/jsonAgg-capable targets. Implementation:src/query-plan-select.ts,src/collection-dispatch.ts. Evidence:test/integration/nested-includes-strategy.test.ts—depth-{2,3} under {lateral,correlated} capabilities runs a single SQL execution; depth-2 self-relation single-execution under both strategies.depth-2 under empty capabilities runs 3 SQL executions (multi-query fallback),depth-3 under empty capabilities runs 4 SQL executions (multi-query fallback).test/integration/nested-includes-strategy.test.ts—depth-2 {lateral,correlated,multi-query} path produces the canonical result tree.orderBy,take,where,select) on the nested level apply inside the inner SELECT. Implementation:buildIncludeChildRowsSelectwas already wiring child state into the inner SELECT; the recursion threads the same wiring per depth. Evidence:test/integration/nested-includes-refinements.test.ts— all four refinement cases plus three edge cases (empty parent, missing grandchildren, unsatisfied FK).combine()andcount()still route to multi-query, including when nested. Implementation:hasComplexIncludeDescriptorsrecursion insrc/collection-dispatch.ts. Evidence:test/integration/nested-includes-strategy.test.ts—top-level combine() stays on multi-query under lateral capabilities,nested scalar at depth 2 stays on multi-query under lateral capabilities (recursive gate). These tests assert.toBeGreaterThan(1); TML-2595 will flip them to.toBe(1).Reviewer notes
query-plan-select.tsrecursion is the most concentrated change, ~70 LOC; everything else is local. Spot-checkbuildNestedIncludeArtifactsand the newstrategyparameter threading inbuildIncludeChildRowsSelect.test/integration/file in the package respects). The split keeps each file deterministic in isolation; a sharednested-includes-helpers.tscarries thecollectionWithCapabilitiesfactory + capability constants. The threshold is documented at the top of the helpers file. Pre-existing test files (codec-async.test.ts,nested-mutations.test.ts) intermittently flake on the same infrastructure under parallel load — out of scope for this PR.hasComplexIncludeDescriptorsrecursion is forward-compat with TML-2595. Without it, droppinghasNestedIncludeswould route depth-2 trees containing a nestedcount()straight into the lateral builder'sthrow new Error('single-query include strategy does not support scalar include selectors or combine()'). The two coexistence tests pin this behaviour.compileSelectWithIncludeStrategycallsbuildMtiJoinsonly for the parent; nested includes into polymorphic relations remain as-is (same constraint that depth-1 already has). No regressions because no test was relying on nested-polymorphic.augmentSelectionForJoinColumnsis still only applied at the parent level. At the child level the innerWHEREreferences columns viaColumnRefdirectly, which don't need to be in the projection. Existingselect()restriction at depth 2 covered by the refinements test.Verification
pnpm typecheck(sql-orm-client) — clean.pnpm lint(sql-orm-client) — clean.pnpm lint:deps(repo root) — clean: 955 modules / 1974 dependencies, no violations.pnpm test(sql-orm-client full package) — 646 tests pass, 3 skipped (pre-existing deferred async-codec stubs).codec-async.test.ts,nested-mutations.test.ts). Confirmed pre-existing prisma/dev infrastructure flakiness under parallel load, not a regression from this PR.Follow-ups
combine()/ scalarcount()still route to multi-query through the recursivehasComplexIncludeDescriptorsgate. Two coexistence tests innested-includes-strategy.test.tscarry.toBeGreaterThan(1)assertions that flip to.toBe(1)when TML-2595 lands.Alternatives considered
stitchCombinedIncludealready does non-trivial work) and conflating them would make the diff harder to review. The recursivehasComplexIncludeDescriptorsis the seam.buildIncludeChildRowsSelectstrategy-agnostic and lift the lateral-vs-correlated choice to the callers per level. Less recursion in the helper, but every caller would need to know how to nest into the next level — duplicating the strategy switch. Threadingstrategythrough the recursion keeps the policy in one place.concurrentfor the integration corpus to keep one file. Would have made the prisma/dev contention worse, not better. The file-count split is the cheaper fix and matches the package's existing per-file convention (every othertest/integration/file is ≤ 13 tests).Skill update
n/a — internal only. No user-visible CLI / API / config surface changes; the fix is observable purely as fewer SQL round-trips for the same
include()calls.Checklist
git commit -s) per the DCO. The DCO status check will block merge if any commit is missing aSigned-off-by:trailer.n/aif the change is doc-only / refactor with no behavioural delta).TML-NNNN: <sentence-case title>form (Linear ticket prefix + concise title naming the concrete deliverable). See.claude/skills/create-pr/SKILL.mdfor the full convention.n/a — internal only).Summary by CodeRabbit
New Features
Bug Fixes
Tests
Documentation