fix(sql-orm-client): alias child table for self-referential 1:N relation predicates - #1010
fix(sql-orm-client): alias child table for self-referential 1:N relation predicates#1010prisma-gremlin[bot] wants to merge 1 commit into
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (4)
🚧 Files skipped from review as they are similar to previous changes (2)
📝 WalkthroughWalkthroughSelf-referential one-to-many relation predicates now alias the child table in correlated ChangesSelf-referential relation predicates
Estimated code review effort: 3 (Moderate) | ~20 minutes Sequence Diagram(s)sequenceDiagram
participant RelationPredicate
participant buildExistsExpr
participant ChildExistsSubquery
RelationPredicate->>buildExistsExpr: Build invitedUsers relation predicate
buildExistsExpr->>ChildExistsSubquery: Generate aliased correlated EXISTS subquery
ChildExistsSubquery-->>RelationPredicate: Return filtered user rows
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
size-limit report 📦
|
@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/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/extension-supabase
@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/config-loader
@prisma-next/emitter
@prisma-next/language-server
@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
🤖 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/src/model-accessor.ts`:
- Around line 370-393: Limit the alias remapping in the current EXISTS
construction around buildJoinWhere and remapColumnRefs so it only rewrites
ColumnRefs belonging to this relation-filter level. Update rewrite() to avoid
descending into nested subqueries, preserving their internal aliases and
correlations while still remapping direct references from relatedTableName to
relatedTableRef.
🪄 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: e28fa923-2e17-48db-82a7-3760330c2d14
📒 Files selected for processing (3)
packages/3-extensions/sql-orm-client/src/model-accessor.tspackages/3-extensions/sql-orm-client/test/model-accessor.test.tstest/integration/test/sql-orm-client/ported-regressions.test.ts
…ion predicates
A relation predicate (some/every/none) on a self-referential one-to-many
relation emitted a correlated EXISTS subquery whose child FROM referenced the
unaliased parent table, so the inner FROM shadowed the outer correlation and
the predicate silently matched nothing (e.g. invitedUsers.some({ name: 'Bob' })
returned [] instead of [Alice]).
Mirror the M:N predicate and include paths: when parent and child resolve to
the same table, alias the child FROM to ${relationName}__child, route the join
correlation's target column and the EXISTS projection through the alias, and
remap the predicate's column refs onto it. Non-self-relations are unchanged.
Fixes #980
Signed-off-by: Gremlin <gremlin@users.noreply.github.com>
a90267c to
48309de
Compare
Fixes #980
Root cause
A relation predicate (
some/every/none) on a self-referential one-to-manyrelation emitted a correlated
EXISTSsubquery whose childFROMreferenced theunaliased parent table. For
User.invitedUsers(a 1:N self-relation viainvited_by_id, both sides resolving tousers), the generated SQL was:In SQL the inner
FROM usersshadows the outeruserscorrelation, sousers.invited_by_id = users.idcompared the inner row against itself (matchingonly rows that invited themselves) instead of correlating the child's
invited_by_idto the outer parent'sid. The predicate therefore silentlymatched nothing —
invitedUsers.some({ name: 'Bob' })returned[]instead of[Alice].Only the 1:N relation-predicate path in
buildExistsExpr(
packages/3-extensions/sql-orm-client/src/model-accessor.ts) was affected. Thesibling M:N predicate path (
buildManyToManyExistsExpr) and the include path(
resolveChildTableSourceinquery-plan-select.ts) already alias the childtable to
${relationName}__childfor self-relations; the 1:N predicate path wasthe only one missing this aliasing.
include()on the same self-relation workedbecause it goes through the already-aliased include path, which is why the bug
was specific to relation predicates on self-referential relations.
Fix
Make the 1:N
buildExistsExprmirror the M:N path: when the parent and childresolve to the same underlying table (same namespace + same table name), alias
the child
FROMto${relationName}__child, route the join correlation'starget column and the
EXISTSprojection through that alias, and remap thepredicate's column refs onto the alias via the existing
remapColumnRefshelper.Non-self-relations are unchanged — the alias is
undefinedandremapColumnRefsshort-circuits when the table name equals the ref.buildJoinWhere's parameter was renamed fromrelatedTableNametorelatedTableRefso the correlation's child side follows the alias; it has asingle caller.
Tests
test/integration/test/sql-orm-client/ported-regressions.test.ts(entry 107) reproduces the issue against PGlite:
some/none/everyonUser.invitedUserswith the issue's exact seed.somereturned[]beforethe fix; all three return the correct sets after.
packages/3-extensions/sql-orm-client/test/model-accessor.test.tsassert the self-referential 1:N predicate emits the
invitedUsers__childalias on
from/projection/where, with the parent kept onusersand thepredicate remapped onto the alias. These fail without the fix and pass with it.
subtaskspolymorphic self-relation unit test, which hadbeen codifying the buggy
tasks.parent_id = tasks.idAST, to expect thesubtasks__childalias. Its intent (base relations resolve against the basetable even when a variant is selected) is preserved — the parent side remains
tasks.Verification
pnpm test(sql-orm-client): 61 files / 665 tests pass, no type errors.pnpm test(integration, fulltest/sql-orm-client/): 33 files / 251 testspass — no regressions across self-relations, M:N filters, includes,
polymorphism, nested includes.
pnpm typecheck(sql-orm-client and integration-tests): clean.pnpm lint(both packages): clean (only pre-existingno-bare-castinfos inuntouched files; no new bare casts —
asonly in test files, which areexempt).
pnpm lint:deps: no dependency violations.somereturning[]; unit: 2 failed withalias: undefined) and pass withit.
Created by Mohawk
Summary by CodeRabbit
some/none/everypredicates generate correct SQL and return accurate results.invitedUsersandsubtasks.