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

TML-2794: M:N slice 5 — PSL authors many-to-many (junction → N:M + through) - #819

Merged
aqrln merged 22 commits into
mainfrom
tml-2794-slice-5-psl-mn-authoring
Jun 22, 2026
Merged

aqrln merged 22 commits into
mainfrom
tml-2794-slice-5-psl-mn-authoring

Conversation

@tensordreams

@tensordreams tensordreams commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

Slice 5 of the SQL ORM: Many-to-Many End to End project (follow-on group). Refs TML-2794.

Stacked PR — base is tml-2790-mn-demo-examples (#742, slice 4); below that tml-2787-slice-3-write (#683) → main.

Overview

PSL could not author a navigable many-to-many relation: the relation resolver emitted only N:1/1:N, and a bare list field (tags Tag[]) with no FK pair was diagnosed as PSL_ORPHANED_BACKRELATION_LIST — cardinality: 'N:M' + through existed only via the TS contract builder. This PR teaches the PSL interpreter explicit-junction recognition (form 1, pinned at pickup): when a bare list field has a recognisable junction model — composite @@id([a, b]) covering exactly the FK columns of two N:1 relations to the two side models — the list lowers to a navigable N:M relation through that junction, shape-identical to rel.manyToMany output.

Changes

  • psl-relation-resolution.ts: junction recognition in the previously-orphaned branch — findJunctionFkPairs + id-coverage gate + manyToManyRelationNode; child FK must reference the target's full id (set-equal), through.childColumns reordered to id order (the runtime joins childColumns[i] = targetColumns[i] by index); decline → existing orphaned diagnostic. Self-referential M:N disambiguated by the list's @relation name (pins the parent-side FK); unnamed symmetric lists get the ambiguity diagnostic. Surrogate-id join models are deliberately not recognised. Direct FK matches still win (stay 1:N).
  • 10 lowering unit tests (interpreter.relations.many-to-many.test.ts): both directions, composite keys, swapped-order FK references, self-referential, diagnostic preservation, validateContract round-trip.
  • PSL-authored integration fixture fixtures/mn-psl/ (User ↔ Tag via user_tags, mirroring the TS fixture) wired into the sql-orm-client emit pipeline so fixtures:check regenerates and diffs it.
  • mn-psl-parity.test.ts: 8 integration tests proving the full M:N ORM API (include explicit+implicit, some/none/every, connect, disconnect, nested create) against the PSL-emitted contract.

Why

The PG demo emits its contract from PSL, so it cannot show the M:N API until PSL can author it (slice 6 is blocked on this). Form 1 was chosen over Prisma-style implicit lists as the smallest surface that matches the existing diagnostic's guidance; implicit lists remain a clean follow-up.

Scope

PSL authoring layer + fixtures/tests only. No sql-orm-client runtime changes, no TS-builder changes, no demo changes (slice 6). Implicit-list authoring (form 2) deliberately excluded.

Summary by CodeRabbit

  • New Features

    • Improved many-to-many backrelation lowering via explicit junction models, including composite-key support and correct through/column ordering.
    • Enhanced FK/backrelation metadata to improve many-to-many resolution across namespaces.
  • Bug Fixes / Improvements

    • Added richer diagnostics for orphaned, ambiguous, and invalid many-to-many junction scenarios.
    • Strengthened full SQL contract validation for N:M through configurations (pairing, referenced column existence, and storage-type consistency).
  • Tests

    • Added unit tests for many-to-many lowering and diagnostics.
    • Added integration parity coverage for includes, filters, and nested writes using the mn-psl fixture.
  • Documentation / Chores

    • Updated Prisma Next emit flow and refreshed mn-psl fixture typing for UUID-style IDs.

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

coderabbitai Bot commented Jun 12, 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
  • ✅ Review completed - (🔄 Check again to review again)
📝 Walkthrough

Walkthrough

Extends the PSL interpreter to detect explicit junction models and emit N:M relation nodes with through-table and column metadata. indexFkRelations gains a new fkRelationsByDeclaringModel index; applyBackrelationCandidates uses it to resolve bare list fields via junction pairs or emit ambiguity/orphan diagnostics. A new validation step ensures through-table column arrays are length-consistent and types match. An mn-psl fixture and ORM parity integration tests validate the feature end-to-end.

Changes

M:N PSL junction resolution and ORM parity

Layer / File(s) Summary
FK index extension and interpreter wiring
packages/2-sql/2-authoring/contract-psl/src/interpreter.ts, packages/2-sql/2-authoring/contract-psl/src/psl-relation-resolution.ts
FkRelationMetadata adds optional declaringNamespaceId; indexFkRelations returns fkRelationsByDeclaringModel keyed by declaring model name; the interpreter derives modelIdColumns from modelNodes primary keys and passes both new maps into applyBackrelationCandidates.
Junction-pair detection and N:M relation construction
packages/2-sql/2-authoring/contract-psl/src/psl-relation-resolution.ts
Introduces JunctionFkPair/JunctionNearMiss types and helpers to verify FK/id-column coverage and reorder child junction columns into target id-column order. findJunctionFkPairs searches using declaring/target model names and optional relation-name pinning. manyToManyRelationNode constructs N:M metadata. relationsForModel centralizes per-model array initialization. applyBackrelationCandidates gains N:M branch: one junction pair → N:M node; multiple → ambiguity diagnostic; zero → orphan or junction-specific diagnostic. The 1:N path refactored to use relationsForModel.
M:N relation through-table validation
packages/2-sql/1-core/contract/src/validators.ts, packages/2-sql/1-core/contract/test/validators.test.ts
Adds validateRelationThroughConsistency to enforce positional array-length invariants for N:M relations: through.parentColumns.length matches on.localFields.length; through.childColumns.length matches through.targetColumns.length. Validates column existence in storage tables and enforces storage-type matching per paired column. Integrated into validateSqlContractFully. Comprehensive test coverage for consistent, length-mismatched, missing-column, type-mismatch, and field-to-column resolution cases.
Unit tests for M:N interpreter behavior
packages/2-sql/2-authoring/contract-psl/test/interpreter.relations.many-to-many.test.ts, packages/2-sql/2-authoring/contract-psl/test/interpreter.namespaces.test.ts
Vitest suite covering bare-list junction lowering into N:M relations, composite-key through derivation, FK reference reordering to target id-column order, self-referential disambiguation by relation name, and diagnostic cases for non-@id unique references, missing junctions, uncovered @@id, and ambiguous lists. Also validates explicit junction preservation as 1:N/N:1 relations and direct-FK precedence over junction recognition. Cross-namespace backrelation metadata validation included.
Integration fixture schema, config, emit wiring, and ORM parity tests
test/integration/test/sql-orm-client/fixtures/mn-psl/contract.prisma, test/integration/test/sql-orm-client/fixtures/mn-psl/prisma-next.config.ts, packages/3-extensions/sql-orm-client/package.json, skills/extension-author/prisma-next-extension-upgrade/upgrades/0.14-to-0.15/instructions.md, test/integration/test/sql-orm-client/fixtures/contract.ts, test/integration/test/sql-orm-client/fixtures/execution-defaulted-tags/contract.ts, test/integration/test/sql-orm-client/mn-psl-parity.test.ts
Adds User, Tag, and UserTag junction fixture schema with composite @@id aligned to FK columns and @@map table mapping. Prisma Next config points to contract and output path. Updates sql-orm-client emit script to invoke contract emit for mn-psl fixture. Documents fixture as test infrastructure in upgrade notes. Aligns fixture contract templates to use charColumn(36) for UUID junction foreign-key fields. Deserializes PSL-authored contract at load time and constructs shared Postgres ExecutionContext with pgvector extension. Covers include projections (explicit and implicit select), relation filters (some/none/every including vacuous truth for users without tags), and nested writes (connect/disconnect/create) on tags M:N relation with direct SQL readback against user_tags junction table.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~75 minutes

Suggested reviewers

  • wmadden
  • aqrln

Poem

🐇 Through junction tables the rabbits hop,
From bare lists to N:M they don't stop.
fkRelationsByDeclaringModel maps the way,
through columns reordered, hip-hip-hooray!
The ORM connects, disconnects, and creates—
Many-to-many behind junction gates! 🎉

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 60.00% 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 PR title accurately summarizes the main change: PSL now supports authoring many-to-many relations through explicit junction models (converting junction models to N:M relations with 'through' descriptors).
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-2794-slice-5-psl-mn-authoring

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 12, 2026 •

Copy link
Copy Markdown

size-limit report 📦

Path Size
postgres / no-emit 155.17 KB (+0.4% 🔺)
postgres / emit 142.76 KB (+0.45% 🔺)
mongo / no-emit 78 KB (0%)
mongo / emit 72.09 KB (0%)
cf-worker / no-emit 182.53 KB (+0.4% 🔺)
cf-worker / emit 168.51 KB (+0.44% 🔺)

@pkg-pr-new

pkg-pr-new Bot commented Jun 12, 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@819

@prisma-next/mongo-runtime

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

@prisma-next/family-mongo

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

@prisma-next/sql-runtime

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

@prisma-next/family-sql

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

@prisma-next/extension-arktype-json

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

@prisma-next/middleware-cache

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

@prisma-next/mongo

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

@prisma-next/extension-paradedb

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

@prisma-next/extension-pgvector

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

@prisma-next/extension-postgis

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

@prisma-next/postgres

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

@prisma-next/sql-orm-client

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

@prisma-next/sqlite

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

@prisma-next/extension-supabase

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

@prisma-next/target-mongo

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

@prisma-next/adapter-mongo

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

@prisma-next/driver-mongo

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

@prisma-next/contract

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

@prisma-next/utils

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

@prisma-next/config

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

@prisma-next/errors

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

@prisma-next/framework-components

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

@prisma-next/operations

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

@prisma-next/ts-render

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

@prisma-next/contract-authoring

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

@prisma-next/ids

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

@prisma-next/psl-parser

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

@prisma-next/psl-printer

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

@prisma-next/cli

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

@prisma-next/cli-telemetry

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

@prisma-next/config-loader

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

@prisma-next/emitter

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

@prisma-next/language-server

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/language-server@819

@prisma-next/migration-tools

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

prisma-next

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

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

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

@prisma-next/mongo-codec

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

@prisma-next/mongo-contract

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

@prisma-next/mongo-value

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

@prisma-next/mongo-contract-psl

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

@prisma-next/mongo-contract-ts

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

@prisma-next/mongo-emitter

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

@prisma-next/mongo-schema-ir

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

@prisma-next/mongo-query-ast

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

@prisma-next/mongo-orm

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

@prisma-next/mongo-query-builder

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

@prisma-next/mongo-lowering

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

@prisma-next/mongo-wire

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

@prisma-next/sql-contract

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

@prisma-next/sql-errors

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

@prisma-next/sql-operations

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

@prisma-next/sql-schema-ir

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

@prisma-next/sql-contract-psl

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

@prisma-next/sql-contract-ts

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

@prisma-next/sql-contract-emitter

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

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

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

@prisma-next/sql-relational-core

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

@prisma-next/sql-builder

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

@prisma-next/target-postgres

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

@prisma-next/target-sqlite

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

@prisma-next/adapter-postgres

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

@prisma-next/adapter-sqlite

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

@prisma-next/driver-postgres

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

@prisma-next/driver-sqlite

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

commit: 16a6967

@tensordreams
tensordreams force-pushed the tml-2790-mn-demo-examples branch from 868089d to b10234d Compare June 15, 2026 10:07
@tensordreams
tensordreams force-pushed the tml-2794-slice-5-psl-mn-authoring branch from 872c0ac to 1c43446 Compare June 15, 2026 10:07
@tensordreams
tensordreams force-pushed the tml-2790-mn-demo-examples branch from b10234d to 956c3ec Compare June 15, 2026 16:57
@tensordreams
tensordreams force-pushed the tml-2794-slice-5-psl-mn-authoring branch 2 times, most recently from 564ebc0 to 96a2c6f Compare June 16, 2026 07:39
@tensordreams
tensordreams force-pushed the tml-2790-mn-demo-examples branch 2 times, most recently from 55c0085 to cc561e9 Compare June 16, 2026 15:08
@tensordreams
tensordreams force-pushed the tml-2794-slice-5-psl-mn-authoring branch from 96a2c6f to 3903f46 Compare June 16, 2026 15:09
@tensordreams
tensordreams force-pushed the tml-2790-mn-demo-examples branch from cc561e9 to 56485cd Compare June 16, 2026 18:53
@tensordreams
tensordreams force-pushed the tml-2794-slice-5-psl-mn-authoring branch from 3903f46 to 23d1440 Compare June 16, 2026 18:55
@tensordreams
tensordreams force-pushed the tml-2790-mn-demo-examples branch from 56485cd to 347b9fa Compare June 17, 2026 11:58
@tensordreams
tensordreams force-pushed the tml-2794-slice-5-psl-mn-authoring branch from 23d1440 to 389209a Compare June 17, 2026 11:59
@tensordreams
tensordreams force-pushed the tml-2790-mn-demo-examples branch from 347b9fa to 5822c1a Compare June 17, 2026 13:57
@tensordreams
tensordreams force-pushed the tml-2794-slice-5-psl-mn-authoring branch from 389209a to 643be8b Compare June 17, 2026 13:59
@tensordreams
tensordreams force-pushed the tml-2790-mn-demo-examples branch from 5822c1a to b566f6b Compare June 17, 2026 14:20
@tensordreams
tensordreams force-pushed the tml-2794-slice-5-psl-mn-authoring branch 3 times, most recently from 153e30a to 03a7a8b Compare June 18, 2026 13:50
@coderabbitai

coderabbitai Bot commented Jun 18, 2026

Copy link
Copy Markdown
Contributor

Caution

Failed to replace (edit) comment. This is likely due to insufficient permissions or the comment being deleted.

Error details
{}

Base automatically changed from tml-2790-mn-demo-examples to main June 18, 2026 14:30

@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.

Review — TML-2794 slice 5 (PSL authors M:N)

Reviewed for system design, correctness, completeness, and test quality. This is a tight, well-scoped change and I'm confident in it. CI is green (incl. Integration + Fixtures + Type Check).

System design

Confined to the PSL authoring layer (psl-relation-resolution.ts + the modelIdColumns plumbing in interpreter.ts). No runtime, TS-builder, or demo changes. The new path emits the same RelationNode (cardinality: 'N:M' + through) the TS builder already produces, so the whole runtime stack is reused as-is and parity is by construction. Declined cases fall back to the pre-existing PSL_ORPHANED_BACKRELATION_LIST / PSL_AMBIGUOUS_BACKRELATION_LIST diagnostics. Good layering — the "smallest surface that matches the existing diagnostic's guidance" framing holds.

Correctness (verified)

  • Shape parity is exact. Diffed the emitted mn-psl contract against the TS-builder fixture: User.tags is byte-identical — on: {localFields:['id'], targetFields:['user_id']} and through: {parentColumns:['user_id'], childColumns:['tag_id'], targetColumns:['id'], table:'user_tags'}.
  • The child-column reordering fix (a0c8bce) is genuinely necessary and correct. The runtime (model-accessor.ts) pairs through.childColumns[i] = through.targetColumns[i] positionally, and buildThroughDescriptor derives targetColumns from the target's @id in declared order — so without childColumnsInTargetIdOrder a swapped-order FK would emit a silently-wrong join. The swapped-order unit test pins exactly this.
  • The id-coverage gate (idColumnsAreExactlyFkPair) correctly rejects surrogate-id junctions, ternary junctions, and partial-id references; self-referential disambiguation by relation name is consistent with the existing 1:N relation-name filtering.

Tests — high quality

  • 10 lowering unit tests cover both directions, composite keys, swapped FK order, self-ref (named + ambiguous), surrogate-id / non-id-unique declines, direct-FK precedence, and validateContract round-trips.
  • The integration parity suite drives the full ORM API (include explicit/implicit, some/none/every, connect/disconnect/nested-create) against a real emitted PSL contract, with whole-row toEqual + junction-row assertions.
  • fixtures:check wiring (a0ae774) closes the vacuous-green gap — confirmed the root fixtures:check globs **/contract.*, which now includes the new fixture's generated/.

Non-blocking notes

Three inline comments below: (1) a TS/PSL parity gap + misleading diagnostic for @unique-referenced junction targets, (2) composite-key M:N has no runtime coverage on either the PSL or TS-builder side (pre-existing posture, inherited here), (3) a precision caveat on the "shape-identical" claim for parent-side on ordering. None block merge.

@tensordreams
tensordreams force-pushed the tml-2794-slice-5-psl-mn-authoring branch from 03a7a8b to 7d71303 Compare June 18, 2026 14:36

@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.

Review — PSL many-to-many junction recognition

Verdict: solid implementation, correct, well-tested. No blocking issues.

I verified by building the PR branch and running the full @prisma-next/sql-contract-psl test suite (258 tests, 18 files — all pass, no regressions) plus the new mn-psl-parity integration suite (8 tests — all pass against a live Postgres dev server). Lint (biome) and dependency layering (lint:deps) are clean. Typecheck passes.

System design & architecture

The junction recognition approach (form 1: explicit junction with composite @@id([a, b]) covering exactly the FK columns) is a clean, minimal surface that matches the existing PSL_ORPHANED_BACKRELATION_LIST diagnostic's guidance. The new fkRelationsByDeclaringModel index and modelIdColumns map are clean additions that don't perturb the existing fkRelationsByPair matching path — junction recognition only runs as a fallback when no direct FK match exists, so direct 1:N relations are unaffected.

The critical correctness property — reordering through.childColumns to the target's id-column order — is well-justified. I traced the runtime join builder (buildManyToManyJunctionArtifacts in query-plan-select.ts:368-387 and buildPairedColumnExprs in model-accessor.ts:492-519): both pair through.childColumns[i] = through.targetColumns[i] strictly by index, and through.targetColumns is emitted in the target's PK declaration order. Without reordering, a composite-key junction whose FK references are in a different order from the PK would produce silently wrong JOINs. The PR handles this correctly.

The storage-column-name convention is consistent throughout: modelNode.id.columns, FkRelationMetadata.localColumns/referencedColumns, and all on/through fields are storage column names, matching the existing 1:N/N:1 paths and what build-contract.ts lowering expects.

Correctness — verified

  • Column reordering: the composite-key + swapped-FK-references test correctly asserts through.childColumns reordered to target PK order for a target whose @@id is in a different order from the FK's references. ✓
  • Direct FK precedence: a direct FK match wins over junction recognition. ✓
  • Self-referential M:N: disambiguated by the list field's @relation name pinning the parent-side junction FK; unnamed symmetric lists get the ambiguity diagnostic. ✓
  • Non-id unique rejection: childColumnsInTargetIdOrder correctly returns undefined when the child FK references a non-id unique. ✓
  • Surrogate-id junction exclusion: the idColumns.length < 2 gate rejects junctions with a single-column surrogate PK (deliberate, documented, tested). ✓

Completeness — suggestions (non-blocking)

  1. Diagnostic UX for surrogate-id junctions — the orphaned diagnostic doesn't explain that the junction needs a composite @@id; will confuse users with the common Prisma surrogate-id junction pattern. See inline.
  2. Contract-level through length validation — no validator checks through.childColumns.length === through.targetColumns.length; a future regression would produce silently wrong JOINs. See inline.
  3. toNamespaceId inconsistency — the new N:M path correctly propagates toNamespaceId, but the existing 1:N path drops it (pre-existing, not a regression). See inline.
  4. Test gap: junction with extra data columns — a junction like UserTag { userId, tagId, createdAt, @@id([userId, tagId]) } is untested. See inline.

Tests

The 10 unit tests are well-chosen and cover the important matrix: both directions, composite keys, swapped FK order, non-id unique rejection, self-ref with/without name, orphaned (no junction), surrogate-id junction, explicit junction without bare lists (stays 1:N), and direct-FK precedence. The 8 integration tests prove the full M:N ORM API (include, some/none/every, connect/disconnect/nested create) against a PSL-emitted contract, with whole-row toEqual assertions per repo convention.

Minor note: the PR body references mn-nested-write.test.ts as an existing TS fixture test file, but that file doesn't exist in the repo — the TS M:N integration tests are mn-include.test.ts and mn-filter.test.ts only.

tensordreams added a commit that referenced this pull request Jun 18, 2026
…ostics

Addresses PR #819 review (TML-2794 slice 5):

- Cross-namespace junctions emitted a `through` with no namespaceId, so
  the contract builder fell back to the default namespace and the ORM
  joined the wrong junction table. Carry the junction model's declaring
  namespace on FkRelationMetadata and set `through.namespaceId`. Output
  is unchanged for default-namespace junctions (the builder already
  defaulted to the same value); a non-default-namespace junction now
  resolves correctly.
- Align the 1:N backrelation path to propagate `toNamespaceId`, matching
  the N:1 and N:M paths.
- A model that links both sides but is declined (its id doesn't cover its
  FK columns, or its target-side FK references a non-@id key) now gets a
  junction-specific diagnostic naming the model and the requirement,
  instead of the generic orphaned-backrelation message.

Claude-Session: https://claude.ai/code/session_01XcWuDhwCq2tXf5W4Py1Mk6
Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…er_tags)

Mirror the TS-builder M:N fixture in PSL: an explicit UserTag junction
model with composite @@id over its two FK columns plus bare
backrelation list fields on User and Tag. The emitted contract carries
cardinality N:M with a populated through descriptor on both sides --
shape-identical to what rel.manyToMany produces -- proving the PSL
explicit-junction lowering round-trips the canonical emit + validate
pipeline.

Generated artifacts come from the canonical CLI emit
(prisma-next contract emit --config .../mn-psl/prisma-next.config.ts)
and re-emit byte-identically, following the polymorphism fixture
convention.

Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…xture

Drive the PSL-emitted M:N contract through the full ORM API with one
representative integration case per surface: include (explicit select +
implicit default selection), some/none/every relation filters, and
connect/disconnect/nested-create junction writes -- mirroring the
TS-fixture coverage in mn-include / mn-filter / mn-nested-write.

Deserializing the emitted JSON runs the full sql contract validation
pipeline, so the suite also pins that a PSL-authored N:M + through
contract round-trips validation. The runtime is built against the
mn-psl contract (storageHash differs from the base fixture), following
the polymorphism-fixture contractOverride pattern.

Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
The mn-psl PSL fixture config was not emitted by the package emit
script, so fixtures:check was vacuously green for it and a PSL
interpreter regression would leave the committed contract.json stale.
Append the mn-psl contract emit alongside the polymorphism fixture;
no cp step needed since the fixture emits into its own generated dir.

Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…0 main

Rebasing onto main picked up TML-2916 (un-namespaced PG models default to
`public`, dropping the empty `__unbound__` storage slot). Re-emit the PSL-authored
`mn-psl` fixture so it matches the new emitter output; storage hash updates.

Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
Slice 3 merged, so the extension-author 0.14-to-0.15 directory now lives in main
and is no longer in this PR's diff. Slice 5 independently touches
`packages/3-extensions/` (the `mn-psl` fixture's entry in the sql-orm-client test
`emit` script), so record that incidental, test-only substrate diff in the
extension-author 0.14-to-0.15 instructions to satisfy the per-PR coverage gate.

Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…ostics

Addresses PR #819 review (TML-2794 slice 5):

- Cross-namespace junctions emitted a `through` with no namespaceId, so
  the contract builder fell back to the default namespace and the ORM
  joined the wrong junction table. Carry the junction model's declaring
  namespace on FkRelationMetadata and set `through.namespaceId`. Output
  is unchanged for default-namespace junctions (the builder already
  defaulted to the same value); a non-default-namespace junction now
  resolves correctly.
- Align the 1:N backrelation path to propagate `toNamespaceId`, matching
  the N:1 and N:M paths.
- A model that links both sides but is declined (its id doesn't cover its
  FK columns, or its target-side FK references a non-@id key) now gets a
  junction-specific diagnostic naming the model and the requirement,
  instead of the generic orphaned-backrelation message.

Claude-Session: https://claude.ai/code/session_01XcWuDhwCq2tXf5W4Py1Mk6
Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
Addresses PR #819 review (TML-2794 slice 5): validateSqlContractFully
now checks that an N:M relation's `through.parentColumns` matches
`on.localFields` in length and `through.childColumns` matches
`through.targetColumns`. The runtime join builder pairs these arrays
positionally, so a length mismatch previously surfaced as a silently
wrong JOIN at query time rather than a validation error. Hardens both
the PSL and TS-builder lowering paths.

Claude-Session: https://claude.ai/code/session_01XcWuDhwCq2tXf5W4Py1Mk6
Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
Addresses PR #819 round-2 review (TML-2794 slice 5).

The earlier through-length check only tallied column counts — redundant
with what storage-FK validation already guarantees, and silent about
existence. Replace it with one that ties each N:M `through` join side to
the storage columns it actually joins: matching column count and
existence of every referenced column, resolving `on.localFields` (domain
field names) through the model's field→column map and reading
`through.*Columns` as storage columns directly. One code path regardless
of whether the junction carries declared FK constraints (the TS builder
accepts explicit join columns without them).

Type *compatibility* of paired columns is deliberately not asserted here:
it is target-specific (a `text`↔`character` join is valid on Postgres)
and enforced by the migration/database layer, so an exact-type check
would falsely reject valid joins.

