Skip to content

fix: prisma2 introspect for mysql database - #683

Merged
timsuchanek merged 1 commit into
prisma:masterfrom
wardpeet:fix/introspection
Oct 18, 2019
Merged

timsuchanek merged 1 commit into
prisma:masterfrom
wardpeet:fix/introspection

Conversation

@wardpeet

@wardpeet wardpeet commented Oct 7, 2019

Copy link
Copy Markdown
Contributor

When using prisma2 init I can create a connection with my mysql connection and get a prisma.schema generated. However when I run prisma2 introspect it gives me Please provide a database name error. Schema is not necessary for mysql but it is for Postgres so I updated the statements to support MySQL as well.

@CLAassistant

CLAassistant commented Oct 7, 2019 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@janpio
janpio requested a review from timsuchanek October 7, 2019 21:55
@janpio

janpio commented Oct 7, 2019

Copy link
Copy Markdown
Contributor

Ha, database vs. schema already caused bugs in Prisma 1 ;)

@pantharshit00

Copy link
Copy Markdown
Contributor

Thanks for the PR!

This bug was not reported but I can confirm it.
image

@janpio
janpio requested review from divyenduz and removed request for timsuchanek October 11, 2019 15:53
@janpio janpio added this to the Preview 15 milestone Oct 11, 2019
@janpio

janpio commented Oct 11, 2019

Copy link
Copy Markdown
Contributor

@divyenduz will look into both the bug and the possible fix via this PR to check if this solves the problem.

@wardpeet

Copy link
Copy Markdown
Contributor Author

Do you want me to post a before/after gif?

@divyenduz

Copy link
Copy Markdown

@wardpeet That would be great thanks 🙌

@janpio janpio added bug/2-confirmed Bug has been reproduced and confirmed. kind/bug A reported bug. labels Oct 16, 2019

@divyenduz divyenduz left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

LGTM!

@timsuchanek
timsuchanek merged commit 388d7bb into prisma:master Oct 18, 2019
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug/2-confirmed Bug has been reproduced and confirmed. kind/bug A reported bug.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants