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

TML-2786: M:N slice 2 — relation filters (some/every/none) through the junction - #680

Merged
aqrln merged 12 commits into
mainfrom
tml-2786-slice-2-filter
Jun 12, 2026
Merged

aqrln merged 12 commits into
mainfrom
tml-2786-slice-2-filter

Conversation

@tensordreams

@tensordreams tensordreams commented Jun 1, 2026 •

Copy link
Copy Markdown
Contributor

Slice 2 of the SQL ORM: Many-to-Many End to End project (Linear project). Filters an M:N relation through its junction.

Stacked PR. Base is tml-2785 (#679, slice 1) → tml-2784 (#678) → tml-2597 (#673) → tml-2729 (#667) → main. Review/merge bottom-up.

Overview

db.orm.User.filter((u) => u.tags.some/every/none((t) => …)) now emits an EXISTS / NOT EXISTS subquery that walks the UserTag junction. Previously buildJoinWhere read only relation.on.localFields/targetFields, so an M:N filter produced a wrong-shape EXISTS that skipped the junction.

Changes (2 commits)

  • f9226ccb9 — model-accessor.ts: buildManyToManyExistsExpr builds 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)), vacuous every({})=AndExpr.true() (consistent with the FK every path). Dispatch via a hasThrough type predicate (no bare cast). 6 AST unit tests.
  • e65a9db43 — 9 integration tests (PGlite).

Integration tests (per the project standard)

Whole-row toEqual on the filtered user set; 8/9 use explicit .select; test 6 uses implicit/default selection. Covers some, 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 through primitive. 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

    • Many-to-many relation filters now supported: use tags.some(...), tags.none(...), and tags.every(...) on M:N relations with correct EXISTS/NOT EXISTS semantics.
  • Tests

    • Added unit and integration tests covering M:N filters, composite-key and self-referential joins, vacuous-every behavior, and error cases for invalid junction metadata.
  • Documentation

    • Upgrade notes updated to mention M:N relation filter support.

@tensordreams
tensordreams requested a review from a team as a code owner June 1, 2026 19:41
@coderabbitai

coderabbitai Bot commented Jun 1, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

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

Use the following commands to manage reviews:

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

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This PR implements M:N relation filters by detecting through-backed relations and lowering some/none/every into correlated EXISTS/NOT EXISTS subqueries that join through the junction table; it adds builders, helpers, typed accessor adjustments, unit and integration tests, and an upgrade note.

Changes

Many-to-many relation filtering implementation

Layer / File(s) Summary
Type system and through-metadata detection
packages/3-extensions/sql-orm-client/src/model-accessor.ts
Introduces ResolvedModelRelationWithThrough typing and expands relational-core AST imports for join/projection/select/table-source primitives.
Relation proxy wiring (relationName)
packages/3-extensions/sql-orm-client/src/model-accessor.ts
Updates relation accessor proxy to forward relationName into createRelationFilterAccessor and threads it into buildExistsExpr.
M:N EXISTS query construction and planning
packages/3-extensions/sql-orm-client/src/model-accessor.ts
Refactors buildExistsExpr to detect through relations and delegate to buildManyToManyExistsExpr; adds planRelationFilterMode, buildPairedColumnExprs, remapColumnRefs, and replaces inline EXISTS/NOT-EXISTS branching with a filter plan emitter.
Type-safe casting improvements in accessors
packages/3-extensions/sql-orm-client/src/model-accessor.ts
Refactors createScalarFieldAccessor, createExtensionMethodFactory, and toRelationWhereExpr shorthand handling to use blindCast-typed proxies for stronger local typing.
Unit tests for M:N filtering
packages/3-extensions/sql-orm-client/test/model-accessor.test.ts
Adds tests asserting generated EXISTS/NOT EXISTS subquery AST shapes for junction from/joins, correlated where, predicate AND-correlation, vacuous every({}), composite-key joins, aliasing, and error cases for join metadata.
Integration tests for M:N relation filtering
test/integration/test/sql-orm-client/mn-filter.test.ts
End-to-end tests seeding users, tags, and user_tags verifying tags.some/tags.none/tags.every semantics, selection shape, and edge-case predicate matching behaviors.
Extension upgrade documentation
skills/extension-author/prisma-next-extension-upgrade/upgrades/0.13-to-0.14/instructions.md
Adds TML-2786 note documenting the internal runtime change enabling M:N relation filters via EXISTS subqueries with no API/contract change.

Sequence Diagram

sequenceDiagram
  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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • prisma/prisma-next#678: Adds and validates through metadata on N:M relations which this change consumes for M:N filtering.

Suggested reviewers

  • aqrln

Poem

🐰 In tunnels of tables and columns that meet,

I hop through the junction to make filters neat.
With EXISTS and NOT, I pair keys with a grin,
Some, none, every — the logic fits in.
A rabbit-approved query — precise and succinct!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 22.22% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly and concisely describes the main change: implementing M:N relation filters (some/every/none) through junction tables, which is the core focus of the changeset.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch tml-2786-slice-2-filter

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions

github-actions Bot commented Jun 1, 2026 •

Copy link
Copy Markdown

size-limit report 📦

Path Size
postgres / no-emit 154.9 KB (+0.29% 🔺)
postgres / emit 122.13 KB (+0.38% 🔺)
mongo / no-emit 76.83 KB (0%)
mongo / emit 70.95 KB (0%)
cf-worker / no-emit 183.49 KB (0%)
cf-worker / emit 147.45 KB (0%)

@pkg-pr-new

pkg-pr-new Bot commented Jun 1, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@prisma-next/extension-author-tools

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

@prisma-next/mongo-runtime

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

@prisma-next/family-mongo

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

@prisma-next/sql-runtime

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

@prisma-next/family-sql

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

@prisma-next/extension-arktype-json

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

@prisma-next/middleware-cache

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

@prisma-next/mongo

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

@prisma-next/extension-paradedb

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

@prisma-next/extension-pgvector

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

@prisma-next/extension-postgis

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

@prisma-next/postgres

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

@prisma-next/sql-orm-client

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

@prisma-next/sqlite

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

@prisma-next/extension-supabase

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/extension-supabase@680

@prisma-next/target-mongo

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

@prisma-next/adapter-mongo

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

@prisma-next/driver-mongo

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

@prisma-next/contract

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

@prisma-next/utils

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

@prisma-next/config

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

@prisma-next/errors

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

@prisma-next/framework-components

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

@prisma-next/operations

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

@prisma-next/ts-render

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

@prisma-next/contract-authoring

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

@prisma-next/ids

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

@prisma-next/psl-parser

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

@prisma-next/psl-printer

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

@prisma-next/cli

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

@prisma-next/cli-telemetry

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

@prisma-next/emitter

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

@prisma-next/migration-tools

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

prisma-next

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

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

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

@prisma-next/mongo-codec

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

@prisma-next/mongo-contract

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

@prisma-next/mongo-value

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

@prisma-next/mongo-contract-psl

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

@prisma-next/mongo-contract-ts

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

@prisma-next/mongo-emitter

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

@prisma-next/mongo-schema-ir

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

@prisma-next/mongo-query-ast

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

@prisma-next/mongo-orm

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

@prisma-next/mongo-query-builder

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

@prisma-next/mongo-lowering

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

@prisma-next/mongo-wire

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

@prisma-next/sql-contract

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

@prisma-next/sql-errors

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

@prisma-next/sql-operations

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

@prisma-next/sql-schema-ir

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

@prisma-next/sql-contract-psl

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

@prisma-next/sql-contract-ts

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

@prisma-next/sql-contract-emitter

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

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

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

@prisma-next/sql-relational-core

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

@prisma-next/sql-builder

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

@prisma-next/target-postgres

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

@prisma-next/target-sqlite

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

@prisma-next/adapter-postgres

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

@prisma-next/adapter-sqlite

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

@prisma-next/driver-postgres

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