Also: use `.` not `:` to separate namespace/model in messages (matching
the SQL and ORM surfaces), restore the orphaned `validateSqlContractFully`
doc block, and tighten the assertions to quote more of the message.

Claude-Session: https://claude.ai/code/session_01XcWuDhwCq2tXf5W4Py1Mk6
Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
Addresses PR #819 round-2 review (TML-2794 slice 5). The 1:N
toNamespaceId test referenced `Post` across namespaces unqualified,
leaning on bare-name resolution (which collapses to the last entry on a
name collision). Use `blog.Post[]` so the cross-namespace reference is
explicit and unambiguous.

Claude-Session: https://claude.ai/code/session_01XcWuDhwCq2tXf5W4Py1Mk6
Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
PR #819 round-3 review (TML-2794 slice 5). The sql-orm-client fixtures
declared junction FK columns (`user_tags.tag_id`, `user_roles.role_id`)
as `text` while the ids they reference (`Tag.id`, `Role.id`, generated
by `uuidv4()`) emit `char(36)`. That mismatch was accidental — `textColumn`
where the referenced id is `char(36)` — and would lean on implicit
char↔text coercion at the database, which is not safe on writes. Use
`charColumn(36)` so each junction FK matches the column it references.
Re-emitted the affected generated contracts.

Claude-Session: https://claude.ai/code/session_01XcWuDhwCq2tXf5W4Py1Mk6
Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
PR #819 round-3 review (TML-2794 slice 5). The through-consistency check
now requires each pair of joined columns to be the *same* storage type
(`nativeType` + `typeParams`), not merely compatible. Relying on implicit
conversion (e.g. `text`↔`character`) is unsafe on writes — `character(n)`
space-padding makes such coercions non-associative — and no ADR sanctions
heterogeneous junction columns. Equality is the conservative default and
can be relaxed deliberately if a real use case appears. `codecId` and
`nullable` are not compared: they don't change the database-level type a
join sees.

Claude-Session: https://claude.ai/code/session_01XcWuDhwCq2tXf5W4Py1Mk6
Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…rgets

Tracks the deferred work surfaced in PR #819 review: supporting junctions
whose target-side FK references a non-id non-null `@unique` (reworking
`through.targetColumns` derivation across PSL + TS lowering). Linear TML-2933.

Claude-Session: https://claude.ai/code/session_01XcWuDhwCq2tXf5W4Py1Mk6
Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
PR #819 review (CodeRabbit). The through-consistency validator returned
early for a cross-space N:M target, skipping all child-side checks — so a
malformed `through.childColumns` (length mismatch or a column absent from
the junction table) passed validation. Those checks don't depend on
resolving the target model. Make the model side optional: the column-count
and junction-column-existence checks now run regardless; only the
target-column existence and storage-type checks are skipped when the
target lives in another contract space.

Claude-Session: https://claude.ai/code/session_01XcWuDhwCq2tXf5W4Py1Mk6
Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
Rebase onto main brought TML-2929 (CST symbol-table parser), which
removed `parsePslDocument` and now requires `controlMutationDefaults` on
the interpreter input. Re-port the many-to-many and 1:N cross-namespace
tests to `symbolTableInputFromParseArgs` + the spread-input call shape.

Claude-Session: https://claude.ai/code/session_01XcWuDhwCq2tXf5W4Py1Mk6
Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…erenced char(36) PKs

