Repository navigation
fix: prisma2 introspect for mysql database - #683
Merged
Merged
Conversation
Contributor
|
Ha, |
Contributor
Contributor
|
@divyenduz will look into both the bug and the possible fix via this PR to check if this solves the problem. |
Contributor
Author
|
Do you want me to post a before/after gif? |
|
@wardpeet That would be great thanks 🙌 |
tensordreams
added a commit
that referenced
this pull request
Jul 28, 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` (#680) → `tml-2785` (#679) → `tml-2784` (#678) → `tml-2597` (#673) → `tml-2729` (#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 #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]>
tensordreams
added a commit
that referenced
this pull request
Jul 28, 2026
…–6) (#742) > **Supersedes #697** — that PR was auto-marked *merged* by GitHub when a botched force-push briefly made its head identical to its base (nothing was actually merged; the branch content is unchanged). Same commits, same review state. Follow-on to the [SQL ORM: Many-to-Many End to End](https://linear.app/prisma-company/project/sql-orm-many-to-many-end-to-end-c178df40ca3a) project: M:N **demo examples** + the project-plan expansion they surfaced. > **Stacked PR** — top of the M:N stack: `tml-2787` (#683) → … → `tml-2729` (#667) → `main` (the whole stack is rebased onto the latest `main`). ## SQLite demo M:N examples (`72ef8b793`, `883309ecc`) The SQLite demo (`examples/prisma-next-demo-sqlite`, TS-authored) now demonstrates the full M:N ORM API via a pure `Post ↔ Tag` junction (`PostTag`): - **Read:** `get-post-tags` — `.include(tags, t => t.select(...))`. - **Filter:** `get-posts-by-tag-filter` — `.where(p => p.tags.some/none/every(t => t.label.eq(...)))`. - **Write (callback mutator):** `connect-post-tags` / `disconnect-post-tags` / `create-post-with-tags` — `.update/.create({ tags: t => t.connect/disconnect/create([...]) })` with readback. Wired as 6 CLI commands + seed; **smoke-tested end-to-end** (SQLite is offline-runnable); emitted contract carries `cardinality:N:M` + `through`; `emit:check` + typecheck clean. ## Why only SQLite (and the plan expansion) (`d711adfb6`) Adding examples surfaced a real gap: **the navigable M:N API is authorable only via the TS contract builder (`rel.manyToMany`), not PSL** — PSL emits only `1:N`/`N:1` and routes M:N to explicit junction models. The PG demo emits from PSL, so it **cant** show M:N until PSL learns to author it. So: - **Filed [TML-2794](https://linear.app/prisma-company/issue/TML-2794)** — PSL many-to-many authoring (the framework gap). - **Filed [TML-2795](https://linear.app/prisma-company/issue/TML-2795)** — PG demo M:N examples + pre-existing dual-mode contract drift (blocked by TML-2794). - **Amended the project spec + plan** with follow-on **slices 4–6** (SQLite examples [done], PSL M:N authoring [planned], PG demo [planned]) + slice specs/plans. Slice 5 is framework-scoped and flagged for possible promotion to its own project. ## Scope / notes This PR ships the **SQLite** examples + the planning docs only. PG demo examples + PSL authoring are tracked (TML-2794/2795) and specd but not implemented here. No production `src/` changes — demo + project-docs only. Refs: TML-2790. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit ## Release Notes * **New Features** * Expanded the sqlite demo to support `Post` ↔ `Tag` many-to-many tagging via a junction. * Added CLI commands to query posts/tags, apply tag filters (`some`/`none`/`every`), and connect/disconnect or create posts with tags. * **Documentation** * Updated the demo README to cover the full many-to-many API, command behaviors, and junction insert/delete notes. * Enhanced seeding instructions and the seed process to create tags and junction rows. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
tensordreams
added a commit
that referenced
this pull request
Jul 28, 2026
…rough) (#819) **Slice 5 of the [SQL ORM: Many-to-Many End to End](https://linear.app/prisma-company/project/sql-orm-many-to-many-end-to-end-c178df40ca3a) 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. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## 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. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.

When using
prisma2 initI can create a connection with my mysql connection and get a prisma.schema generated. However when I runprisma2 introspectit gives mePlease provide a database nameerror. Schema is not necessary for mysql but it is for Postgres so I updated the statements to support MySQL as well.