@prisma/orm-postgres 8.0.0-rc.24-dev.28 → 8.0.0-rc.24-dev.29
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -3
- package/dist/components-CWcPJJxx-0zxP3brl.mjs +19 -0
- package/dist/components-CWcPJJxx-0zxP3brl.mjs.map +1 -0
- package/dist/config.mjs +21 -14
- package/dist/config.mjs.map +1 -1
- package/dist/{contract-from-json-BykLXhvn-QBZhmOB4.mjs → contract-from-json-BQdx9dk3-CHLY5fww.mjs} +3 -3
- package/dist/{contract-from-json-BykLXhvn-QBZhmOB4.mjs.map → contract-from-json-BQdx9dk3-CHLY5fww.mjs.map} +1 -1
- package/dist/contract-types.d.mts +4 -0
- package/dist/contract-types.mjs +1 -0
- package/dist/control.mjs +2 -8
- package/dist/control.mjs.map +1 -1
- package/dist/init-quick-reference-prisma7.md +80 -0
- package/dist/init-quick-reference.md +95 -0
- package/dist/init-readme.md +34 -0
- package/dist/init.d.mts +7 -0
- package/dist/init.d.mts.map +1 -0
- package/dist/init.mjs +272 -0
- package/dist/init.mjs.map +1 -0
- package/dist/internal__static-context.mjs +1 -1
- package/dist/internal__transaction-members.d.mts +1 -1
- package/dist/internal__transaction-members.mjs +1 -1
- package/dist/internal__validate-contract.mjs +1 -1
- package/dist/module-base-C02qpQ9x-BEyIGqx7.mjs +6 -0
- package/dist/module-base-C02qpQ9x-BEyIGqx7.mjs.map +1 -0
- package/dist/{postgres-members-B7ZvxGYc-D_L3NVGm.mjs → postgres-members-CRPX0rhb-C0keDjWe.mjs} +18 -16
- package/dist/postgres-members-CRPX0rhb-C0keDjWe.mjs.map +1 -0
- package/dist/{postgres-members-F9CVSrrN-BFAuNPbW.d.mts → postgres-members-DQvChDJ--ByodBWAn.d.mts} +3 -2
- package/dist/postgres-members-DQvChDJ--ByodBWAn.d.mts.map +1 -0
- package/dist/{postgres-static-P3V5EpAP-Df_jRCSf.mjs → postgres-static-BsLAA6GS-BBKjNHT8.mjs} +3 -3
- package/dist/{postgres-static-P3V5EpAP-Df_jRCSf.mjs.map → postgres-static-BsLAA6GS-BBKjNHT8.mjs.map} +1 -1
- package/dist/runtime.d.mts +1 -1
- package/dist/runtime.mjs +3 -3
- package/dist/runtime.mjs.map +1 -1
- package/dist/serverless.d.mts +1 -1
- package/dist/serverless.mjs +3 -3
- package/dist/serverless.mjs.map +1 -1
- package/dist/static.mjs +2 -2
- package/package.json +12 -10
- package/skills/prisma-8/SKILL.md +10 -10
- package/skills/prisma-8/references/build.md +12 -16
- package/skills/prisma-8/references/contract.md +35 -33
- package/skills/prisma-8/references/debug.md +5 -3
- package/skills/prisma-8/references/feedback.md +8 -8
- package/skills/prisma-8/references/migration-model.md +4 -0
- package/skills/prisma-8/references/migration-review.md +6 -5
- package/skills/prisma-8/references/migrations.md +73 -26
- package/skills/prisma-8/references/queries-mongo.md +3 -3
- package/skills/prisma-8/references/queries-postgres.md +25 -9
- package/skills/prisma-8/references/queries.md +9 -8
- package/skills/prisma-8/references/quickstart.md +19 -19
- package/skills/prisma-8/references/runtime.md +23 -23
- package/skills/prisma-8/references/supabase.md +7 -7
- package/skills/prisma-8/references/upgrade-app.md +1 -1
- package/dist/postgres-members-B7ZvxGYc-D_L3NVGm.mjs.map +0 -1
- package/dist/postgres-members-F9CVSrrN-BFAuNPbW.d.mts.map +0 -1
|
@@ -28,9 +28,9 @@ Prisma 8 ships **two query lanes per target** on the same `db` value from `src/p
|
|
|
28
28
|
|
|
29
29
|
| Runtime import in `db.ts` | Load |
|
|
30
30
|
| --- | --- |
|
|
31
|
-
| `@
|
|
32
|
-
| `@
|
|
33
|
-
| `@
|
|
31
|
+
| `@prisma/orm-postgres/runtime` | [`queries-postgres.md`](./queries-postgres.md) — `db.orm.<ns>.<Model>` + `db.sql.<ns>.<table>` |
|
|
32
|
+
| `@prisma/orm-mongo/runtime` | [`queries-mongo.md`](./queries-mongo.md) — `db.orm.<root>` + `db.query.from(...)` |
|
|
33
|
+
| `@prisma/orm-extension-supabase/runtime` | [`queries-postgres.md`](./queries-postgres.md) — a Supabase `RoleBoundDb` is a Postgres surface (`db.orm.<ns>.<Model>` + `db.sql.<ns>.<table>`); bind a role first via `references/supabase.md` |
|
|
34
34
|
|
|
35
35
|
Both targets share the contract and connection on one `db` value. Reach for the ORM first; drop to the lower-level lane when the ORM can't express the shape. Lane choice is local — one query function picks one lane, not the whole app.
|
|
36
36
|
|
|
@@ -147,7 +147,7 @@ Every read terminal (`.all()`, and `db.query(plan)` for a SQL-builder plan) retu
|
|
|
147
147
|
|
|
148
148
|
There is no `.stream()` method on a client or on a connection.
|
|
149
149
|
|
|
150
|
-
## Prepared statements (Postgres, SQLite, MySQL, MongoDB)
|
|
150
|
+
## Prepared statements (Postgres, SQLite, MySQL, MariaDB, MongoDB)
|
|
151
151
|
|
|
152
152
|
This section covers the SQL clients. MongoDB's `db.prepare` has the same shape, takes query-builder plans and ORM `.prepared` reads, and runs against `await db.runtime()`; see *Workflow — Prepared statements* in [`queries-mongo.md`](queries-mongo.md).
|
|
153
153
|
|
|
@@ -208,7 +208,7 @@ async function getUserWithPosts(userId: Models.public_User['id']): Promise<UserR
|
|
|
208
208
|
type Bad = Shape<Models.public_User, { nope: {} }>;
|
|
209
209
|
```
|
|
210
210
|
|
|
211
|
-
On Mongo the imports are `@prisma/orm-mongo/family-contract
|
|
211
|
+
On Mongo the imports are `@prisma/orm-mongo/family-contract` and `@prisma/orm-mongo/components/runtime`; embedded documents are fields, so they stay in `Scalars`. To name a model plus some of its relations, write `Shape<Models.public_User, { '+': 'id' | 'posts' }>`, not `Pick<Models.public_User, 'id' | 'posts'>`: `Pick` demands fully loaded nested posts that no query returns. Input types (`CreateInput<Contract, 'User'>`, `MutationUpdateInput<Contract, 'User'>`, `ShorthandWhereFilter<Contract, 'public', 'User'>`) come from `@prisma/orm-postgres/orm-client`.
|
|
212
212
|
|
|
213
213
|
Coming from Prisma 7: `Prisma.User` → `Models.public_User` (note: now carries relations; the scalars-only row is `Scalars<Models.public_User>`); `Prisma.UserGetPayload<{ include: { posts: true } }>` → `Shape<Models.public_User, { '+': 'posts' }>`; `Prisma.UserGetPayload<{ select: { id: true; posts: { select: { title: true } } } }>` → `Shape<Models.public_User, { '+': 'id'; posts: { '+': 'title' } }>`; `Prisma.UserCreateInput` → `CreateInput<Contract, 'User'>`; `Awaited<ReturnType<typeof fn>>` → `ResultType<typeof query>`.
|
|
214
214
|
|
|
@@ -226,15 +226,16 @@ Target-specific pitfalls live in the per-target guides.
|
|
|
226
226
|
|
|
227
227
|
## What Prisma 8 doesn't do yet
|
|
228
228
|
|
|
229
|
-
- **Many-to-many relations work through the junction.** `.include('tags', (tag) => tag.select(...))` traverses an N:M relation's `through` table, and nested `create` / `connect` / `disconnect` on an N:M relation write the junction rows for you (`examples/prisma-8-demo/src/orm-client/get-post-tags.ts`, `create-post-with-tags.ts`). The one refusal: a junction with required payload columns the relation API cannot populate throws `ORM.
|
|
229
|
+
- **Many-to-many relations work through the junction.** `.include('tags', (tag) => tag.select(...))` traverses an N:M relation's `through` table, and nested `create` / `connect` / `disconnect` on an N:M relation write the junction rows for you (`examples/prisma-8-demo/src/orm-client/get-post-tags.ts`, `create-post-with-tags.ts`). The one refusal: a junction with required payload columns the relation API cannot populate throws `ORM.OPERATION_UNSUPPORTED` — write that junction directly or use the SQL builder.
|
|
230
230
|
- **Ordering grouped aggregates by an aggregate alias (Postgres).** `db.orm.<ns>.<Model>.groupBy(...)` supports `.orderBy(...)` on group keys plus `.limit(...)` / `.offset(...)`, but the grouped collection cannot order by an aggregate alias such as `SUM(amount)`. A "top-N groups by SUM" query therefore falls back to JS-side sort + slice over the full grouped result, which is fine at small cardinalities and bad at scale. Workarounds: (a) drop to `db.sql.<ns>.<table>` and write the `GROUP BY` + `ORDER BY` + `LIMIT` against the aggregated table directly; (b) live with the JS-side sort/slice if the grouped cardinality is bounded. File a feature request via `references/feedback.md` if this is hitting you in production.
|
|
231
|
+
- **Set operations, window functions and `WITH` in the SQL builder.** `db.sql` has no `union` / `intersect` / `except`, no `OVER (...)` and no common table expressions. Write the whole query as raw SQL (next entry). If you want them in the builder, file a feature request via `references/feedback.md`.
|
|
231
232
|
- **A raw-SQL lane.** This one exists. Write whole-query raw SQL through the client's raw lane: ``db.raw.sql`SELECT ...`.returnsRow({ ... }).build()`` for rows, or `.affectedCount()` for a mutation's row count. Each declared column names the codec that decodes it, so the row stays typed. For an expression fragment inside a builder query, use `fns.raw` in a `.select(...)` callback instead.
|
|
232
233
|
- **TypedSQL (`.sql` files compiled into typed callables).** Not implemented. For a repeated query, use `db.prepare(...)` (see *Prepared statements* above) or a function that returns the built plan and `db.query(plan)` at the call site. If you want a `.sql`-file compile path, file a feature request via `references/feedback.md`.
|
|
233
234
|
- **`EXPLAIN` / query-plan inspection.** Prisma 8 does not expose an `.explain()` method. Workaround: connect a `pg.Pool` you control via the runtime's `pg:` binding (see `references/runtime.md`) and issue `EXPLAIN ANALYZE` through it. If you want a first-class plan-inspection surface, file a feature request via `references/feedback.md`.
|
|
234
235
|
- **Multi-statement batching (Prisma-7-style `db.$transaction([call1, call2])`).** Prisma 8 runs each call sequentially. Workaround: wrap atomically-related work in `db.transaction(async (tx) => { ... })` on Postgres. If you want batch-as-array semantics, file a feature request via `references/feedback.md`.
|
|
235
|
-
- **Mongo façade transactions.** `@
|
|
236
|
+
- **Mongo façade transactions.** `@prisma/orm-mongo/runtime` does not expose `db.transaction(...)`. Multi-document atomicity is not yet wrapped in the Prisma 8 Mongo façade. Workaround: use the MongoDB driver's session API directly if you control the client binding (`mongoClient:` option). File a feature request via `references/feedback.md` if you need a first-class façade surface.
|
|
236
237
|
- **Mongo ORM aggregates.** No `.aggregate(...)` / `.groupBy(...)` on `db.orm.<root>`. Workaround: express aggregations through `db.query.from(...).group(...).build()` and `runtime.query(plan)`.
|
|
237
|
-
- **Mongo filter helpers on the façade.** Rich filters (`.in`, ranges, boolean composition)
|
|
238
|
+
- **Mongo filter helpers on the façade.** Rich filters (`.in`, ranges, boolean composition) are filter expressions built with `MongoFieldFilter` and its siblings from `@prisma/orm-mongo/query-ast/execution`, not from `@prisma/orm-mongo/runtime`, and the ORM's `.where(...)` takes no callback. Use object equality `.where({ field: value })` where it is enough.
|
|
238
239
|
- **Automatic N+1 detection.** Prisma 8 does not warn when an `.include(...)` is missing. Workaround: be deliberate about `.include(...)` in code review; the `lints` middleware (see `references/runtime.md`) catches the more common authoring slips (missing `WHERE` on a `DELETE` / `UPDATE`, missing `LIMIT` on a `SELECT`).
|
|
239
240
|
|
|
240
241
|
## Reference Files
|
|
@@ -13,28 +13,28 @@ This skill does **not** cover migrating from another ORM (Drizzle, Prisma 6/7, S
|
|
|
13
13
|
|
|
14
14
|
## When to Use
|
|
15
15
|
|
|
16
|
-
- User asks *"what can I do with Prisma 8?"*, *"what can I do next with Prisma?"*, *"where do I start?"*, *"what should I do first?"* — and a
|
|
16
|
+
- User asks *"what can I do with Prisma 8?"*, *"what can I do next with Prisma?"*, *"where do I start?"*, *"what should I do first?"* — and a Prisma 8 project already exists on disk. **First-touch orientation** path below.
|
|
17
17
|
- User just ran `createprisma` (or equivalent scaffold tool) and is asking what to do next. **First-touch orientation** path.
|
|
18
18
|
- User is starting a new project and wants to use Prisma 8. **Greenfield** path.
|
|
19
|
-
- User has an existing database (no
|
|
20
|
-
- User typed *"prisma orm init"*, *"get started with
|
|
21
|
-
- User says *"I have an existing Postgres/Mongo, how do I start using
|
|
19
|
+
- User has an existing database (no Prisma 8 contract) and wants to introduce Prisma 8. **Brownfield-DB** path.
|
|
20
|
+
- User typed *"prisma orm init"*, *"get started with Prisma 8"*, *"set up Prisma 8"*, *"how do I scaffold a project"*. **Greenfield** path.
|
|
21
|
+
- User says *"I have an existing Postgres/Mongo, how do I start using Prisma 8?"*. **Brownfield-DB** path.
|
|
22
22
|
|
|
23
23
|
## When Not to Use
|
|
24
24
|
|
|
25
|
-
- User already has a
|
|
26
|
-
- User wants to migrate FROM
|
|
25
|
+
- User already has a Prisma 8 project and wants to add a model → `references/contract.md`.
|
|
26
|
+
- User wants to migrate FROM another ORM → Prisma 8 has no tool for that; see *What Prisma 8 doesn't do yet* below.
|
|
27
27
|
- User wants to wire `db.ts` in a project that already has a contract → `references/runtime.md`.
|
|
28
28
|
- User wants to integrate Prisma 8 with a build tool (Vite plugin, Next.js, …) → `references/build.md`.
|
|
29
29
|
|
|
30
30
|
## Key Concepts
|
|
31
31
|
|
|
32
32
|
- **Contract**: the data model. Authored as `contract.prisma` (PSL, the canonical surface) or `contract.ts` (TypeScript builder). The framework reads it and emits two artefacts: `contract.json` (runtime IR) and `contract.d.ts` (types).
|
|
33
|
-
- **Target**: the backing store. Today: `postgres` or `mongodb`. Picked at `init` time; baked into the `@
|
|
33
|
+
- **Target**: the backing store. Today: `postgres` or `mongodb`. Picked at `init` time; baked into the `@prisma/orm-<target>` façade the scaffold imports from.
|
|
34
34
|
- **Authoring mode**: how you write the contract. `psl` (Prisma Schema Language, default) or `typescript` (programmatic builder, optionally paired with the Vite plugin for auto-emit during `vite dev` — see `references/build.md`).
|
|
35
|
-
- **Façade packages.** The scaffold installs exactly one façade per target — `@
|
|
35
|
+
- **Façade packages.** The scaffold installs exactly one façade per target — `@prisma/orm-postgres` (or `@prisma/orm-mongo`). User code imports from façade subpaths (`@prisma/orm-postgres/config`, `@prisma/orm-postgres/runtime`, `@prisma/orm-postgres/static`, `@prisma/orm-postgres/contract-builder`). The façade bakes in the family / target / adapter / driver wiring; never reach past it. See `references/contract.md` for the full list.
|
|
36
36
|
- **`db.ts`**: the runtime entry point. Lives next to the contract source at `src/prisma/db.ts`. Imports the contract artefacts and exports a `db` value the rest of the app uses.
|
|
37
|
-
- **Marker**: a row in the `prisma_contract.marker` table (Postgres) or a document in the `_prisma_migrations` collection (Mongo) that records the contract hash per contract space. Lets
|
|
37
|
+
- **Marker**: a row in the `prisma_contract.marker` table (Postgres) or a document in the `_prisma_migrations` collection (Mongo) that records the contract hash per contract space. Lets Prisma 8 detect drift between contract and live DB. Created by `db init` (greenfield / first-touch orientation) or `db sign` (brownfield).
|
|
38
38
|
|
|
39
39
|
### Canonical on-disk layout
|
|
40
40
|
|
|
@@ -96,9 +96,9 @@ If that prints `[{ id: 1, email: 'alice@example.com' }]`, the project is wired e
|
|
|
96
96
|
|
|
97
97
|
`db.orm.<ns>.<Model>` is the default ORM lane — model-shaped, fully typed against the contract, lazily connects to the database on first use (it picks up `DATABASE_URL` from `.env` via the runtime's `dotenv/config`-loaded environment). The deeper `references/queries.md` reference covers the rest of the supported surface (filters, joins, transactions, the SQL builder, raw SQL via `db.raw.sql`, prepared statements) when the user is ready — and names the gaps (TypedSQL is not available).
|
|
98
98
|
|
|
99
|
-
> **SQLite target:** `prisma orm init` scaffolds only `postgres` and `mongodb`; a SQLite project is wired by hand with the `@
|
|
99
|
+
> **SQLite target:** `prisma orm init` scaffolds only `postgres` and `mongodb`; a SQLite project is wired by hand with the `@prisma/orm-sqlite` façade (`references/runtime.md` § *Switch between Postgres, SQLite, and Mongo*; `examples/prisma-8-demo-sqlite`). SQLite has no schemas, so that façade exposes the unbound namespace directly — write `db.orm.User` rather than `db.orm.public.User`.
|
|
100
100
|
>
|
|
101
|
-
> **Mongo target:** the snippet above is SQL-target shape. On `@
|
|
101
|
+
> **Mongo target:** the snippet above is SQL-target shape. On `@prisma/orm-mongo`, `db.orm` is keyed by the collection's storage name (`@@map(...)`, or the lowercased model name if no `@@map`), so the same arc reads `await db.orm.users.create(...)` / `await db.orm.users.select('id', 'email').all()` — not `db.orm.public.User`. Full rule and rewrite recipe in `references/queries.md` § *MongoDB ORM addressing*.
|
|
102
102
|
|
|
103
103
|
**Prerequisites for the arc to work.** All three paths leave these in place by the time you reach the arc:
|
|
104
104
|
|
|
@@ -112,7 +112,7 @@ The three workflows below each describe how their path gets the user to that sta
|
|
|
112
112
|
|
|
113
113
|
## Workflow — First-touch orientation
|
|
114
114
|
|
|
115
|
-
Triggers: *"what can I do with Prisma 8?"*, *"what can I do next with Prisma?"*, *"where do I start?"*, *"I just ran createprisma"*, *"what's next?"*, or any close variant — paired with a
|
|
115
|
+
Triggers: *"what can I do with Prisma 8?"*, *"what can I do next with Prisma?"*, *"where do I start?"*, *"I just ran createprisma"*, *"what's next?"*, or any close variant — paired with a Prisma 8 project already on disk (scaffolded by `createprisma`, by `prisma orm init`, by a teammate, however).
|
|
116
116
|
|
|
117
117
|
The user's high-level intent is *"I want to be running an application against my database, against this thing called Prisma 8."* The job of this workflow is to anchor them on the contract, get one round-trip working, and let further commands surface organically as their next move requires them. **It is orientation, not a tour, not a feature inventory, not a syllabus.**
|
|
118
118
|
|
|
@@ -219,7 +219,7 @@ Then run the snippet from *Your first arc* above against the `User` model. When
|
|
|
219
219
|
|
|
220
220
|
## Workflow — Brownfield-DB (existing database, no contract)
|
|
221
221
|
|
|
222
|
-
The concept: against an existing database with no
|
|
222
|
+
The concept: against an existing database with no Prisma 8 contract, `contract infer` walks the live schema (tables, columns, indexes — including expression and partial ones — constraints, and RLS enablement + policies) and writes a PSL contract that describes it. Where authoring would generate a CHECK constraint the database does not carry (the element-non-null check on a list column), infer writes the list with nullable elements (`String?[]`), which derives no such check, so the contract declares exactly what the database enforces. The reverse gap is closed too: a hand-written CHECK constraint the database enforces that authoring would never have generated comes back as `@@check(expression: <reprint>, map: "<name>")`, so it is a declared object from the first pull instead of an invisible extra a later destructive plan could drop. That inferred check warns (`PN_EXACT_NAME_BODY_COMPARISON`) the next time you run `contract emit` — expected, not a defect: the warning fires on any `map:` body regardless of who wrote it, and the comparison stays sound because both sides are Postgres's own reprint. Columns come back as the convenience types with their defaults, and only the arguments that differ: `int2` as `Int(storage: int2)`, `numeric(10,2)` as `Decimal(precision: 10, scale: 2)`, `varchar(12)` as `String(storage: varchar, length: 12)`, `json` as `Json`, `jsonb` as `Json(storage: jsonb)`, `timestamptz(3)` as `DateTime` (a JavaScript `Date`), a `timestamptz` with no declared precision as `DateTime(precision: 6)`, `timestamp(3)` as `DateTime(storage: timestamp)`, `date` as `Date`, `time` as `Time` and `interval` as `Duration` (ISO strings). A `Date` holds milliseconds, so a timestamp column whose values use microseconds reads with them dropped: change such a field to `DateTime(as: temporal)` or `DateTime(as: string)` to keep them. The result is a *starting point*, not the final contract — review and clean it up, then `db sign` to record the current contract hash as the marker (instead of letting `db init` try to recreate the schema from scratch). By default `db sign` also sets the `db` ref and stores the contract snapshot, so the next `migration plan` chains from the adopted schema — even when the database is named with `--db`. `--advance-ref <name>` writes another ref instead and `--no-advance-ref` writes none; in either case the next plan needs `--from` or a `db` ref you set yourself.
|
|
223
223
|
|
|
224
224
|
```bash
|
|
225
225
|
mkdir my-app && cd my-app
|
|
@@ -238,9 +238,9 @@ pnpm prisma contract infer --db "$DATABASE_URL" --output src/prisma/contract.pri
|
|
|
238
238
|
|
|
239
239
|
The agent should pause here and read the inferred PSL. Symptoms a re-author pass is needed:
|
|
240
240
|
|
|
241
|
-
- Tables
|
|
242
|
-
- Columns where
|
|
243
|
-
- Missing `@unique` / `@index` hints
|
|
241
|
+
- Tables Prisma 8 couldn't categorise (e.g. legacy linking tables you could express as relations).
|
|
242
|
+
- Columns where Prisma 8's type guess is wrong (e.g. `String` where you want an extension type like `pgvector.Vector(length: 1536)`).
|
|
243
|
+
- Missing `@unique` / `@index` hints Prisma 8 couldn't see.
|
|
244
244
|
- Field names you'd prefer to alias.
|
|
245
245
|
|
|
246
246
|
Then re-emit and sign:
|
|
@@ -266,7 +266,7 @@ A reference table — not a script to recite at the user. Commands surface in th
|
|
|
266
266
|
| Apply pending migrations | `prisma db migrate` | `references/migrations.md` |
|
|
267
267
|
| Inspect the live database | `prisma db schema` | `references/debug.md` |
|
|
268
268
|
| Confirm the DB matches the contract (drift check) | `prisma db verify` | `references/debug.md` |
|
|
269
|
-
| Bring an existing DB into a
|
|
269
|
+
| Bring an existing DB into a Prisma 8 contract | `prisma contract infer --db "$DATABASE_URL"` | this skill (brownfield) |
|
|
270
270
|
| Decode a structured error envelope | (read the `code` / `why` / `fix` fields) | `references/debug.md` |
|
|
271
271
|
| Report a bug or request a feature | (file via the feedback skill) | `references/feedback.md` |
|
|
272
272
|
|
|
@@ -289,8 +289,8 @@ Switch authoring later by re-running `prisma orm init` in the same directory. Th
|
|
|
289
289
|
|
|
290
290
|
## What Prisma 8 doesn't do yet
|
|
291
291
|
|
|
292
|
-
- **Migration from another ORM.** Prisma 8 doesn't migrate your schema *from* Drizzle / Sequelize / TypeORM / Kysely / Knex / a raw driver. A Prisma 6 MongoDB schema and a Prisma 7 Postgres schema are the exception: they can be the contract source as they are (`prisma6Schema` / `prisma7Schema`, see `references/contract.md`). For the others
|
|
293
|
-
- **`prisma db push`-style production sync.** `db update` is for databases whose migration history does not need to be kept (local, development, staging, preview); for production, use migrations (`migration plan` + `db migrate`).
|
|
292
|
+
- **Migration from another ORM.** Prisma 8 doesn't migrate your schema *from* Drizzle / Sequelize / TypeORM / Kysely / Knex / a raw driver. A Prisma 6 MongoDB schema and a Prisma 7 Postgres schema are the exception: they can be the contract source as they are (`prisma6Schema` / `prisma7Schema`, see `references/contract.md`). For the others, treat the source as a brownfield database. On Postgres, `contract infer` writes a contract from it. Only the Postgres target implements inference: on SQLite, MySQL and MongoDB, `contract infer` fails with `CONTRACT.INFER_UNSUPPORTED`, so write the contract by hand. If you need a guided migration flow built-in, file a feature request via the `references/feedback.md` skill.
|
|
293
|
+
- **`prisma db push`-style production sync.** `db update` is for databases whose migration history does not need to be kept (local, development, staging, preview); for production, use migrations (`migration plan` + `db migrate`). Prisma 8 deliberately does not offer a "push-to-prod-without-a-migration" surface — see `references/migrations.md`.
|
|
294
294
|
- **Studio / GUI database browser.** Use `prisma db schema` for a CLI tree-style summary of the live DB. If you need an interactive UI, file a feature request via the `references/feedback.md` skill.
|
|
295
295
|
|
|
296
296
|
## Reference Files
|
|
@@ -11,7 +11,7 @@ This skill covers the **runtime entry point** — `db.ts` — and how to compose
|
|
|
11
11
|
- User wants to add middleware (lints, budgets, cache, custom).
|
|
12
12
|
- User wants per-environment config (dev vs prod, multi-region).
|
|
13
13
|
- User wants to switch between the Postgres, SQLite, and Mongo façades.
|
|
14
|
-
- User wants to wrap operations in `db.transaction(...)` (Postgres, SQLite and Supabase role-bound clients).
|
|
14
|
+
- User wants to wrap operations in `db.transaction(...)` (Postgres, SQLite, MySQL, MariaDB and Supabase role-bound clients).
|
|
15
15
|
- User is running a one-off script (`tsx my-script.ts`, Node CLI, CI task) and the process won't exit after queries finish, or they need script teardown (`db.close()`, `await using`).
|
|
16
16
|
- User is deploying to a per-request runtime (Cloudflare Workers + Hyperdrive, AWS Lambda, Vercel Edge, Deno Deploy, Bun edge) and needs `postgresServerless()` with `postgres.connect({ url })` per request.
|
|
17
17
|
- User mentions: *db.ts, postgres(), mongo(), middleware, lints, budgets, cache, query log, slow query, DATABASE_URL, .env, connection pool, poolOptions, dev vs prod, transactions, read replicas, multi-database, script won't exit, hangs, db.close, db.end, close connection, pool.end, await using, serverless, edge, Cloudflare Workers, Hyperdrive, postgresServerless, connect per request*.
|
|
@@ -27,8 +27,8 @@ This skill covers the **runtime entry point** — `db.ts` — and how to compose
|
|
|
27
27
|
|
|
28
28
|
## Key Concepts
|
|
29
29
|
|
|
30
|
-
- **`db.ts` is the runtime entry point.** Imports the runtime factory from the `@
|
|
31
|
-
- **`db.ts` imports only from the façade's `/runtime` and `/static` entry points.** Each factory is a *default* export. For Postgres: `import postgres from '@
|
|
30
|
+
- **`db.ts` is the runtime entry point.** Imports the runtime factory from the `@prisma/orm-<target>` façade (`@prisma/orm-postgres/runtime`, `@prisma/orm-sqlite/runtime`, or `@prisma/orm-mongo/runtime`), `contractFromJson` from the same façade's `/static` entry point, the contract artefacts (`contract.json` + the `Contract` type from `contract.d.ts`), and any middleware. Exports the typed `contract` and a `db` value the rest of your app imports. On a per-request runtime, `db.ts` imports `postgresServerless` from `@prisma/orm-postgres/serverless` instead and exports the serverless client `postgres`; see *Workflow — Serverless and per-request runtimes*.
|
|
31
|
+
- **`db.ts` imports only from the façade's `/runtime` and `/static` entry points.** Each factory is a *default* export. For Postgres: `import postgres from '@prisma/orm-postgres/runtime'`; SQLite: `import sqlite from '@prisma/orm-sqlite/runtime'`; Mongo: `import mongo from '@prisma/orm-mongo/runtime'`. The factory takes one options object and no type argument: it infers the contract type from `contract`. Turn the emitted JSON into a typed value once with `contractFromJson<Contract>(contractJson)` from the façade's `/static` entry point (`@prisma/orm-postgres/static`, `@prisma/orm-sqlite/static`, `@prisma/orm-mongo/static`; Supabase uses the Postgres one). That call is the only place you write the `Contract` type argument. A contract written in TypeScript with `defineContract` is already a typed value and goes to `{ contract }` directly. A contract value is validated once, however many clients use it.
|
|
32
32
|
- **Lazy connect.** The factory does not connect to the database synchronously. `db.sql` and `db.orm` are available immediately; the driver / pool is instantiated on the first call that needs a runtime (or when you explicitly call `await db.connect({ url })`, which binds the client to that URL), and the pool opens its first database connection on the first query. This is why `db.ts` can be imported in modules that load before the env is ready.
|
|
33
33
|
- **Middleware composes in order.** Every hook runs in the order of the `middleware: [...]` array — the first middleware's `beforeEncode` sees the statement first, and `intercept.onQuery` handlers are consulted in registration order with the first non-`undefined` result winning. Register a cache first so it gets first claim on a hit. Every middleware's `activityEnded` still fires on a cache hit, with `result.source: 'middleware'`.
|
|
34
34
|
- **`prisma.config.ts` vs `.env`.** The config (`definePrismaConfig({ orm: ormConfig({ contract, db, extensions, migrations }) })` — see `references/contract.md`) is for static project shape: contract path, installed extensions, migrations directory, default connection string. `.env` is for per-environment values (`DATABASE_URL`, secrets). Nothing reads `.env` on its own: the scaffolded `prisma.config.ts` starts with `import 'dotenv/config'`, and that import is what loads `.env` into `process.env` before the config (and the CLI running it) reads `process.env['DATABASE_URL']`. Keep the import; a config without it sees no `.env` values. Hardcoding `DATABASE_URL` in the config file leaks credentials and bypasses per-env overrides.
|
|
@@ -42,8 +42,8 @@ The concept: `db.ts` is the seam between the emitted contract artefacts (target-
|
|
|
42
42
|
|
|
43
43
|
```typescript
|
|
44
44
|
// src/prisma/db.ts
|
|
45
|
-
import postgres from '@
|
|
46
|
-
import { contractFromJson } from '@
|
|
45
|
+
import postgres from '@prisma/orm-postgres/runtime';
|
|
46
|
+
import { contractFromJson } from '@prisma/orm-postgres/static';
|
|
47
47
|
import type { Contract } from './contract.d';
|
|
48
48
|
import contractJson from './contract.json' with { type: 'json' };
|
|
49
49
|
|
|
@@ -63,7 +63,7 @@ Three things to know:
|
|
|
63
63
|
- **`with { type: 'json' }` is required.** Node's ESM JSON-import-attribute spec. Without it, the import errors.
|
|
64
64
|
- **`url` is optional at construct time.** If `DATABASE_URL` is not set when `db.ts` loads, the factory still returns a client; you can call `await db.connect({ url })` later. The factory throws lazily — only when a runtime is actually needed.
|
|
65
65
|
|
|
66
|
-
The Mongo façade has the same construction shape — `import mongo from '@
|
|
66
|
+
The Mongo façade has the same construction shape — `import mongo from '@prisma/orm-mongo/runtime'` — and the same `db.connect(...)` / `db.close()` lifecycle methods. **The Mongo façade does not expose `db.transaction(...)`.** See *What Prisma 8 doesn't do yet* for the workaround. **The ORM surface differs in one place: keys.** On Mongo, `db.orm` is keyed by the collection's storage name (from `@@map(...)`, or the lowercased model name if no `@@map` is set), not by the PSL model name — so `model User { … @@map("users") }` is reached at `db.orm.users`, not `db.orm.public.User`. The SQL builder lane (`db.sql.<ns>.<table>`) doesn't exist on Mongo at all (`db.sql` is `undefined`). See `references/queries.md` § *MongoDB ORM addressing* for the full rule and a rewrite recipe for SQL-target examples.
|
|
67
67
|
|
|
68
68
|
## Workflow — Running as a script (teardown)
|
|
69
69
|
|
|
@@ -86,7 +86,7 @@ await db.close();
|
|
|
86
86
|
|
|
87
87
|
```typescript
|
|
88
88
|
// src/scripts/hello.ts — top-level await in a script module
|
|
89
|
-
import postgres from '@
|
|
89
|
+
import postgres from '@prisma/orm-postgres/runtime';
|
|
90
90
|
import { contract } from '../prisma/db';
|
|
91
91
|
|
|
92
92
|
await using db = postgres({ contract, url: process.env.DATABASE_URL! });
|
|
@@ -139,12 +139,12 @@ Servers (HTTP handlers, workers in a request loop) **do not call `db.close()`**
|
|
|
139
139
|
|
|
140
140
|
## Workflow — Serverless and per-request runtimes
|
|
141
141
|
|
|
142
|
-
The concept: a per-request runtime (Cloudflare Workers + Hyperdrive, AWS Lambda, Vercel Edge, Deno Deploy, Bun edge) must not keep a database connection at module scope. Use `postgresServerless()` from `@
|
|
142
|
+
The concept: a per-request runtime (Cloudflare Workers + Hyperdrive, AWS Lambda, Vercel Edge, Deno Deploy, Bun edge) must not keep a database connection at module scope. Use `postgresServerless()` from `@prisma/orm-postgres/serverless`. It returns a **serverless client**; name it `postgres`. It holds no database connection. In each request, open a **connection** named `db` with `await using db = await postgres.connect({ url })`. A connection owns one database connection, a `pg.Client`, and `await using` closes it when the handler returns. `db` has the members of a `postgres()` client except `connect`.
|
|
143
143
|
|
|
144
144
|
```typescript
|
|
145
145
|
// src/prisma/db.ts — the serverless client: module scope, built once per isolate, holds no database connection
|
|
146
|
-
import postgresServerless from '@
|
|
147
|
-
import { contractFromJson } from '@
|
|
146
|
+
import postgresServerless from '@prisma/orm-postgres/serverless';
|
|
147
|
+
import { contractFromJson } from '@prisma/orm-postgres/static';
|
|
148
148
|
import type { Contract } from './contract.d';
|
|
149
149
|
import contractJson from './contract.json' with { type: 'json' };
|
|
150
150
|
|
|
@@ -218,8 +218,8 @@ The concept: lints catch authoring mistakes that survive type-check (e.g. `DELET
|
|
|
218
218
|
Both are exported from the façade's `family-runtime` subpath — `@prisma/orm-postgres/family-runtime` (and `@prisma/orm-sqlite/family-runtime`, `@prisma/orm-mongo/family-runtime`). `examples/prisma-8-demo/src/prisma/db.ts` shows the canonical import.
|
|
219
219
|
|
|
220
220
|
```typescript
|
|
221
|
-
import postgres from '@
|
|
222
|
-
import { contractFromJson } from '@
|
|
221
|
+
import postgres from '@prisma/orm-postgres/runtime';
|
|
222
|
+
import { contractFromJson } from '@prisma/orm-postgres/static';
|
|
223
223
|
import { budgets, lints } from '@prisma/orm-postgres/family-runtime';
|
|
224
224
|
import type { Contract } from './contract.d';
|
|
225
225
|
import contractJson from './contract.json' with { type: 'json' };
|
|
@@ -357,7 +357,7 @@ export const db = postgres({
|
|
|
357
357
|
|
|
358
358
|
## Workflow — Transactions
|
|
359
359
|
|
|
360
|
-
The concept applies to **Postgres, SQLite and Supabase**. `db.transaction(fn)` opens a transaction, passes the callback a `tx`, commits when the callback returns and rolls back when it throws. `tx` offers the client's query members with the same types: `sql`, `orm` (with the client's custom collection classes), `raw`, `prepare`, `query` (rows), `execute` (affected count) and `toSql`. Postgres and serverless-connection transactions also have `enums` and `nativeEnums`; SQLite's
|
|
360
|
+
The concept applies to **Postgres, SQLite, MySQL, MariaDB and Supabase**. `db.transaction(fn)` opens a transaction, passes the callback a `tx`, commits when the callback returns and rolls back when it throws. `tx` offers the client's query members with the same types: `sql`, `orm` (with the client's custom collection classes), `raw`, `prepare`, `query` (rows), `execute` (affected count) and `toSql`. Postgres and serverless-connection transactions also have `enums` and `nativeEnums`; SQLite's, MySQL's and MariaDB's have `enums`. `tx` has no `close`, `[Symbol.asyncDispose]` or `runtime()`. `tx.transaction(async (inner) => ...)` runs a nested transaction in a savepoint on every one of them, and `inner` has the same members as `tx`; see *Workflow — Transactions* in `references/queries-postgres.md`. Inside the callback, send every query through `tx`, not `db`, so it runs inside the transaction. A Supabase role-bound client (`asUser`, `asAnon`, `asServiceRole`) has `transaction(fn)` too, and its `tx` runs every statement under the bound role. The Mongo façade does not expose `db.transaction(...)`.
|
|
361
361
|
|
|
362
362
|
```typescript
|
|
363
363
|
await db.transaction(async (tx) => {
|
|
@@ -384,14 +384,14 @@ await db.transaction(async (tx) => {
|
|
|
384
384
|
|
|
385
385
|
## Workflow — Switch between Postgres, SQLite, and Mongo
|
|
386
386
|
|
|
387
|
-
The concept: the façade selection is baked into `db.ts` (`@
|
|
387
|
+
The concept: the façade selection is baked into `db.ts` (`@prisma/orm-postgres` or `@prisma/orm-mongo`) and `prisma.config.ts` (which target's `config` subpath `ormConfig` is imported from). To switch a project's target, re-run `prisma orm init` in the same directory and pick the other target — the init flow detects the existing scaffold and prompts to reinit (non-interactive runs grant the consent with `--confirm <directory name>`). Prisma 8 re-scaffolds `prisma.config.ts` and `db.ts` for the new façade. The contract source needs to be re-authored for the new target's idioms (Mongo expresses nested documents; Postgres expresses relations).
|
|
388
388
|
|
|
389
389
|
After the switch (Mongo):
|
|
390
390
|
|
|
391
391
|
```typescript
|
|
392
392
|
// src/prisma/db.ts (Mongo)
|
|
393
|
-
import mongo from '@
|
|
394
|
-
import { contractFromJson } from '@
|
|
393
|
+
import mongo from '@prisma/orm-mongo/runtime';
|
|
394
|
+
import { contractFromJson } from '@prisma/orm-mongo/static';
|
|
395
395
|
import type { Contract } from './contract.d';
|
|
396
396
|
import contractJson from './contract.json' with { type: 'json' };
|
|
397
397
|
|
|
@@ -403,8 +403,8 @@ SQLite:
|
|
|
403
403
|
|
|
404
404
|
```typescript
|
|
405
405
|
// src/prisma/db.ts (SQLite)
|
|
406
|
-
import sqlite from '@
|
|
407
|
-
import { contractFromJson } from '@
|
|
406
|
+
import sqlite from '@prisma/orm-sqlite/runtime';
|
|
407
|
+
import { contractFromJson } from '@prisma/orm-sqlite/static';
|
|
408
408
|
import type { Contract } from './contract.d';
|
|
409
409
|
import contractJson from './contract.json' with { type: 'json' };
|
|
410
410
|
|
|
@@ -420,7 +420,7 @@ The `db.sql` / `db.orm` surfaces stay the same in name; the operators each surfa
|
|
|
420
420
|
|
|
421
421
|
If you want contract artefacts to re-emit automatically while the dev server is running (instead of running `prisma contract emit` by hand each time the contract source changes), reach for the build-tool plugin from `references/build.md`:
|
|
422
422
|
|
|
423
|
-
- **Vite**:
|
|
423
|
+
- **Vite**: import `prismaVitePlugin` from `@prisma/orm-<target>/vite-plugin-contract-emit` and register `prismaVitePlugin('prisma.config.ts')` in `vite.config.ts`.
|
|
424
424
|
- **Next.js, Webpack, esbuild, Rollup, Turbopack**: no first-party plugin yet — the workaround is a `prebuild` script that runs `prisma contract emit`. See `references/build.md` for the walkthrough.
|
|
425
425
|
|
|
426
426
|
The runtime side (this skill) is the same regardless: `db.ts` reads `contract.json` + `contract.d.ts` from disk. The build-system plugin's job is to keep those files current during development.
|
|
@@ -431,7 +431,7 @@ The runtime side (this skill) is the same regardless: `db.ts` reads `contract.js
|
|
|
431
431
|
2. **Writing the type argument on the client, or passing `contractJson`.** `postgres<Contract>({ contractJson })` no longer compiles: the clients take `{ contract }` and infer its type. Write `contractFromJson<Contract>(contractJson)` and pass the result. Omitting `<Contract>` there collapses the static surfaces to a generic shape and you lose autocomplete for models.
|
|
432
432
|
3. **Forgetting `with { type: 'json' }` on the contract import.** Required by Node's ESM JSON-import-attribute spec.
|
|
433
433
|
4. **Middleware order matters.** Registration order is hook order; put the cache first so its `intercept.onActivity` and `intercept.onQuery` are consulted first.
|
|
434
|
-
5. **Importing middleware from a non-existent package or subpath.**
|
|
434
|
+
5. **Importing middleware from a non-existent package or subpath.** The Postgres package has no `middleware` subpath, and there is no telemetry middleware package. `lints` / `budgets` / `SqlMiddleware` come from `@prisma/orm-postgres/family-runtime`; the cache comes from `@prisma/orm-extension-middleware-cache`; a query log or telemetry hook is a custom `activityEnded` middleware (above).
|
|
435
435
|
6. **Confabulating lint / budget option names.** Lints take `severities` (with the five keys above), not `requireWhere` / `maxRowsWithoutLimit`. Budgets use `maxLatencyMs` (not `maxDurationMs`) plus `maxRows` / `defaultTableRows` / `tableRows`. When in doubt, read the source.
|
|
436
436
|
7. **Switching targets without re-emitting.** The contract artefacts are target-shaped; emit after the target change.
|
|
437
437
|
8. **Script hangs after queries finish on Postgres.** The `pg.Pool` keeps Node's event loop alive. Solution: `await db.close()` before the script returns, or `await using db = postgres({ contract, ... })` at the top of a script module. Do not put `await using db = postgres(...)` inside a request handler — it's block-scoped and would close the pool after every request. The right server pattern is a module-level singleton in `db.ts` that lives for the process lifetime. On a per-request runtime, use `postgresServerless()` and `await using db = await postgres.connect({ url })` in the handler instead (see *Workflow — Serverless and per-request runtimes*).
|
|
@@ -449,7 +449,7 @@ This skill is intentionally body-only; `prisma orm init --help`, the target `def
|
|
|
449
449
|
|
|
450
450
|
## Checklist
|
|
451
451
|
|
|
452
|
-
- [ ] `db.ts` imports the runtime factory from `@
|
|
452
|
+
- [ ] `db.ts` imports the runtime factory from `@prisma/orm-<target>/runtime` (`postgres`, `sqlite`, or `mongo`), `contractFromJson` from `@prisma/orm-<target>/static`, and the `Contract` type from `./contract.d`.
|
|
453
453
|
- [ ] `with { type: 'json' }` on the contract JSON import.
|
|
454
454
|
- [ ] `Contract` is named once, on `contractFromJson<Contract>(contractJson)`, and the client gets `{ contract }` with no type argument.
|
|
455
455
|
- [ ] `DATABASE_URL` lives in `.env`, not in `prisma.config.ts`.
|
|
@@ -457,7 +457,7 @@ This skill is intentionally body-only; `prisma orm init --help`, the target `def
|
|
|
457
457
|
- [ ] `lints` / `budgets` imported from `@prisma/orm-postgres/family-runtime` and using the verified option keys (`severities`, `maxLatencyMs`, `maxRows`, `tableRows`).
|
|
458
458
|
- [ ] Per-env divergence (if any) gated by `NODE_ENV` or similar.
|
|
459
459
|
- [ ] Did NOT hardcode credentials in any committed file.
|
|
460
|
-
- [ ] Did NOT confabulate a
|
|
461
|
-
- [ ] Did NOT claim `db.transaction(...)` exists on the Mongo façade — only Postgres, SQLite and Supabase role-bound clients expose it.
|
|
460
|
+
- [ ] Did NOT confabulate a `middleware` subpath on the Postgres package, a telemetry middleware package, an audit extension package, or a type argument or `contractJson` option on `postgres(...)`.
|
|
461
|
+
- [ ] Did NOT claim `db.transaction(...)` exists on the Mongo façade — only Postgres, SQLite, MySQL, MariaDB and Supabase role-bound clients expose it.
|
|
462
462
|
- [ ] Did NOT confabulate read-replica / multi-DB / extra pool config — pointed at *What Prisma 8 doesn't do yet* and routed to `references/feedback.md`.
|
|
463
463
|
- [ ] For build-system / dev-server prompts (Vite plugin, Next.js plugin, …) routed to `references/build.md`.
|
|
@@ -23,7 +23,7 @@ This skill covers using Prisma 8 against a **Supabase** project end-to-end: comp
|
|
|
23
23
|
|
|
24
24
|
## Key Concepts
|
|
25
25
|
|
|
26
|
-
- **The pack is an `external` contract space.** `@
|
|
26
|
+
- **The pack is an `external` contract space.** `@prisma/orm-extension-supabase/pack` ships a complete, introspection-generated contract of everything Supabase owns — the `auth` and `storage` schemas, their native enum types, and the platform roles (`anon`, `authenticated`, `service_role`) — all with control policy `external`. Composed via `extensions`, it means: the migration planner **emits no DDL** for those objects (Supabase manages them), and `db verify` **confirms they exist** in the live database. Your own tables stay `managed` as usual.
|
|
27
27
|
- **Roles come from the pack; you never declare them.** RLS `roles = [authenticated]` identifiers resolve against the composed contract. Pointing the runtime at a non-Supabase Postgres fails verify with a `not-found` issue naming the missing role — the common "wrong database" misconfiguration surfaces before queries run.
|
|
28
28
|
- **The runtime is role-first.** `supabase()` returns a `SupabaseDb` with **no top-level query surface** — there is no `db.sql` / `db.orm` until you bind a role. `await db.asUser(jwt)` / `db.asAnon()` / `db.asServiceRole()` each return a `RoleBoundDb` exposing `.sql`, `.orm`, `.raw`, `.prepare(...)`, `.query(plan)` (rows), `.execute(plan)` (affected count), `.enums`, `.nativeEnums`, and `.transaction(fn)`. This is deliberate: in a Supabase app there is no meaningful "no role" execution context, and defaulting to the connection's login role is a silent-RLS-bypass footgun.
|
|
29
29
|
- **Role binding is below middleware and cannot leak.** Each role-bound query runs on a connection that had `set_config('role', …)` and `set_config('request.jwt.claims', …)` applied beneath the user-middleware chain, with `RESET ALL` on release. Postgres-side `auth.uid()` / `auth.jwt()` read those session vars — RLS enforcement is Postgres's job; the runtime's job is binding the context.
|
|
@@ -38,8 +38,8 @@ The concept: the pack registers the Supabase contract space so your contract can
|
|
|
38
38
|
```typescript
|
|
39
39
|
// prisma.config.ts
|
|
40
40
|
import { definePrismaConfig } from '@prisma/cli-engine';
|
|
41
|
-
import supabasePack from '@
|
|
42
|
-
import { defineConfig as ormConfig } from '@
|
|
41
|
+
import supabasePack from '@prisma/orm-extension-supabase/pack';
|
|
42
|
+
import { defineConfig as ormConfig } from '@prisma/orm-postgres/config';
|
|
43
43
|
|
|
44
44
|
export default definePrismaConfig({
|
|
45
45
|
orm: ormConfig({
|
|
@@ -97,7 +97,7 @@ The pieces:
|
|
|
97
97
|
- **Per-operation policy blocks**: `policy_select`, `policy_insert`, `policy_update`, `policy_delete`, `policy_all`. Body is `key = value`: `target` (a model in this namespace), `roles` (resolve against the composed contract — the pack supplies `anon` / `authenticated` / `service_role`), `using`, and (for write operations) `withCheck`. `using` and `withCheck` are `sql` literals, as in `` using = sql`"userId"::uuid = auth.uid()` ``; a quoted string is refused, and the error message gives the rewrite. Multiple permissive policies per `(target, operation)` are valid — Postgres ORs them. A block may also carry `@@map("physical name")` to adopt an existing live policy under its exact name (no wire-name hash; drift detection then byte-compares the body against Postgres's reprint, so keep the text as captured — hand-authoring it warns).
|
|
98
98
|
- **`@@rls` is required on policy targets.** A `policy_*` block whose target model lacks `@@rls` fails emit with `PSL_EXTENSION_TARGET_MODEL_MISSING_ATTRIBUTE`. A model with `@@rls` and *no* policies is also meaningful: RLS enabled, deny-all.
|
|
99
99
|
- **Predicates are `sql` literals holding verbatim SQL.** Quote camelCase column names inside them with ordinary double quotes (`"userId"`; inside a backtick `sql` literal the only escapes are `` \` `` and `\\`), and cast where needed — `auth.uid()` returns `uuid`. Renames in your contract do not rewrite predicate bodies.
|
|
100
|
-
- **TS-builder parity exists.** `@
|
|
100
|
+
- **TS-builder parity exists.** `@prisma/orm-postgres/contract-builder` exports `policySelect` / `policyInsert` / `policyUpdate` / `policyDelete` / `policyAll`, `rlsEnabled(Model)`, and `role('anon')` — mirroring the PSL lowering key-for-key (identical emitted wire names). PSL is the canonical path shown here.
|
|
101
101
|
|
|
102
102
|
Emit + migrate as usual (`prisma contract emit`, then `references/migrations.md`). The plan creates your table, its FK, `ENABLE ROW LEVEL SECURITY`, and the `CREATE POLICY` statements — and **no DDL for `auth.*`**.
|
|
103
103
|
|
|
@@ -107,8 +107,8 @@ The concept: instead of the stock `postgres()` factory, a Supabase app builds it
|
|
|
107
107
|
|
|
108
108
|
```typescript
|
|
109
109
|
// src/prisma/db.ts
|
|
110
|
-
import { supabase } from '@
|
|
111
|
-
import { contractFromJson } from '@
|
|
110
|
+
import { supabase } from '@prisma/orm-extension-supabase/runtime';
|
|
111
|
+
import { contractFromJson } from '@prisma/orm-postgres/static';
|
|
112
112
|
import type { Contract } from './contract.d';
|
|
113
113
|
import contractJson from './contract.json' with { type: 'json' };
|
|
114
114
|
|
|
@@ -226,7 +226,7 @@ The concept: the runtime needs a **direct, session-capable** Postgres connection
|
|
|
226
226
|
- [ ] `extensions: [supabasePack]` (the `pack` export) in `ormConfig({...})` inside `definePrismaConfig({ orm: ... })`.
|
|
227
227
|
- [ ] Cross-space FK typed `supabase:auth.AuthUser` with explicit `fields` / `references` (+ `onDelete` if wanted).
|
|
228
228
|
- [ ] Every policy target model carries `@@rls`; predicates quote camelCase columns and cast for `auth.uid()`.
|
|
229
|
-
- [ ] `db.ts` uses `await supabase({ contract, url, jwksUrl | jwtSecret })`, with `contract` from `contractFromJson<Contract>(contractJson)` of `@
|
|
229
|
+
- [ ] `db.ts` uses `await supabase({ contract, url, jwksUrl | jwtSecret })`, with `contract` from `contractFromJson<Contract>(contractJson)` of `@prisma/orm-postgres/static` — exactly one JWT key source; `jwksUrl` for current projects, `jwtSecret` only for legacy HS256.
|
|
230
230
|
- [ ] Queries go through a `RoleBoundDb` from `asUser` / `asAnon` / `asServiceRole`; `asUser` is awaited.
|
|
231
231
|
- [ ] `auth.*` / `storage.*` reads go through `asServiceRole().supabase` only, after the one-time narrow grant (`GRANT USAGE ON SCHEMA auth` + `GRANT SELECT` on the tables you read).
|
|
232
232
|
- [ ] No per-table grants added for your own `public` tables — Supabase default privileges cover them; RLS does the protecting.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Upgrade Prisma 8 (user app)
|
|
2
2
|
|
|
3
|
-
This reference upgrades a project that **consumes** Prisma 8 via the public package API (`@prisma/orm-postgres`, `@prisma/orm-mongo`, `@prisma/orm-sqlite`, the contract files in `prisma/`, etc.). Package names below are the published `@prisma/orm-*` names, which is what `package.json`, the lockfile, and the registry use
|
|
3
|
+
This reference upgrades a project that **consumes** Prisma 8 via the public package API (`@prisma/orm-postgres`, `@prisma/orm-mongo`, `@prisma/orm-sqlite`, the contract files in `prisma/`, etc.). Package names below are the published `@prisma/orm-*` names, which is what `package.json`, the lockfile, and the registry use. The other references in this skill use the same names. If the project is itself a Prisma 8 *extension*, use [`upgrade-extension.md`](upgrade-extension.md) instead — or both, if the repo contains both an app and an extension package.
|
|
4
4
|
|
|
5
5
|
The per-transition instructions this reference reads live under [`../upgrading/app/upgrades/`](../upgrading/app/upgrades/).
|
|
6
6
|
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"postgres-members-B7ZvxGYc-D_L3NVGm.mjs","names":[],"sources":["../../../../3-targets/postgres/9-facade/dist/postgres-members-B7ZvxGYc.mjs"],"sourcesContent":["import { i as validateTransactionOptions } from \"./postgres-options-CZyV9Him.mjs\";\nimport { ifDefined } from \"@internal/utils/defined\";\nimport { activitySource, delegatingActivitySource, delegatingRuntime, withTransaction, withTransactionMembers } from \"@internal/sql-runtime\";\nimport { orm, prepareQuery } from \"@internal/sql-orm-client\";\n//#region src/runtime/postgres-members.ts\n/**\n* Builds the query members of a Postgres transaction over `txCtx`, so every statement they run goes through the transaction. `query` and `execute` are the transaction's own; `sql`, `raw` and `toSql` are the client's. Preparing sends nothing to the database, so `prepare` uses `prepareRuntime`; the prepared statement runs on the queryable it is given.\n*/\nfunction buildPostgresQueryMembers(options, txCtx) {\n\tconst { context, collections, sql, raw, toSql, prepareRuntime } = options;\n\treturn {\n\t\ttoSql,\n\t\tsql,\n\t\traw,\n\t\torm: orm({\n\t\t\truntime: {\n\t\t\t\tquery(plan) {\n\t\t\t\t\treturn txCtx.query(plan);\n\t\t\t\t},\n\t\t\t\texecute(plan) {\n\t\t\t\t\treturn txCtx.execute(plan);\n\t\t\t\t},\n\t\t\t\t[activitySource]: delegatingActivitySource(() => txCtx)\n\t\t\t},\n\t\t\tcontext,\n\t\t\t...ifDefined(\"collections\", collections)\n\t\t}),\n\t\tprepare(declaration, callback) {\n\t\t\treturn prepareQuery(prepareRuntime, declaration, callback);\n\t\t}\n\t};\n}\nfunction buildPostgresRuntimeBoundMembers(options) {\n\tconst { context, collections, sql, raw, enums, nativeEnums, toSql, getRuntime, getRuntimeForWork, transactionOptions } = options;\n\tconst workRuntime = delegatingRuntime(getRuntimeForWork);\n\tconst orm$1 = orm({\n\t\truntime: workRuntime,\n\t\tcontext,\n\t\t...ifDefined(\"collections\", collections)\n\t});\n\tfunction prepare(declaration, callback) {\n\t\treturn prepareQuery(workRuntime, declaration, callback);\n\t}\n\treturn {\n\t\torm: orm$1,\n\t\tquery: workRuntime.query,\n\t\texecute: workRuntime.execute,\n\t\truntime() {\n\t\t\treturn getRuntime();\n\t\t},\n\t\tprepare,\n\t\tasync transaction(fn, localOptions) {\n\t\t\tconst local = validateTransactionOptions(localOptions);\n\t\t\tconst isolationLevel = local?.isolationLevel !== void 0 ? local.isolationLevel : transactionOptions?.isolationLevel;\n\t\t\tconst timeout = local?.timeout !== void 0 ? local.timeout : transactionOptions?.timeout;\n\t\t\treturn withTransaction(workRuntime, (txCtx) => {\n\t\t\t\treturn fn(withTransactionMembers(txCtx, {\n\t\t\t\t\t...buildPostgresQueryMembers({\n\t\t\t\t\t\tcontext,\n\t\t\t\t\t\tcollections,\n\t\t\t\t\t\tsql,\n\t\t\t\t\t\traw,\n\t\t\t\t\t\ttoSql,\n\t\t\t\t\t\tprepareRuntime: workRuntime\n\t\t\t\t\t}, txCtx),\n\t\t\t\t\tenums,\n\t\t\t\t\tnativeEnums\n\t\t\t\t}));\n\t\t\t}, {\n\t\t\t\tisolationLevel,\n\t\t\t\ttimeout\n\t\t\t});\n\t\t}\n\t};\n}\n//#endregion\nexport { buildPostgresRuntimeBoundMembers as n, buildPostgresQueryMembers as t };\n\n//# sourceMappingURL=postgres-members-B7ZvxGYc.mjs.map"],"mappings":";;;;;;;;AAQA,SAAS,0BAA0B,SAAS,OAAO;CAClD,MAAM,EAAE,SAAS,aAAa,KAAK,KAAK,OAAO,mBAAmB;CAClE,OAAO;EACN;EACA;EACA;EACA,KAAK,IAAI;GACR,SAAS;IACR,MAAM,MAAM;KACX,OAAO,MAAM,MAAM,IAAI;IACxB;IACA,QAAQ,MAAM;KACb,OAAO,MAAM,QAAQ,IAAI;IAC1B;KACC,iBAAiB,+BAA+B,KAAK;GACvD;GACA;GACA,GAAG,UAAU,eAAe,WAAW;EACxC,CAAC;EACD,QAAQ,aAAa,UAAU;GAC9B,OAAO,aAAa,gBAAgB,aAAa,QAAQ;EAC1D;CACD;AACD;AACA,SAAS,iCAAiC,SAAS;CAClD,MAAM,EAAE,SAAS,aAAa,KAAK,KAAK,OAAO,aAAa,OAAO,YAAY,mBAAmB,uBAAuB;CACzH,MAAM,cAAc,kBAAkB,iBAAiB;CACvD,MAAM,QAAQ,IAAI;EACjB,SAAS;EACT;EACA,GAAG,UAAU,eAAe,WAAW;CACxC,CAAC;CACD,SAAS,QAAQ,aAAa,UAAU;EACvC,OAAO,aAAa,aAAa,aAAa,QAAQ;CACvD;CACA,OAAO;EACN,KAAK;EACL,OAAO,YAAY;EACnB,SAAS,YAAY;EACrB,UAAU;GACT,OAAO,WAAW;EACnB;EACA;EACA,MAAM,YAAY,IAAI,cAAc;GACnC,MAAM,QAAQ,2BAA2B,YAAY;GACrD,MAAM,iBAAiB,OAAO,mBAAmB,KAAK,IAAI,MAAM,iBAAiB,oBAAoB;GACrG,MAAM,UAAU,OAAO,YAAY,KAAK,IAAI,MAAM,UAAU,oBAAoB;GAChF,OAAO,gBAAgB,cAAc,UAAU;IAC9C,OAAO,GAAG,uBAAuB,OAAO;KACvC,GAAG,0BAA0B;MAC5B;MACA;MACA;MACA;MACA;MACA,gBAAgB;KACjB,GAAG,KAAK;KACR;KACA;IACD,CAAC,CAAC;GACH,GAAG;IACF;IACA;GACD,CAAC;EACF;CACD;AACD"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"postgres-members-F9CVSrrN-BFAuNPbW.d.mts","names":[],"sources":["../../../../3-targets/postgres/9-facade/dist/postgres-members-F9CVSrrN.d.mts"],"mappings":";;;;;;;;;;;;KAWK,UAAU,kBAAkB,SAAS,aAAa,qBAAqB,qBAAqB,kBAAkB,IAAI,WAAW;;UAExH,qBAAqB,kBAAkB,SAAS,aAAa,qBAAqB,oBAAoB,6BAA6B,cAAc,YAAY,cAAc;WAC1K,KAAK,GAAG;WACR,KAAK,UAAU,WAAW;WAC1B,KAAK,QAAQ;;UAEd,2BAA2B,kBAAkB,SAAS,aAAa,qBAAqB,oBAAoB,6BAA6B,oBAAoB,qBAAqB,WAAW;WAC5L,OAAO,gBAAgB;WACvB,aAAa,sBAAsB;;UAEpC,4BAA4B,kBAAkB,SAAS,aAAa,qBAAqB;WACxF,SAAS,iBAAiB;WAC1B,aAAa;WACb,KAAK,GAAG;WACR,KAAK,QAAQ;WACb,OAAO;WACP,gBAAgB,KAAK;;;;;iBAKf,0BAA0B,kBAAkB,SAAS,aAAa,qBAAqB,mBAAmB,SAAS,4BAA4B,WAAW,eAAe,OAAO,qBAAqB,KAAK,qBAAqB,WAAW,qBAAqB;UACtQ,sBAAsB,kBAAkB,SAAS,qBAAqB,sBAAsB;WAC3F,OAAO,4BAA4B;;UAEpC,4BAA4B,kBAAkB,SAAS,aAAa,qBAAqB,oBAAoB,6BAA6B,cAAc;WACvJ,KAAK,UAAU,WAAW;EACnC,WAAW;EACX,YAAY,GAAG,KAAK,IAAI,2BAA2B,WAAW,kBAAkB,YAAY,IAAI,UAAU,6BAA6B,QAAQ;;UAEvI;EACR,SAAS;GACR,OAAO,iBAAiB"}
|