The fixture source authors `UserRole.roleId` and `UserTag.tagId` as
`charColumn(36)` to match the char(36) uuid primary keys they reference
(`roles.id`, `tags.id`), but the committed `contract.json`/`contract.d.ts`
still carried `text` for `role_id`/`tag_id`. The many-to-many
junction-type-equality validator rejects the mismatch at deserialize time,
which failed every suite that loads the fixture.

Re-emit both artifacts so the junction columns are char(36), matching their
referenced PKs and satisfying the validator.

Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
@tensordreams
tensordreams force-pushed the tml-2794-slice-5-psl-mn-authoring branch from 00d7fd5 to dbbd50f Compare June 22, 2026 09:28
…same model pair

The relation-name disambiguation that resolves self-referential many-to-many
sides is general: it equally distinguishes two separate many-to-many relations
between the same pair of distinct models, each through its own junction. That
path was exercised only for the same-model (self-referential) permutation.

Add two interpreter cases for the distinct-models shape (User <-> Tag through
TagOwnership and TagWatch): one where both list fields and their junction
parent-side FKs carry matching @relation names, asserting both relations lower
to N:M with the correct through descriptors and the contract validates fully;
and one without relation names, asserting the PSL_AMBIGUOUS_BACKRELATION_LIST
diagnostic. No implementation change — the behaviour was already correct.

Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…l spread