@prisma-next/driver-sqlite

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

commit: 5e11ddd

@tensordreams
tensordreams force-pushed the tml-2785-slice-1-correlated-read branch from 4ee6af6 to 78affcf Compare June 2, 2026 12:39
@tensordreams
tensordreams force-pushed the tml-2786-slice-2-filter branch from 92d1741 to 25a3c7e Compare June 2, 2026 12:40
@tensordreams
tensordreams force-pushed the tml-2785-slice-1-correlated-read branch from 78affcf to e4e3004 Compare June 2, 2026 13:07
@tensordreams
tensordreams force-pushed the tml-2786-slice-2-filter branch 2 times, most recently from 06fc270 to bc2d4b9 Compare June 3, 2026 08:51
@tensordreams
tensordreams force-pushed the tml-2785-slice-1-correlated-read branch 2 times, most recently from 9e24a8b to ed06084 Compare June 3, 2026 11:32
@tensordreams
tensordreams force-pushed the tml-2786-slice-2-filter branch 2 times, most recently from 3982e13 to b1dadcf Compare June 4, 2026 15:12
@tensordreams
tensordreams force-pushed the tml-2785-slice-1-correlated-read branch from ed06084 to 38bcb74 Compare June 4, 2026 15:12
@tensordreams
tensordreams force-pushed the tml-2786-slice-2-filter branch from b1dadcf to df900cd Compare June 4, 2026 15:41
@tensordreams
tensordreams force-pushed the tml-2785-slice-1-correlated-read branch from 38bcb74 to c32cd78 Compare June 4, 2026 15:41
@tensordreams
tensordreams force-pushed the tml-2786-slice-2-filter branch from df900cd to ee44053 Compare June 5, 2026 12:44
@tensordreams
tensordreams force-pushed the tml-2785-slice-1-correlated-read branch 2 times, most recently from b7c8ede to c73f70b Compare June 5, 2026 14:21
@tensordreams
tensordreams force-pushed the tml-2786-slice-2-filter branch 2 times, most recently from 65d4fe3 to bd47c00 Compare June 5, 2026 15:02
@tensordreams
tensordreams force-pushed the tml-2785-slice-1-correlated-read branch 2 times, most recently from 7e21c60 to f383943 Compare June 8, 2026 10:19
@tensordreams
tensordreams force-pushed the tml-2786-slice-2-filter branch 3 times, most recently from 2807fb8 to f1c6a5d Compare June 8, 2026 14:46
@tensordreams
tensordreams force-pushed the tml-2785-slice-1-correlated-read branch from a36b0d5 to 07aa1cf Compare June 8, 2026 14:46
@tensordreams
tensordreams force-pushed the tml-2786-slice-2-filter branch from f1c6a5d to 840a6b3 Compare June 8, 2026 16:45
@tensordreams
tensordreams force-pushed the tml-2785-slice-1-correlated-read branch from 07aa1cf to 12ec127 Compare June 8, 2026 16:45
Base automatically changed from tml-2785-slice-1-correlated-read to main June 10, 2026 14:50
@tensordreams
tensordreams force-pushed the tml-2786-slice-2-filter branch from f159866 to 2828012 Compare June 10, 2026 15:26

@tensordreams tensordreams left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 tensordreams left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]>
@tensordreams
tensordreams force-pushed the tml-2786-slice-2-filter branch from 1ef949e to 6cfb1ac Compare June 12, 2026 11:07
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]>
@aqrln
aqrln enabled auto-merge June 12, 2026 12:30
@aqrln
aqrln added this pull request to the merge queue Jun 12, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Jun 12, 2026
@aqrln
aqrln added this pull request to the merge queue Jun 12, 2026
Merged via the queue into main with commit 00eeeaf Jun 12, 2026
20 checks passed
@aqrln
aqrln deleted the tml-2786-slice-2-filter branch June 12, 2026 13:06
paulwer pushed a commit to paulwer/prisma-next that referenced this pull request Jun 21, 2026
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]>
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants