Repository navigation
TML-2786: M:N slice 2 — relation filters (some/every/none) through the junction - #680
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 M:N relation filters by detecting through-backed relations and lowering ChangesMany-to-many relation filtering implementation
Sequence DiagramsequenceDiagram
participant Caller as createRelationFilterAccessor
participant Guard as hasThrough
participant Planner as planRelationFilterMode
participant Builder as buildManyToManyExistsExpr
participant Mapper as remapColumnRefs
Caller->>Guard: check relation metadata
Guard->>Caller: through present?
alt Through relation detected
Caller->>Planner: plan some/every/none semantics
Planner->>Caller: filter plan (exists/notExists/constantTrue)
Caller->>Builder: delegate with plan + relationName
Builder->>Builder: buildPairedColumnExprs (junction -> child)
Builder->>Builder: buildPairedColumnExprs (parent -> junction)
Builder->>Mapper: remap child predicate column refs
Builder->>Caller: EXISTS or NOT EXISTS AST
else Standard relation
Caller->>Caller: FK-based join logic
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 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 |
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/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: |
4ee6af6 to
78affcf
Compare
92d1741 to
25a3c7e
Compare
78affcf to
e4e3004
Compare
06fc270 to
bc2d4b9
Compare
9e24a8b to
ed06084
Compare
3982e13 to
b1dadcf
Compare
ed06084 to
38bcb74
Compare
b1dadcf to
df900cd
Compare
38bcb74 to
c32cd78
Compare
df900cd to
ee44053
Compare
b7c8ede to
c73f70b
Compare
65d4fe3 to
bd47c00
Compare
7e21c60 to
f383943
Compare
2807fb8 to
f1c6a5d
Compare
a36b0d5 to
07aa1cf
Compare
f1c6a5d to
840a6b3
Compare
07aa1cf to
12ec127
Compare
f159866 to
2828012
Compare
tensordreams
left a comment
There was a problem hiding this comment.
Reviewed this PR separately against main (origin/main...origin/tml-2786-slice-2-filter). I focused on the M:N filter EXISTS builder, composite-key handling, cross-namespace/table-source behavior, and the added unit/integration coverage. I did not find actionable issues in this PR.
tensordreams
left a comment
There was a problem hiding this comment.
Reviewed this slice against projects/sql-orm-many-to-many/slices/02-filter-exists-through-junction/spec.md, the slice-1 include path (query-plan-select.ts), and the AST builders.
Solid, spec-faithful slice. The junction-EXISTS shapes for some/every/none are correct (some → EXISTS(target JOIN junction …), none → NOT EXISTS(…), every → NOT EXISTS(… AND NOT(pred)) with vacuous-true for an empty predicate), deliberately mirroring the existing FK path as the spec requires. Composite keys are AND-ed on both correlation and join sides, and namespace coordinates are threaded explicitly everywhere (through.namespaceId, relation.toNamespace, parentNamespaceId) — no new bare-name lookups. Type-safety and test conventions (no should, whole-shape toEqual with explicit select) are all observed.
No blockers or majors. The inline comments are hardening/consistency items — the most substantive being the silent Math.min truncation in buildPairedColumnExprs (diverges from the invariant-based handling slice 1 established for the identical condition on the include path) and the unaliased self-relation gap, which deserves at least a recorded follow-up.
Filter slice: some/every/none EXISTS through the junction. 2 dispatches (filter code / integration tests). Reuses slice 1 User↔Tag fixture. Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
Add some/every/none filter support for many-to-many relations, generating
correlated EXISTS/NOT EXISTS subqueries that join through the junction table.
Both correlation sides are correctly threaded:
- junction→target: JOIN junction ON junction.childColumns = target.targetColumns
- junction→parent: WHERE junction.parentColumns = parent.{localFields→columns}
(parent anchor columns resolved via resolveFieldToColumn, mirroring slice-1
read path in buildManyToManyJunctionArtifacts)
Shapes:
- some → EXISTS(SELECT 1 FROM target JOIN junction ON <j→t> WHERE <j→parent> [AND pred])
- none → NOT EXISTS(… [AND pred])
- every → NOT EXISTS(… AND NOT(pred)); vacuously true (AndExpr.true()) when no pred
Composite keys are AND-ed across all column pairs via buildPairedColumnExprs.
A hasThrough type guard narrows ResolvedModelRelation at the dispatch site,
keeping the narrowed type in buildManyToManyExistsExpr explicit without bare casts.
Unit tests cover single-key and composite-key junction shapes for all three
modes, plus AND-ed predicate variants and the vacuous-true edge case.
FK relation filter tests are unaffected.
Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…e/every)
Add PGlite integration tests for User.tags M:N filter operators. Tests
seed users/tags/junction rows via existing runtime-helpers and assert the
exact filtered user set as whole rows (toEqual), covering:
- some: users with ≥1 matching tag; multiple users; single match
- none: users with no matching tag (including tag-less users)
- every: all tags match + vacuous case (no-tags user qualifies) +
partial-match exclusion
- empty-match edge: some/none/every against a predicate no tag satisfies
- implicit selection: one test without .select asserts full default row shape
Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
… (TML-2786) Filter slice orchestrator artifacts (filter-code dispatch took 2 rounds incl. a truncation recovery; integration-tests dispatch one round). Review log gitignored. Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…05 rebase The EXISTS-through-junction subquery built bare table sources, which no longer compiled (main dropped the raw TableSource import) and rendered unqualified SQL. Qualify the target via tableSourceForContract and the junction via the carried through.namespaceId. Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…contract helper resolveThrough now requires the contract through block to carry the junction's namespaceId; without it the relation resolves as non-M:N and the filter EXISTS tests assert the wrong shape. Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…er TML-2841 rebase buildManyToManyExistsExpr now takes parentNamespaceId; resolveFieldToColumn, toRelationWhereExpr, and tableSourceForContract gained namespace coordinates. Pass parentNamespaceId for the junction-correlation columns and relation.toNamespace for the target side; thread the namespace in the filter tests. Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
1ef949e to
6cfb1ac
Compare
Replace the contractWithProjectRelatedThrough helper, which patched the raw through metadata on the test contract, with direct unit tests of the buildPairedColumnExprs guard. The authoring surface already rejects mismatched many-to-many field counts at lowering time, so malformed through metadata cannot be produced by any user-facing surface; the guards are defense-in-depth and are now exercised with their own typed inputs instead of a forged contract. Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
Tests must never patch raw contract data structures. Use real emitted fixtures, or generate contracts at runtime only from a high-level representation made with a user-facing authoring surface; for scenarios the authoring surface rejects, test the defensive guard directly with its own typed inputs. Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
Slice 3 (final) of the **SQL ORM: Many-to-Many End to End** project ([Linear project](https://linear.app/prisma-company/project/sql-orm-many-to-many-end-to-end-c178df40ca3a)). Nested `connect`/`disconnect`/`create` through the junction + the required-payload safety rail. > **Stacked PR.** Base `tml-2786` (prisma#680) → `tml-2785` (prisma#679) → `tml-2784` (prisma#678) → `tml-2597` (prisma#673) → `tml-2729` (prisma#667) → `main`. Review/merge bottom-up. ## Overview `db.orm.User.update/create({ tags: (t) => t.connect/disconnect/create(...) })` now routes to the `UserTag` junction (INSERT / DELETE / target-insert+link), under both `create()` and `update()`. The `N:M not supported yet` guard is gone. Junctions with a **required non-FK payload column** cant be written through the sugar, so `create` **and** `connect` on them are disabled at both the type level and runtime with a clear error (disconnect stays). ## Changes - **Runtime junction write path:** `partitionByOwnership` gains a `junctionOwned` bucket (keyed on `through` presence); connect→INSERT, disconnect→DELETE, create→target-insert+link, both flows, composite-key AND-ed; the rejection unit test flipped positive. (`getRelationDefinitions` now carries `through`.) - **Required-payload fixture:** `User ↔ Role` via `UserRole(user_id, role_id, level NOT NULL)` (canonical CLI emit). - **Runtime guard:** nested `create` **and** `connect` on a required-payload junction throw (connect also INSERTs a junction row it cant complete → DB NOT-NULL violation). Disconnect stays allowed. - **Type-level gate:** `HasRequiredJunctionPayload` + `HasJunctionThrough` compose `LinkWritesDisabled` and `BareDisconnectDisabled` on `RelationMutator`, disabling `create`/`connect` and bare `disconnect()` at the type level for required-payload junctions. The `.d.ts` emitter now carries `through` (namespace-scoped), so the gate derives required-payload columns from the junction model's field types without `any`. Covered by type tests (`junction-link-write-disable.test-d.ts`). - **Error handling:** `isUniqueConstraintViolation` uses driver-normalized `SqlQueryError.sqlState`; duplicate-connect wraps with a domain error naming the junction; shared-column conflicts detected on both INSERT and DELETE sides; metadata-length assertions fail fast; preflight detects duplicate resolved targets. - **Namespace scoping:** `MutationDefaultsOptions` carries `namespace`; `ModelNameForTable` and `JunctionPayloadFieldNames` are namespace-aware; execution-default and storage-default columns are excluded from `requiredPayloadColumns`. - **Transaction safety:** ORM mutations run inside a transaction via `withMutationScope`. ## Integration tests (per the project standard) `mn-nested-write.test.ts` — connect/create/disconnect on the pure `User.tags` junction and the required-payload `User.roles` junction, both `create()` and `update()` flows; duplicate-connect rejection; missing-target rejection; parent-insert-failure-after-connect-preflight (no partial writes); execution-defaulted junction payload column; bare `disconnect()` type error on junctions; whole-row `toEqual`, explicit `.select` in most, ≥1 implicit/default selection. ## AC status - ✅ **AC-1** — connect/disconnect/create route to junction DML, both flows, guard removed, rejection test flipped (unit + integration). - ✅ **AC-2** — Runtime disable of `create`+`connect` on required-payload junctions + type-level disable (`create`/`connect` → `never`, bare `disconnect()` → type error on junctions). Both implemented and tested. - ✅ **AC-3** — write integration tests per the standard. ## Notes `connect`-disabled-on-required-payload was a mid-flight spec correction (the original spec wrongly assumed connect was FK-pair-only safe). Duplicate `connect` errors deliberately rather than silently succeeding (intentional divergence from Prisma-classic implicit-M:N `connect`, which is idempotent via `ON CONFLICT DO NOTHING`). The reverse `Tag.users`/`Role.users` directions are deferred (one-directional fixture, decision prisma#3). Refs: TML-2787. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Enabled many-to-many nested mutations via junction tables when junction metadata is available, including `create`, `connect`, and `disconnect`. * Added compile-time and runtime protections to prevent creating/connecting junction links when the junction has required payload fields. * **Bug Fixes** * Improved unique-constraint error detection for more consistent handling (based on SQLSTATE). * **Tests** * Expanded unit and integration coverage for junction-based M:N nested writes, junction payload validation, and correct junction DML behavior. * **Chores** * Updated generated contract and example artifacts to use namespace-qualified execution-default references. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
Slice 2 of the SQL ORM: Many-to-Many End to End project (Linear project). Filters an M:N relation through its junction.
Overview
db.orm.User.filter((u) => u.tags.some/every/none((t) => …))now emits an EXISTS / NOT EXISTS subquery that walks theUserTagjunction. PreviouslybuildJoinWhereread onlyrelation.on.localFields/targetFields, so an M:N filter produced a wrong-shape EXISTS that skipped the junction.Changes (2 commits)
f9226ccb9—model-accessor.ts:buildManyToManyExistsExprbuilds the two-sided junction correlation — junction→target (through.childColumns = target.targetColumns) and junction→parent (through.parentColumns = parent.{on.localFields resolved}, mirroring slice 1s read correlation), composite-key AND-ed. Shapes:some=EXISTS,none=NOT EXISTS,every=NOT EXISTS(… AND NOT(pred)), vacuousevery({})=AndExpr.true()(consistent with the FKeverypath). Dispatch via ahasThroughtype predicate (no bare cast). 6 AST unit tests.e65a9db43— 9 integration tests (PGlite).Integration tests (per the project standard)
Whole-row
toEqualon the filtered user set; 8/9 use explicit.select; test 6 uses implicit/default selection. Coverssome,none,every(incl. the vacuous tag-less-user-qualifies case, tested in isolation and alongside partial-match exclusion), and empty-match edges for all three operators.Why
Second of the three relation-shaped M:N consumers over slice 0s shared
throughprimitive. The filter correlation mirrors slice 1s read correlation for consistency.Scope / notes
Filter only — write (TML-2787) is the last slice. No fixture change (reuses slice 1s
User ↔ Tag+ its seed helpers). No production change in the test dispatch. Broad integration runs show pre-existing PGlite/WASM JIT flakiness (logged); the M:N filter tests pass on targeted runs.Refs: TML-2786.
Summary by CodeRabbit
New Features
Tests
Documentation