Replace the conditional object spread that adds the optional `model` key to the
child-side validateThroughJoinSide call with the `ifDefined` helper, matching
the established pattern in this file and the repo convention.

Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
@tensordreams

Copy link
Copy Markdown
Contributor Author

@coderabbitai Re the actionable comment about the cross-space early return skipping child-side through validation (validators.ts ~981–987): this doesn't apply to the current code.

The child-side validateThroughJoinSide call (validators.ts:1040) runs unconditionally. Inside it, the column-count check and the junction-column-existence check execute before the model === undefined guard; only the target-column existence/type checks are skipped for a cross-space target, because that target's storage lives in another contract and isn't resolvable here. There is no early continue that bypasses child-side invariants.

validators.test.ts:390 ("validates child-side through length even for a cross-space target") pins exactly this: a cross-space N:M whose through.childColumns (1) and through.targetColumns (2) differ in length is rejected. No change needed.

@coderabbitai

coderabbitai Bot commented Jun 22, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

@tensordreams You're right — I misread the structure. The child-side validateThroughJoinSide call is unconditional, and the length/junction-column-existence invariants fire before the model === undefined guard; only the target-column existence and type checks are gated behind it (correctly so, since the target's storage isn't resolvable cross-space). The test at line 390 nails the exact boundary case. I'll withdraw the comment.

@aqrln
aqrln added this pull request to the merge queue Jun 22, 2026
Merged via the queue into main with commit 508b9e0 Jun 22, 2026
20 checks passed
@aqrln
aqrln deleted the tml-2794-slice-5-psl-mn-authoring branch June 22, 2026 15:24
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