Repository navigation
TML-2794: M:N slice 5 — PSL authors many-to-many (junction → N:M + through) - #819
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughExtends the PSL interpreter to detect explicit junction models and emit ChangesM:N PSL junction resolution and ORM parity
Estimated code review effort🎯 4 (Complex) | ⏱️ ~75 minutes Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
size-limit report 📦
|
@prisma-next/extension-author-tools
@prisma-next/mongo-runtime
@prisma-next/family-mongo
@prisma-next/sql-runtime
@prisma-next/family-sql
@prisma-next/extension-arktype-json
@prisma-next/middleware-cache
@prisma-next/mongo
@prisma-next/extension-paradedb
@prisma-next/extension-pgvector
@prisma-next/extension-postgis
@prisma-next/postgres
@prisma-next/sql-orm-client
@prisma-next/sqlite
@prisma-next/extension-supabase
@prisma-next/target-mongo
@prisma-next/adapter-mongo
@prisma-next/driver-mongo
@prisma-next/contract
@prisma-next/utils
@prisma-next/config
@prisma-next/errors
@prisma-next/framework-components
@prisma-next/operations
@prisma-next/ts-render
@prisma-next/contract-authoring
@prisma-next/ids
@prisma-next/psl-parser
@prisma-next/psl-printer
@prisma-next/cli
@prisma-next/cli-telemetry
@prisma-next/config-loader
@prisma-next/emitter
@prisma-next/language-server
@prisma-next/migration-tools
prisma-next
@prisma-next/vite-plugin-contract-emit
@prisma-next/mongo-codec
@prisma-next/mongo-contract
@prisma-next/mongo-value
@prisma-next/mongo-contract-psl
@prisma-next/mongo-contract-ts
@prisma-next/mongo-emitter
@prisma-next/mongo-schema-ir
@prisma-next/mongo-query-ast
@prisma-next/mongo-orm
@prisma-next/mongo-query-builder
@prisma-next/mongo-lowering
@prisma-next/mongo-wire
@prisma-next/sql-contract
@prisma-next/sql-errors
@prisma-next/sql-operations
@prisma-next/sql-schema-ir
@prisma-next/sql-contract-psl
@prisma-next/sql-contract-ts
@prisma-next/sql-contract-emitter
@prisma-next/sql-lane-query-builder
@prisma-next/sql-relational-core
@prisma-next/sql-builder
@prisma-next/target-postgres
@prisma-next/target-sqlite
@prisma-next/adapter-postgres
@prisma-next/adapter-sqlite
@prisma-next/driver-postgres
@prisma-next/driver-sqlite
commit: |
868089d to
b10234d
Compare
872c0ac to
1c43446
Compare
b10234d to
956c3ec
Compare
564ebc0 to
96a2c6f
Compare
55c0085 to
cc561e9
Compare
96a2c6f to
3903f46
Compare
cc561e9 to
56485cd
Compare
3903f46 to
23d1440
Compare
56485cd to
347b9fa
Compare
23d1440 to
389209a
Compare
347b9fa to
5822c1a
Compare
389209a to
643be8b
Compare
5822c1a to
b566f6b
Compare
153e30a to
03a7a8b
Compare
|
Caution Failed to replace (edit) comment. This is likely due to insufficient permissions or the comment being deleted. Error details |
tensordreams
left a comment
There was a problem hiding this comment.
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-pslcontract against the TS-builder fixture:User.tagsis byte-identical —on: {localFields:['id'], targetFields:['user_id']}andthrough: {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) pairsthrough.childColumns[i] = through.targetColumns[i]positionally, andbuildThroughDescriptorderivestargetColumnsfrom the target's@idin declared order — so withoutchildColumnsInTargetIdOrdera 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
validateContractround-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:checkwiring (a0ae774) closes the vacuous-green gap — confirmed the rootfixtures:checkglobs**/contract.*, which now includes the new fixture'sgenerated/.
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.
03a7a8b to
7d71303
Compare
tensordreams
left a comment
There was a problem hiding this comment.
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.childColumnsreordered to target PK order for a target whose@@idis in a different order from the FK'sreferences. ✓ - Direct FK precedence: a direct FK match wins over junction recognition. ✓
- Self-referential M:N: disambiguated by the list field's
@relationname pinning the parent-side junction FK; unnamed symmetric lists get the ambiguity diagnostic. ✓ - Non-id unique rejection:
childColumnsInTargetIdOrdercorrectly returnsundefinedwhen the child FK references a non-id unique. ✓ - Surrogate-id junction exclusion: the
idColumns.length < 2gate rejects junctions with a single-column surrogate PK (deliberate, documented, tested). ✓
Completeness — suggestions (non-blocking)
- 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. - Contract-level
throughlength validation — no validator checksthrough.childColumns.length === through.targetColumns.length; a future regression would produce silently wrong JOINs. See inline. toNamespaceIdinconsistency — the new N:M path correctly propagatestoNamespaceId, but the existing 1:N path drops it (pre-existing, not a regression). See inline.- 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.
…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]>
Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
… main 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]>
00d7fd5 to
dbbd50f
Compare
…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]>
|
@coderabbitai Re the actionable comment about the cross-space early return skipping child-side The child-side
|
|
Tip For best results, initiate chat on the files or code changes.
|
Slice 5 of the SQL ORM: Many-to-Many End to End project (follow-on group). Refs TML-2794.
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 asPSL_ORPHANED_BACKRELATION_LIST—cardinality: 'N:M' + throughexisted 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 twoN:1relations to the two side models — the list lowers to a navigableN:Mrelation through that junction, shape-identical torel.manyToManyoutput.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.childColumnsreordered to id order (the runtime joinschildColumns[i] = targetColumns[i]by index); decline → existing orphaned diagnostic. Self-referential M:N disambiguated by the list's@relationname (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 (stay1:N).interpreter.relations.many-to-many.test.ts): both directions, composite keys, swapped-order FK references, self-referential, diagnostic preservation,validateContractround-trip.fixtures/mn-psl/(User ↔ Tagviauser_tags, mirroring the TS fixture) wired into the sql-orm-client emit pipeline sofixtures:checkregenerates 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
Bug Fixes / Improvements
Tests
Documentation / Chores