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

TML-2597: SQL ORM many-to-many — project spec + plan - #673

Merged
aqrln merged 1 commit into
mainfrom
tml-2597-sql-orm-complete-end-to-end-many-to-many-support-include
Jun 3, 2026
Merged

aqrln merged 1 commit into
mainfrom
tml-2597-sql-orm-complete-end-to-end-many-to-many-support-include

Conversation

@tensordreams

Copy link
Copy Markdown
Contributor

Shaping artifacts for the SQL ORM: Many-to-Many End to End project. No code changes — projects/sql-orm-many-to-many/ only (spec, plan, README, trace).

Stacked on #667 (TML-2729, correlated-only read path). Review/merge that first; this PR is based on its branch, not main.

What this adds

  • spec.md — system-level intent: restore the relation-shaped ORM API (include / filter / nested write) over M:N, so users stop hand-wiring explicit junction models and the Pothos plugin stops rejecting M:N at build.
  • plan.md — 4 slices: slice 0 (contract + resolver foundation) gates a parallel fan-out of read / filter / write.

Key decisions captured

  • The ticket was stale. Its Phase 1/2 (LATERAL path, multi-query fallback) were deleted by TML-2729: drop LATERAL include codegen for correlated-only read path #667 (TML-2729) and TML-2657. The work now extends the correlated builder; there is no LATERAL or fallback path to teach.
  • Surprise found while shaping: an emitted M:N contract does not validate today — the relation validator rejects cardinality: N:M and the undeclared through key. Slice 0 closes that; it is a real gap, not prep.
  • Representation: a uniform through descriptor on the single shared resolver, consumed three ways (not junction-as-nested-include, which does not generalise to filter/write).
  • Scope: write vocabulary is the three kinds that exist (connect/disconnect/create); nested update/upsert/delete/set are out of scope → TML-2781.

Linear

Promoted from TML-2597 to a dedicated Linear Project (SQL ORM: Many-to-Many End to End). Slices: TML-2784 (0) / TML-2785 (1) / TML-2786 (2) / TML-2787 (3).

Scope statement

Planning artifacts only. No package code, no fixtures, no behavior change. Refs: TML-2597.

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

coderabbitai Bot commented Jun 1, 2026 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Review was skipped due to path filters

⛔ Files ignored due to path filters (4)
  • projects/sql-orm-many-to-many/README.md is excluded by !projects/**
  • projects/sql-orm-many-to-many/plan.md is excluded by !projects/**
  • projects/sql-orm-many-to-many/spec.md is excluded by !projects/**
  • projects/sql-orm-many-to-many/trace.jsonl is excluded by !projects/**

CodeRabbit blocks several paths by default. You can override this behavior by explicitly including those paths in the path filters. For example, including **/dist/** will override the default block on the dist directory, by removing the pattern from both the lists.

⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: 85c98717-6d8d-4529-a1e6-77c9435be0d5

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch tml-2597-sql-orm-complete-end-to-end-many-to-many-support-include

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.

@tensordreams
tensordreams force-pushed the tml-2729-sql-orm-drop-lateral-for-includes-in-favour-of-correlated branch from 72db66a to 291bb99 Compare June 2, 2026 12:53
@tensordreams
tensordreams force-pushed the tml-2597-sql-orm-complete-end-to-end-many-to-many-support-include branch from 90cf526 to 669c230 Compare June 2, 2026 13:07
Base automatically changed from tml-2729-sql-orm-drop-lateral-for-includes-in-favour-of-correlated to main June 2, 2026 13:10
An error occurred while trying to automatically change base from tml-2729-sql-orm-drop-lateral-for-includes-in-favour-of-correlated to main June 2, 2026 13:10
@tensordreams
tensordreams force-pushed the tml-2597-sql-orm-complete-end-to-end-many-to-many-support-include branch from 669c230 to 433e9bb Compare June 3, 2026 08:51
@github-actions

github-actions Bot commented Jun 3, 2026

Copy link
Copy Markdown

size-limit report 📦

Path Size
postgres / no-emit 137.29 KB (0%)
postgres / emit 108.81 KB (0%)
mongo / no-emit 75.77 KB (0%)
mongo / emit 70.78 KB (0%)
cf-worker / no-emit 166.3 KB (0%)
cf-worker / emit 134.51 KB (0%)

@pkg-pr-new

pkg-pr-new Bot commented Jun 3, 2026

Copy link
Copy Markdown

Open in StackBlitz

@prisma-next/extension-author-tools

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

@prisma-next/mongo-runtime

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

@prisma-next/family-mongo

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

@prisma-next/sql-runtime

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

@prisma-next/family-sql

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

@prisma-next/extension-arktype-json

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

@prisma-next/middleware-cache

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

@prisma-next/mongo

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

@prisma-next/extension-paradedb

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

@prisma-next/extension-pgvector

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

@prisma-next/extension-postgis

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

@prisma-next/postgres

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

@prisma-next/sql-orm-client

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

@prisma-next/sqlite

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

@prisma-next/target-mongo

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

@prisma-next/adapter-mongo

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

@prisma-next/driver-mongo

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

@prisma-next/contract

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

@prisma-next/utils

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

@prisma-next/config

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

@prisma-next/errors

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

@prisma-next/framework-components

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

@prisma-next/operations

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

@prisma-next/ts-render

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

@prisma-next/contract-authoring

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

@prisma-next/ids

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

@prisma-next/psl-parser

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

@prisma-next/psl-printer

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

@prisma-next/cli

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

@prisma-next/cli-telemetry

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

@prisma-next/emitter

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

@prisma-next/migration-tools

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

prisma-next

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

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

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

@prisma-next/mongo-codec

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

@prisma-next/mongo-contract

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

@prisma-next/mongo-value

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

@prisma-next/mongo-contract-psl

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

@prisma-next/mongo-contract-ts

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

@prisma-next/mongo-emitter

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

@prisma-next/mongo-schema-ir

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

@prisma-next/mongo-query-ast

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

@prisma-next/mongo-orm

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

@prisma-next/mongo-query-builder

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

@prisma-next/mongo-lowering

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

@prisma-next/mongo-wire

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

@prisma-next/sql-contract

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

@prisma-next/sql-errors

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

@prisma-next/sql-operations

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

@prisma-next/sql-schema-ir

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

@prisma-next/sql-contract-psl

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

@prisma-next/sql-contract-ts

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

@prisma-next/sql-contract-emitter

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

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

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

@prisma-next/sql-relational-core

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

@prisma-next/sql-builder

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

@prisma-next/target-postgres

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

@prisma-next/target-sqlite

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

@prisma-next/adapter-postgres

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

@prisma-next/adapter-sqlite

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

@prisma-next/driver-postgres

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

@prisma-next/driver-sqlite

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

commit: 433e9bb

Shape the end-to-end many-to-many project: spec + 4-slice plan
(0 contract+resolver foundation, gating parallel read/filter/write).
Promoted from TML-2597 to a dedicated Linear Project; slices
TML-2784..2787. No code changes — planning artifacts only.

Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
@tensordreams
tensordreams force-pushed the tml-2597-sql-orm-complete-end-to-end-many-to-many-support-include branch from 433e9bb to c350460 Compare June 3, 2026 11:32
@aqrln
aqrln enabled auto-merge (rebase) June 3, 2026 11:37
@aqrln
aqrln merged commit c6ff88a into main Jun 3, 2026
19 checks passed
@aqrln
aqrln deleted the tml-2597-sql-orm-complete-end-to-end-many-to-many-support-include branch June 3, 2026 11:37
paulwer pushed a commit to paulwer/prisma-next that referenced this pull request Jun 11, 2026
…risma#679)

Slice 1 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)).
Reads an M:N relation through its junction.

> **Stacked PR.** Base is `tml-2784` (prisma#678, slice 0) → `tml-2597` (prisma#673)
→ `tml-2729` (prisma#667) → `main`. Review/merge bottom-up.

## Overview

`db.orm.User.include(tags)` now resolves a many-to-many relation to `{
…user, tags: Tag[] }` in a **single correlated subquery** that walks
parent → junction → target — no `LATERAL`, no second query. Built on
slice 0s `ResolvedRelation.through`.

## Changes (4 commits)

- **`fcecac5b3`** — integration fixture gains a `User ↔ Tag` M:N
relation via a `UserTag` junction (composite PK `user_id`/`tag_id`);
`contract.json`/`.d.ts` re-emitted.
- **`e587b433c`** — read path: `IncludeExpr.through` (surfaced by
`resolveIncludeRelation`), and `buildCorrelatedIncludeProjection` gains
an M:N branch — `buildManyToManyJunctionArtifacts` builds a non-LATERAL
inner join to the junction (`junction.childColumns =
target.targetColumns`) correlated to the parent (`junction.parentColumns
= parent` anchor), composite-key AND-ed; FK decode path reused.
Unit-tested at the AST level.
- **`b9c3e9f7b`** — replace 2 bare `as` casts with `castAs`; add the
missing M:N + distinct + non-leaf unit test.
- **`d3232cbad`** — 7 integration tests (PGlite).

## Integration tests (per the project standard)

Whole-row `toEqual`; 6/7 use explicit `.select(...)` (so adding a model
field wont churn assertions); **test 5 uses implicit/default selection**
(full `User` + `tags: Tag[]` shape); a **single-execution /
no-`LATERAL`** assertion; depth-2 nesting (`invitedUsers → tags`); edges
(user with no tags → `tags: []`; a tag shared by multiple users).

## Why

This is the first of the three relation-shaped M:N consumers (read /
filter / write) over slice 0s shared `through` primitive. The
correlated-only approach matches the post-TML-2729 read path (no LATERAL
to reintroduce).

## Scope / notes

Read only — filter (TML-2786) and write (TML-2787) are later slices. The
fixture is **one-directional** (`User.tags`; reverse `Tag.users`
deferred — adding it trips a latent create-overload type fragility in
unrelated mutation-defaults tests; see the projects unattended-decisions
log). Fixture re-emit used a `tsx` bypass because the CLI `contract
emit` fails on a sandbox config-load env issue — **CI `fixtures:check`
is the real golden-stability gate**; please confirm its green (or re-run
the canonical emit). Broad integration runs show pre-existing
PGlite/WASM JIT flakiness; the M:N tests pass on targeted runs.

Refs: TML-2785.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
* include(...) now supports many-to-many (M:N) relationships via
junction tables, returning correct nested arrays and preserving
single-query execution.

* **Tests**
* Added unit and integration tests covering M:N includes, composite
keys, nested includes, distinct+nested scenarios, and end-to-end result
shape correctness.

* **Documentation**
* Added upgrade notes for 0.14 describing the runtime support for M:N
correlated include reads.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
paulwer pushed a commit to paulwer/prisma-next that referenced this pull request Jun 15, 2026
…e junction (prisma#680)

Slice 2 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)).
Filters an M:N relation through its junction.

> **Stacked PR.** Base is `tml-2785` (prisma#679, slice 1) → `tml-2784` (prisma#678)
→ `tml-2597` (prisma#673) → `tml-2729` (prisma#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.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## 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.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
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