@prisma/orm-mongo 8.0.0-rc.4-dev.17 → 8.0.0-rc.5-dev.1
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/package.json +11 -10
- package/skills/prisma-8/SKILL.md +84 -0
- package/skills/prisma-8/references/build.md +142 -0
- package/skills/prisma-8/references/contract.md +417 -0
- package/skills/prisma-8/references/debug.md +141 -0
- package/skills/prisma-8/references/feedback.md +251 -0
- package/skills/prisma-8/references/migration-review.md +224 -0
- package/skills/prisma-8/references/migrations.md +519 -0
- package/skills/prisma-8/references/queries-mongo.md +236 -0
- package/skills/prisma-8/references/queries-postgres.md +415 -0
- package/skills/prisma-8/references/queries.md +168 -0
- package/skills/prisma-8/references/quickstart.md +326 -0
- package/skills/prisma-8/references/runtime.md +344 -0
- package/skills/prisma-8/references/supabase.md +244 -0
- package/skills/prisma-8/references/upgrade-app.md +101 -0
- package/skills/prisma-8/references/upgrade-extension.md +105 -0
- package/skills/prisma-8/upgrading/app/upgrades/0.10-to-0.11/instructions.md +56 -0
- package/skills/prisma-8/upgrading/app/upgrades/0.11-to-0.12/instructions.md +381 -0
- package/skills/prisma-8/upgrading/app/upgrades/0.11-to-0.12/re-emit-closed-mongo-contracts.ts +202 -0
- package/skills/prisma-8/upgrading/app/upgrades/0.11-to-0.12/re-emit-domain-namespaced-contracts.ts +201 -0
- package/skills/prisma-8/upgrading/app/upgrades/0.11-to-0.12/re-emit-postgres-public-default.ts +198 -0
- package/skills/prisma-8/upgrading/app/upgrades/0.11-to-0.12/strip-migration-labels-hints.ts +340 -0
- package/skills/prisma-8/upgrading/app/upgrades/0.12-to-0.13/instructions.md +339 -0
- package/skills/prisma-8/upgrading/app/upgrades/0.12-to-0.13/re-emit-mti-variant-link-columns.ts +229 -0
- package/skills/prisma-8/upgrading/app/upgrades/0.13-to-0.14/instructions.md +543 -0
- package/skills/prisma-8/upgrading/app/upgrades/0.13-to-0.14/migration-op-factories-to-methods.ts +290 -0
- package/skills/prisma-8/upgrading/app/upgrades/0.13-to-0.14/uuid-preset-rename.ts +43 -0
- package/skills/prisma-8/upgrading/app/upgrades/0.14-to-0.15/instructions.md +359 -0
- package/skills/prisma-8/upgrading/app/upgrades/0.15-to-0.16/instructions.md +173 -0
- package/skills/prisma-8/upgrading/app/upgrades/0.16-to-0.17/instructions.md +805 -0
- package/skills/prisma-8/upgrading/app/upgrades/0.16-to-0.17/strip-sha256-hash-prefixes.ts +382 -0
- package/skills/prisma-8/upgrading/app/upgrades/0.17-to-8.0.0-rc.1/instructions.md +72 -0
- package/skills/prisma-8/upgrading/app/upgrades/0.7-to-0.8/instructions.md +8 -0
- package/skills/prisma-8/upgrading/app/upgrades/0.8-to-0.9/instructions.md +36 -0
- package/skills/prisma-8/upgrading/app/upgrades/0.8-to-0.9/strip-inline-contracts.ts +226 -0
- package/skills/prisma-8/upgrading/app/upgrades/0.9-to-0.10/instructions.md +86 -0
- package/skills/prisma-8/upgrading/app/upgrades/0.9-to-0.10/stamp-storage-types-kind.ts +360 -0
- package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.1-to-8.0.0-rc.2/instructions.md +588 -0
- package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.2-to-8.0.0-rc.3/instructions.md +5 -0
- package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.3-to-8.0.0-rc.4/instructions.md +158 -0
- package/skills/prisma-8/upgrading/app/upgrades/8.0.0-rc.4-to-8.0.0-rc.5/instructions.md +42 -0
- package/skills/prisma-8/upgrading/extension/upgrades/0.10-to-0.11/instructions.md +276 -0
- package/skills/prisma-8/upgrading/extension/upgrades/0.11-to-0.12/instructions.md +738 -0
- package/skills/prisma-8/upgrading/extension/upgrades/0.11-to-0.12/migrate-contract-testing-imports.ts +97 -0
- package/skills/prisma-8/upgrading/extension/upgrades/0.11-to-0.12/regenerate-extension-public-baseline.ts +223 -0
- package/skills/prisma-8/upgrading/extension/upgrades/0.11-to-0.12/strip-migration-labels-hints.ts +340 -0
- package/skills/prisma-8/upgrading/extension/upgrades/0.12-to-0.13/instructions.md +266 -0
- package/skills/prisma-8/upgrading/extension/upgrades/0.13-to-0.14/instructions.md +522 -0
- package/skills/prisma-8/upgrading/extension/upgrades/0.13-to-0.14/migration-op-factories-to-methods.ts +290 -0
- package/skills/prisma-8/upgrading/extension/upgrades/0.13-to-0.14/uuid-preset-rename.ts +43 -0
- package/skills/prisma-8/upgrading/extension/upgrades/0.14-to-0.15/instructions.md +803 -0
- package/skills/prisma-8/upgrading/extension/upgrades/0.15-to-0.16/instructions.md +219 -0
- package/skills/prisma-8/upgrading/extension/upgrades/0.16-to-0.17/instructions.md +731 -0
- package/skills/prisma-8/upgrading/extension/upgrades/0.16-to-0.17/strip-sha256-hash-prefixes.ts +382 -0
- package/skills/prisma-8/upgrading/extension/upgrades/0.17-to-8.0.0-rc.1/instructions.md +194 -0
- package/skills/prisma-8/upgrading/extension/upgrades/0.7-to-0.8/instructions.md +8 -0
- package/skills/prisma-8/upgrading/extension/upgrades/0.8-to-0.9/instructions.md +57 -0
- package/skills/prisma-8/upgrading/extension/upgrades/0.8-to-0.9/strip-inline-contracts.ts +226 -0
- package/skills/prisma-8/upgrading/extension/upgrades/0.9-to-0.10/instructions.md +150 -0
- package/skills/prisma-8/upgrading/extension/upgrades/0.9-to-0.10/stamp-storage-types-kind.ts +360 -0
- package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.1-to-8.0.0-rc.2/instructions.md +746 -0
- package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.2-to-8.0.0-rc.3/instructions.md +5 -0
- package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.3-to-8.0.0-rc.4/instructions.md +137 -0
- package/skills/prisma-8/upgrading/extension/upgrades/8.0.0-rc.4-to-8.0.0-rc.5/instructions.md +129 -0
|
@@ -0,0 +1,417 @@
|
|
|
1
|
+
|
|
2
|
+
# Prisma Next — Contract Authoring
|
|
3
|
+
|
|
4
|
+
> **Edit your data contract. Prisma handles the rest.**
|
|
5
|
+
|
|
6
|
+
The data contract is the single source of truth for your data layer. You edit a contract source — `contract.prisma` (PSL, the canonical surface) or `contract.ts` (TypeScript builder) — and the framework derives types, migrations, and runtime configuration from it. The three-step user model:
|
|
7
|
+
|
|
8
|
+
1. **You edit your data contract.**
|
|
9
|
+
2. **The system plans the migrations for you.** (`references/migrations.md`)
|
|
10
|
+
3. **If you need data migrations, you edit `migration.ts` and execute it.** (`references/migrations.md`)
|
|
11
|
+
|
|
12
|
+
Behind step 1 the agent runs `prisma contract emit` after every contract edit (or installs the Vite plugin so the bundler runs it on save — see `references/build.md`). Emit reads the contract source through the provider the façade picks based on the file extension of `contract:` in `prisma.config.ts`, then writes two artefacts colocated with the source:
|
|
13
|
+
|
|
14
|
+
- `contract.json` — the canonical, content-hashed Contract IR. Read by the planner, the runtime, and `db verify`.
|
|
15
|
+
- `contract.d.ts` — the precise TypeScript types the runtime + lanes propagate when you import `Contract` from it.
|
|
16
|
+
|
|
17
|
+
Both files are **emitted artefacts**. Edit the source; never the JSON or `.d.ts`.
|
|
18
|
+
|
|
19
|
+
## When to Use
|
|
20
|
+
|
|
21
|
+
- User wants to add, change, or remove a model / field / relation.
|
|
22
|
+
- User wants to add an index, unique constraint, check constraint, enum, or value object (composite type).
|
|
23
|
+
- User wants to add a namespace block (Postgres schema) or a cross-contract foreign key.
|
|
24
|
+
- User wants to set `@@control` on a model or configure `defaultControlPolicy`.
|
|
25
|
+
- User wants to use a custom type from an extension (`pgvector.Vector(length: 1536)`, `cipherstash.EncryptedString({...})`).
|
|
26
|
+
- User wants to install or configure an extension via `extensions: [...]` in `prisma.config.ts`, including `@internal/extension-supabase`.
|
|
27
|
+
- User is migrating between authoring sources (PSL ↔ TypeScript builder).
|
|
28
|
+
- User received `PN-CLI-4002`, `PN-CLI-4003`, or `PN-CLI-4011` from `contract emit`.
|
|
29
|
+
- User mentions: *schema, fields, models, attributes, prisma schema, PSL, contract.prisma, contract.ts, contract.json, contract.d.ts, contract emit, façade imports, `@internal/postgres/config`, `@internal/postgres/contract-builder`, extensions, pgvector, cipherstash, postgis, paradedb, supabase, namespaces, cross-space FK, `@@control`, enums, check constraints, `@@check`, value objects, validations, callbacks, soft delete, paranoid, scopes*. (The last cluster routes to *What Prisma Next doesn't do yet* below.)
|
|
30
|
+
|
|
31
|
+
## When Not to Use
|
|
32
|
+
|
|
33
|
+
- User wants to apply a contract change to the DB → `references/migrations.md`.
|
|
34
|
+
- User wants to write a query against the contract → `references/queries.md`.
|
|
35
|
+
- User wants to wire `db.ts` (runtime entry point, middleware, env config) → `references/runtime.md`.
|
|
36
|
+
- User wants the Vite / bundler integration → `references/build.md`.
|
|
37
|
+
- User wants to set up Prisma Next for the first time → `references/quickstart.md`.
|
|
38
|
+
- User wants a deeper read of a single structured error envelope → `references/debug.md`.
|
|
39
|
+
- User wants to file a missing-feature request → `references/feedback.md`.
|
|
40
|
+
|
|
41
|
+
## Key Concepts
|
|
42
|
+
|
|
43
|
+
- **The `@internal/<target>` façade is the only surface user-authored code imports from.** For a Postgres app: `@internal/postgres/config`, `@internal/postgres/contract-builder`, `@internal/postgres/control`, `@internal/postgres/runtime`. Mongo has the same layout (`@internal/mongo/config`, `@internal/mongo/contract-builder`, `@internal/mongo/runtime`). Each extension publishes its own façade — `@internal/extension-pgvector/control`, `@internal/extension-postgis/control`, `@internal/extension-paradedb/control`. **Never reach into `@internal/cli/*`, `@internal/family-*`, `@internal/target-*`, `@internal/adapter-*`, `@internal/driver-*`, or `@internal/sql-contract-*` from user code.** The façade bakes the family / target / adapter / driver wiring in. See *Common Pitfalls* #4.
|
|
44
|
+
- **Contract source.** A file the framework reads and lowers to the canonical Contract IR. Two flavours, both first-class:
|
|
45
|
+
- **`contract.prisma` (PSL)** — schema-flavoured DSL. Canonical for typical apps and brownfield Prisma users. Wired by `contract: './<path>/contract.prisma'` — the `defineConfig` façade detects the `.prisma` extension and routes through the PSL provider.
|
|
46
|
+
- **`contract.ts` (TypeScript builder)** — programmatic authoring with `defineContract({...}, ({ field, model, rel, type }) => ({...}))` from `@internal/postgres/contract-builder` (or `@internal/mongo/contract-builder`). Wired by `contract: './<path>/contract.ts'` — the façade detects the `.ts` extension and routes through the TS provider. Use when you need programmatic composition (per-tenant variants, generated fields) or constructs PSL doesn't yet express (e.g. registering a parameterised extension type — see pgvector's contract).
|
|
47
|
+
- **`prisma.config.ts`.** Wires the contract source, the database connection, the migrations directory, and any installed extensions. Use `defineConfig({...})` from `@internal/postgres/config` (or `@internal/mongo/config`). The four fields the façade accepts: `contract` (path string — `.prisma` or `.ts`), `db` (`{ connection?: string }`), `extensions` (array of control descriptors), `migrations` (`{ dir?: string }`). The output path for `contract.json` is auto-derived from `contract` (e.g. `./src/prisma/contract.prisma` → `./src/prisma/contract.json`).
|
|
48
|
+
- **Emit pipeline.** `prisma contract emit --config <path>?` reads `prisma.config.ts`, calls the provider the façade picked, validates the resulting Contract, then atomically writes `contract.json` + `contract.d.ts` colocated with the source.
|
|
49
|
+
- **Extension namespaces.** Extensions contribute namespaced constructors (`pgvector.Vector(length: 1536)`, `cipherstash.EncryptedString({equality: true})`) and helper presets. Install them by adding the descriptor to **two** places — both fields are named `extensions`, but the two surfaces consume two different descriptor types and shapes:
|
|
50
|
+
- **In the config (façade and core):** `extensions: [pgvector]` — array of *control* descriptors imported from `@internal/extension-<name>/control`.
|
|
51
|
+
- **In the TS builder's `defineContract` (only when authoring `contract.ts`):** `extensions: { pgvector }` — record of *pack* descriptors imported from `@internal/extension-<name>/pack`.
|
|
52
|
+
- **Contract space.** Every package that emits a contract owns its own *contract space* — a `prisma.config.ts` at package root, a contract source, the colocated emitted artefacts, and a `migrations/` directory. **There are two intentional on-disk layouts**, picked by whether the contract space is the consuming application or a contract-space package (an extension, an internal aggregate-root package, etc.):
|
|
53
|
+
- **Application layout** (what you use when building an *app*). `prisma.config.ts` at repo root; `src/prisma/contract.{prisma,ts}`; `src/prisma/contract.{json,d.ts}` colocated; `src/prisma/db.ts` colocated; migrations under `migrations/app/<timestamp>_<slug>/`. The `app/` segment is the consuming application's space-id; extension space-ids land in sibling `migrations/<extension-space-id>/` directories that the extension packages manage. This is what `examples/prisma-8-demo` uses. `prisma orm init` currently scaffolds something different (`prisma/...` at repo root) — that's a defect (TML-2532); the canonical layout is what every command actually expects to see.
|
|
54
|
+
- **Contract-space-package layout** (what you use when *publishing* a contract-space package — extensions, internal monorepo packages). `prisma.config.ts` at package root; `src/contract.{prisma,ts}` directly (no `prisma/` subdir); `src/contract.{json,d.ts}` colocated; `migrations/<timestamp>_<slug>/` directly under `migrations/` (no `<space-id>` segment — the package *is* a single space). Documented in `.cursor/rules/contract-space-package-layout.mdc` and ADR 212.
|
|
55
|
+
|
|
56
|
+
Both layouts let `defineConfig`'s `contract:` path point at the source; the framework derives everything else (emit output, migration root) from there. Pick the layout that matches what you're building and stick with it — don't mix.
|
|
57
|
+
|
|
58
|
+
## Diagnostic codes you route on
|
|
59
|
+
|
|
60
|
+
`prisma contract emit` surfaces structured errors with stable codes; branch on `code` rather than message text.
|
|
61
|
+
|
|
62
|
+
| Code | Meaning | Next move |
|
|
63
|
+
|---|---|---|
|
|
64
|
+
| `PN-CLI-4002` *Contract configuration missing* | `contract` not set in `prisma.config.ts`. | Add `contract: './src/prisma/contract.prisma'` (app layout) or `'./src/contract.prisma'` (contract-space-package layout) — likewise for `.ts` sources — to `defineConfig({...})` from `@internal/postgres/config`. |
|
|
65
|
+
| `PN-CLI-4003` *Contract validation failed* | Source loaded but the Contract IR failed structural validation. | Read `meta.diagnostics` / `meta.issues` for the offending model/field, fix the source, re-emit. |
|
|
66
|
+
| `PN-CLI-4011` *Missing extension packs in config* | The contract uses a namespaced constructor (e.g. `pgvector.Vector(...)`) but `extensions` in the config does not list a matching descriptor. `meta.missingExtensions` names them. | Install the package, import its control descriptor (`import pgvector from '@internal/extension-pgvector/control'`), add it to `extensions: [...]` in `prisma.config.ts`. |
|
|
67
|
+
|
|
68
|
+
## Workflow — Read the contract source of truth
|
|
69
|
+
|
|
70
|
+
The concept: every contract change starts by locating the source file. The config is authoritative — read `prisma.config.ts`, find the `contract:` field (a path string under the façade), and open the file it points at. The same field tells you the installed `extensions: [...]`.
|
|
71
|
+
|
|
72
|
+
```bash
|
|
73
|
+
cat prisma.config.ts
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
If `contract:` ends in `.prisma`, the source is PSL; if it ends in `.ts`, the source is the TS builder. If `prisma.config.ts` is missing, route to `references/quickstart.md`.
|
|
77
|
+
|
|
78
|
+
## Workflow — Edit a model / field / relation (PSL)
|
|
79
|
+
|
|
80
|
+
The concept: PSL models lower to tables (or collections, on Mongo); fields lower to columns; `@relation(...)` declares the FK side. Add the relation only on the owning side — the framework derives the back-reference automatically.
|
|
81
|
+
|
|
82
|
+
```prisma
|
|
83
|
+
model User {
|
|
84
|
+
id Int @id @default(autoincrement())
|
|
85
|
+
email String @unique
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
model Post {
|
|
89
|
+
id Int @id @default(autoincrement())
|
|
90
|
+
title String
|
|
91
|
+
authorId Int
|
|
92
|
+
author User @relation(fields: [authorId], references: [id], onDelete: Cascade)
|
|
93
|
+
|
|
94
|
+
@@unique([title, authorId])
|
|
95
|
+
@@index([authorId])
|
|
96
|
+
}
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
Then run `pnpm prisma contract emit` (or rely on the Vite plugin — see `references/build.md`). Specify cascade behaviour explicitly with `onDelete` / `onUpdate`; the default is `Restrict`.
|
|
100
|
+
|
|
101
|
+
`@@index` also accepts `expression:` (instead of a fields list), `where:` (partial-index predicate), `unique:`, `type:`/`options:` (target-registered access method), and `name:` xor `map:`:
|
|
102
|
+
|
|
103
|
+
```prisma
|
|
104
|
+
@@index(expression: "lower(email)", name: "users_email_lower")
|
|
105
|
+
@@index([authorId], where: "(archived_at IS NULL)", name: "posts_author_active")
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
`name:` declares a wire-named index (physical name `<name>_<8-hex hash>`, renames plan as `ALTER INDEX … RENAME`); `map:` adopts an exact physical name verbatim (for infer-captured objects — combining it with a SQL body warns, because drift detection byte-compares the authored text against Postgres's reprint). An `expression:` requires `name:` or `map:`. The TS builder mirrors this via `constraints.index([cols.x], {...})` / `constraints.index({ expression, ... })` — see `packages/2-sql/2-authoring/contract-ts/README.md`.
|
|
109
|
+
|
|
110
|
+
PSL alias surface for repeated types lives in a top-level `types {}` block:
|
|
111
|
+
|
|
112
|
+
```prisma
|
|
113
|
+
types {
|
|
114
|
+
Email = String
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
model User {
|
|
118
|
+
id Int @id @default(autoincrement())
|
|
119
|
+
email Email @unique
|
|
120
|
+
}
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
Note: scalar lists (e.g. `String[]`) and implicit Prisma-ORM many-to-many (list nav on both sides without a join model) are rejected by the SQL interpreter — use a join model. Composite/embeddable types (`type Address { ... }` with `address Address` on a model) are supported: the interpreter lowers them to `valueObjects` in the domain and stores them as `jsonb` columns. See *Workflow — Value objects* below.
|
|
124
|
+
|
|
125
|
+
## Workflow — Edit a model / field / relation (TS builder)
|
|
126
|
+
|
|
127
|
+
The concept: same model, different authoring surface. The façade re-exports `defineContract`, `field`, `model`, `rel`, plus the `family`/`target` packs as default exports of `@internal/postgres/family` and `@internal/postgres/target`. Use the callback overload (`defineContract({...}, ({ field, model, rel, type }) => ({...}))`) to get the higher-level helpers (`field.text()`, `field.id.uuidv7String()`, `field.temporal.createdAt()`, `type.sql.String(35)`).
|
|
128
|
+
|
|
129
|
+
```typescript
|
|
130
|
+
import sqlFamily from '@internal/postgres/family';
|
|
131
|
+
import { defineContract } from '@internal/postgres/contract-builder';
|
|
132
|
+
import postgresPack from '@internal/postgres/target';
|
|
133
|
+
|
|
134
|
+
export const contract = defineContract(
|
|
135
|
+
{
|
|
136
|
+
family: sqlFamily,
|
|
137
|
+
target: postgresPack,
|
|
138
|
+
},
|
|
139
|
+
({ field, model }) => ({
|
|
140
|
+
models: {
|
|
141
|
+
User: model('User', {
|
|
142
|
+
fields: {
|
|
143
|
+
id: field.id.uuidv7String(),
|
|
144
|
+
email: field.text().unique(),
|
|
145
|
+
createdAt: field.temporal.createdAt(),
|
|
146
|
+
},
|
|
147
|
+
}).sql({ table: 'app_user' }),
|
|
148
|
+
},
|
|
149
|
+
}),
|
|
150
|
+
);
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
Then `pnpm prisma contract emit`. The `field.<scalar>()` helpers are only available inside the callback overload; outside the callback only `field.column(...)`, `field.generated(...)`, `field.namedType(...)` exist.
|
|
154
|
+
|
|
155
|
+
For Mongo, swap every `@internal/postgres/*` import for `@internal/mongo/*`. The Mongo builder also exposes `index` and `valueObject`.
|
|
156
|
+
|
|
157
|
+
## Workflow — Add an extension-typed scalar (pgvector)
|
|
158
|
+
|
|
159
|
+
The concept: an extension contributes a namespace (`pgvector.*`) plus two descriptor flavours — a *control* descriptor for the config façade and a *pack* descriptor for the TS builder. Register the control descriptor in `defineConfig.extensions` (array form). If you're authoring with the TS builder, also register the pack descriptor in `defineContract.extensions` (record form). Then reference the namespaced constructor from the contract.
|
|
160
|
+
|
|
161
|
+
`prisma.config.ts`:
|
|
162
|
+
|
|
163
|
+
```typescript
|
|
164
|
+
import pgvector from '@internal/extension-pgvector/control';
|
|
165
|
+
import { defineConfig } from '@internal/postgres/config';
|
|
166
|
+
|
|
167
|
+
export default defineConfig({
|
|
168
|
+
contract: './src/prisma/contract.prisma',
|
|
169
|
+
extensions: [pgvector],
|
|
170
|
+
});
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
`src/prisma/contract.prisma`:
|
|
174
|
+
|
|
175
|
+
```prisma
|
|
176
|
+
model Document {
|
|
177
|
+
id Int @id @default(autoincrement())
|
|
178
|
+
content String
|
|
179
|
+
embedding pgvector.Vector(length: 1536)
|
|
180
|
+
}
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
Emit. The named-type lowering puts `vector(1536)` on the column and the type map in `contract.d.ts` carries the right TS type.
|
|
184
|
+
|
|
185
|
+
If you reference `pgvector.*` without registering the pack in the config, emit fails with `PN-CLI-4011` and `meta.missingExtensions: ['pgvector']`. The envelope's `fix` text says *"Add the missing extension descriptors to `extensions` in prisma.config.ts"* — that field name matches the façade.
|
|
186
|
+
|
|
187
|
+
For canonical worked examples covering single and multi-extension setups, read `examples/multi-extension-monorepo/app/prisma.config.ts` and `examples/prisma-8-postgis-demo/prisma.config.ts`.
|
|
188
|
+
|
|
189
|
+
## Workflow — Polymorphism (`@@discriminator` / `@@base`)
|
|
190
|
+
|
|
191
|
+
The concept (SQL targets): one base model declares the discriminator field; each variant model declares its base + discriminator value. The variant chooses STI vs MTI by **whether it sets `@@map(...)`**: no `@@map` means the variant inherits the base's table (single-table inheritance); `@@map("variant_table")` means the variant gets its own table joined 1:1 by primary key (multi-table inheritance).
|
|
192
|
+
|
|
193
|
+
```prisma
|
|
194
|
+
model Task {
|
|
195
|
+
id Int @id @default(autoincrement())
|
|
196
|
+
title String
|
|
197
|
+
type String
|
|
198
|
+
|
|
199
|
+
@@discriminator(type)
|
|
200
|
+
@@map("tasks")
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// STI variant — shares the `tasks` table.
|
|
204
|
+
model Bug {
|
|
205
|
+
severity String
|
|
206
|
+
|
|
207
|
+
@@base(Task, "bug")
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// MTI variant — joins to `tasks` via PK; carries its own `features` table.
|
|
211
|
+
model Feature {
|
|
212
|
+
priority Int
|
|
213
|
+
|
|
214
|
+
@@base(Task, "feature")
|
|
215
|
+
@@map("features")
|
|
216
|
+
}
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
Verify the polymorphism syntax against the interpreter tests if in doubt: `packages/2-sql/2-authoring/contract-psl/test/interpreter.polymorphism.test.ts`.
|
|
220
|
+
|
|
221
|
+
Mongo has no schema layer, so polymorphism on Mongo is modelled by an explicit `discriminator` field on the model in the TS builder (see `@internal/mongo/contract-builder`); `@@base` / `@@discriminator` PSL attributes are SQL-only.
|
|
222
|
+
|
|
223
|
+
Querying the variants is a runtime concern — see `references/queries.md`.
|
|
224
|
+
|
|
225
|
+
## Workflow — Value objects (composite types)
|
|
226
|
+
|
|
227
|
+
The concept: `type Foo { ... }` blocks declare value-object shapes. The interpreter lowers them to `valueObjects` in the contract domain and stores them as `jsonb` columns. Nested value-object references are supported.
|
|
228
|
+
|
|
229
|
+
```prisma
|
|
230
|
+
type Address {
|
|
231
|
+
street String
|
|
232
|
+
city String
|
|
233
|
+
zip String?
|
|
234
|
+
country String
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
model User {
|
|
238
|
+
id String @id @default(uuid())
|
|
239
|
+
email String
|
|
240
|
+
address Address?
|
|
241
|
+
}
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
Emitted `contract.json` carries `domain.namespaces.<ns>.valueObjects.Address` with its field descriptors, and the `address` column lands as `codecId: "pg/jsonb@1"` / `nativeType: "jsonb"` in `storage`.
|
|
245
|
+
|
|
246
|
+
Canonical worked example: `examples/prisma-8-demo/src/prisma/contract.prisma`.
|
|
247
|
+
|
|
248
|
+
## Workflow — Enums
|
|
249
|
+
|
|
250
|
+
The concept: PSL `enum` blocks declare a domain enum: a named value-set stored through a declared codec (`@@type("pg/text@1")` → a `text` column) and enforced by a planner-generated CHECK constraint. Each member maps to its database value with `Name = "value"`. Use the enum name as a field type on any model in the same contract.
|
|
251
|
+
|
|
252
|
+
```prisma
|
|
253
|
+
enum user_type {
|
|
254
|
+
@@type("pg/text@1")
|
|
255
|
+
admin = "admin"
|
|
256
|
+
user = "user"
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
model User {
|
|
260
|
+
id String @id @default(uuid())
|
|
261
|
+
kind user_type
|
|
262
|
+
}
|
|
263
|
+
```
|
|
264
|
+
|
|
265
|
+
**Waiving enforcement (`@noCheck`).** A field can decline the generated CHECK constraints for its column: bare `@noCheck` waives every kind the column's shape derives; `@noCheck(membership)` and `@noCheck(elementNotNull)` waive one kind (`membership` is the enum value-set check; `elementNotNull` is the no-NULL-elements check every list column gets). The TS authoring equivalent is `.noCheck(...)` on the field builder. Declared types do not change: the field still types as the enum union, and a list still types with non-null elements — once enforcement is waived, runtime values may diverge from what the types claim. That divergence is the author's accepted risk, and it is scoped to the kinds actually waived: waiving `membership` stops the database rejecting out-of-set values, waiving `elementNotNull` stops it rejecting NULL elements. A list that waives only `membership` still rejects NULL elements. `contract infer` emits `@noCheck(elementNotNull)` automatically for list columns whose source database does not carry the generated check.
|
|
266
|
+
|
|
267
|
+
Canonical worked example: `examples/prisma-8-demo/src/prisma/contract.prisma`.
|
|
268
|
+
|
|
269
|
+
## Workflow — CHECK constraints (`@@check`)
|
|
270
|
+
|
|
271
|
+
The concept: `@@check` declares a hand-written CHECK constraint on a model — a rule you want the database to enforce, on top of whatever generated checks the model's enums and list columns already get (see *Workflow — Enums* above). Without it, a constraint you added by hand had no way into the contract, so it looked like an undeclared extra a destructive migration could drop.
|
|
272
|
+
|
|
273
|
+
```prisma
|
|
274
|
+
model Order {
|
|
275
|
+
id Int @id
|
|
276
|
+
total Decimal
|
|
277
|
+
|
|
278
|
+
// name: is a prefix — the physical constraint becomes order_total_positive_<8-hex hash>.
|
|
279
|
+
@@check(expression: "total > 0", name: "order_total_positive")
|
|
280
|
+
}
|
|
281
|
+
```
|
|
282
|
+
|
|
283
|
+
`expression` is the raw predicate — the text that goes inside `CHECK (...)` — and it is never parsed, so get it right; Prisma Next does not validate SQL syntax. Exactly one of `name:` or `map:` is required, and they're mutually exclusive:
|
|
284
|
+
|
|
285
|
+
- **`name:`** — declaring a new rule. Prisma Next picks the physical constraint name and future plans compare by that name, so Postgres's own reprint of your predicate (which rarely matches what you typed byte-for-byte) never causes false drift.
|
|
286
|
+
- **`map:`** — adopting a rule that already exists. Give the constraint's exact physical name and Prisma Next compares the predicate byte-for-byte against what's live. This is the form `contract infer` writes for you (see *Workflow — Brownfield introspection* below) when it finds a hand-written check in the database. Every `map:` body warns at emit time (`PN_EXACT_NAME_BODY_COMPARISON`) — the warning fires on the text, not on who wrote it, so the check `contract infer` just wrote warns again on your next `contract emit` too. That is expected, not a defect: the comparison is still sound because both sides are Postgres's own reprint. Prefer `name:` for anything you're authoring fresh: your text and Postgres's reprint of it rarely match character-for-character, and a byte comparison reports that as drift even when both mean exactly the same thing. Reserve `map:` for adopting what's already there, where both sides are the database's own reprint and so do match.
|
|
287
|
+
|
|
288
|
+
A model can carry any number of `@@check` attributes. The TS builder mirrors this with `check({ expression, name })` / `check({ expression, map })` on a model's `.sql({ checks: [...] })`, next to `index()`.
|
|
289
|
+
|
|
290
|
+
Check constraints need the target's `checkConstraint` capability. Postgres has it; SQLite does not. `@@check` on a SQLite contract is rejected at authoring time; `check()` on a SQLite contract isn't caught until migration DDL is rendered, but either way you get a refusal, never a silently-dropped constraint.
|
|
291
|
+
|
|
292
|
+
## Workflow — Namespaces (Postgres schemas)
|
|
293
|
+
|
|
294
|
+
The concept: wrap models in a `namespace <name> { ... }` block to place them in a non-default Postgres schema. Models outside any block go into the implicit default namespace.
|
|
295
|
+
|
|
296
|
+
```prisma
|
|
297
|
+
namespace public {
|
|
298
|
+
model Profile {
|
|
299
|
+
id String @id @default(uuid())
|
|
300
|
+
username String
|
|
301
|
+
userId String @unique
|
|
302
|
+
@@map("profile")
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
```
|
|
306
|
+
|
|
307
|
+
Canonical worked example: `examples/supabase/src/contract.prisma`.
|
|
308
|
+
|
|
309
|
+
## Workflow — Cross-contract foreign keys
|
|
310
|
+
|
|
311
|
+
The concept: a relation field can reference a model in another contract space using the `<space>:<namespace>.<Model>` form. The contract also supports top-level named-type aliases in a `types {}` block, backed by the same bare type-position constructors used by fields. The `@db.X(args)` channel is removed: rewrite `@db.X` as `X` and `@db.X(args)` as `X(args)`; remaining uses fail with an actionable diagnostic naming the replacement.
|
|
312
|
+
|
|
313
|
+
```prisma
|
|
314
|
+
types {
|
|
315
|
+
AuthUserId = Uuid
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
namespace public {
|
|
319
|
+
model Profile {
|
|
320
|
+
id String @id @default(uuid())
|
|
321
|
+
username String
|
|
322
|
+
userId AuthUserId @unique
|
|
323
|
+
user supabase:auth.AuthUser @relation(fields: [userId], references: [id], onDelete: Cascade)
|
|
324
|
+
@@map("profile")
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
```
|
|
328
|
+
|
|
329
|
+
`supabase:auth.AuthUser` means: model `AuthUser` in namespace `auth` of contract space `supabase`. The target space is provided by a registered extension pack (here `@internal/extension-supabase/pack`).
|
|
330
|
+
|
|
331
|
+
Canonical worked example: `examples/supabase/src/contract.prisma`.
|
|
332
|
+
|
|
333
|
+
## Workflow — `@@control` (control policy)
|
|
334
|
+
|
|
335
|
+
The concept: `@@control(<policy>)` on a model sets whether Prisma manages that table's DDL in migrations. The argument is a positional lowercase literal — one of `managed`, `tolerated`, `external`, or `observed`.
|
|
336
|
+
|
|
337
|
+
```prisma
|
|
338
|
+
model AuditLog {
|
|
339
|
+
id Int @id
|
|
340
|
+
message String
|
|
341
|
+
|
|
342
|
+
@@control(observed)
|
|
343
|
+
}
|
|
344
|
+
```
|
|
345
|
+
|
|
346
|
+
A contract-level default can be set via `defaultControlPolicy` on `prismaContract(path, { defaultControlPolicy })`. See `references/migrations.md` for how control policies affect DDL planning.
|
|
347
|
+
|
|
348
|
+
## Workflow — `@internal/extension-supabase`
|
|
349
|
+
|
|
350
|
+
The concept: the Supabase extension provides the `supabase` contract space (the `auth` / `storage` schemas as `external` tables, plus the platform roles) and its own role-first runtime factory. It does not expose a `/control` subpath so it cannot be registered via the user-facing `defineConfig({ extensions: [...] })` façade — it is wired via `extensions` in the low-level config. See `examples/supabase` for the full working pattern.
|
|
351
|
+
|
|
352
|
+
`prisma.config.ts` (mirrors the example):
|
|
353
|
+
|
|
354
|
+
```typescript
|
|
355
|
+
import supabasePack from '@internal/extension-supabase/pack';
|
|
356
|
+
import { defineConfig } from '@internal/cli/config-types';
|
|
357
|
+
// ... other low-level imports
|
|
358
|
+
|
|
359
|
+
export default defineConfig({
|
|
360
|
+
// ...
|
|
361
|
+
extensions: [supabasePack],
|
|
362
|
+
});
|
|
363
|
+
```
|
|
364
|
+
|
|
365
|
+
`db.ts` does **not** use the stock `postgres()` factory — a Supabase app builds its client with the `supabase()` factory from `@internal/extension-supabase/runtime` (role-first: `asUser(jwt)` / `asAnon()` / `asServiceRole()`, JWT validation, RLS). That runtime — and RLS policy authoring (`policy_select` / `@@rls`) — is covered by **`references/supabase.md`**; load it for anything past the config wiring.
|
|
366
|
+
|
|
367
|
+
Export subpaths: `@internal/extension-supabase/pack`, `@internal/extension-supabase/runtime`, `@internal/extension-supabase/contract`. Canonical worked example: `examples/supabase`.
|
|
368
|
+
|
|
369
|
+
## Workflow — Brownfield introspection
|
|
370
|
+
|
|
371
|
+
The concept: pull a contract source out of an existing database and continue from there. `prisma contract infer --db <url>` reads the live schema and writes a `contract.prisma` file. It stops there — follow it with `contract emit` and (when the schema matches a pinned hash) `db sign` as separate steps.
|
|
372
|
+
|
|
373
|
+
```bash
|
|
374
|
+
pnpm prisma contract infer --db $DATABASE_URL --output ./src/prisma/contract.prisma
|
|
375
|
+
pnpm prisma contract emit
|
|
376
|
+
```
|
|
377
|
+
|
|
378
|
+
Infer captures indexes at full fidelity — expression, partial (`where:`), unique non-constraint, `type:`/`options:` — adopting each under `map:` with the live name, except that a name shaped like a wire name whose hash recomputes from the content re-detects as wire-named and emits `name:` with the prefix. RLS surfaces too: `@@rls` on RLS-enabled models, and every policy as a `policy_<operation>` block with `@@map("<live name>")`, verbatim predicate reprints, and `permissive = false` for RESTRICTIVE rows (a policy whose role name can't be spelled as a PSL identifier is skipped with a comment note). Replacing an adopted `map:` with the plain wire spelling later converges via a single rename migration.
|
|
379
|
+
|
|
380
|
+
## Common Pitfalls
|
|
381
|
+
|
|
382
|
+
1. **Forgetting to re-emit after an edit.** `contract.json` and `contract.d.ts` go stale; downstream typecheck and `migration plan` see the old shape. Re-emit, or install the Vite plugin (`references/build.md`).
|
|
383
|
+
2. **Editing the emitted artefacts.** `contract.json` and `contract.d.ts` are emitted; edits there round-trip away on the next emit. Edit the source.
|
|
384
|
+
3. **Wrong factory/import path for the TS builder.** `defineContract`, `field`, `model`, `rel` come from `@internal/postgres/contract-builder` (or `@internal/mongo/contract-builder`). Outside the callback overload, the available field constructors are `field.column(...)`, `field.generated(...)`, `field.namedType(...)`.
|
|
385
|
+
4. **Reaching into internal packages from user code.** User-authored files (`prisma.config.ts`, `contract.ts`, `db.ts`, control clients) import only from `@internal/<target>/<subpath>` and `@internal/extension-<name>/<subpath>`. Imports from `@internal/cli/*`, `@internal/family-*`, `@internal/target-*`, `@internal/adapter-*`, `@internal/driver-*`, or `@internal/sql-contract-*` are framework-internal — the façade composes them for you. If a façade subpath you need is missing for your target, see *What Prisma Next doesn't do yet* and route to `references/feedback.md`. The canonical worked examples are `examples/multi-extension-monorepo/app/prisma.config.ts` and `examples/prisma-8-postgis-demo/prisma.config.ts`.
|
|
386
|
+
5. **Confusing the config `extensions` with the TS builder's `extensions`.** Same packs, two surfaces, one field name but two shapes: `defineConfig({ extensions: [pgvector] })` (array of *control* descriptors from `@internal/extension-<name>/control`) versus `defineContract({ extensions: { pgvector } })` (record of *pack* descriptors from `@internal/extension-<name>/pack`).
|
|
387
|
+
6. **Renaming a field and expecting the planner to detect it.** Prisma Next has no in-contract rename hint; the planner sees a destructive drop+add. Hand-edit `migration.ts` after `migration plan` (see `references/migrations.md`), or use the keep-then-drop two-migration pattern.
|
|
388
|
+
|
|
389
|
+
## What Prisma Next doesn't do yet
|
|
390
|
+
|
|
391
|
+
- **In-contract rename hint.** No `@@rename(old: ..., new: ...)` or similar. Use the workarounds in *Common Pitfalls* #6. To request first-class rename, file via `references/feedback.md`.
|
|
392
|
+
- **Model validations.** No declarative `@validates(...)` surface. Validate in application code (arktype). To request declarative validations in the contract, file via `references/feedback.md`.
|
|
393
|
+
- **Lifecycle callbacks** (`beforeSave`, `afterCreate`, etc.). Not supported. Use middleware (`references/runtime.md`) or app code. To request lifecycle callbacks, file via `references/feedback.md`.
|
|
394
|
+
- **Soft delete / `paranoid: true`.** No built-in soft-delete column. Add a nullable `deletedAt DateTime?` and filter explicitly in queries (or in middleware). To request built-in soft delete, file via `references/feedback.md`.
|
|
395
|
+
- **Scopes / default filters.** No ActiveRecord-style scopes. Compose query helpers yourself. To request scopes, file via `references/feedback.md`.
|
|
396
|
+
- **Implicit Prisma-ORM many-to-many.** List navigation on both sides without an explicit join model is rejected. Author the join model explicitly. To request implicit M2M, file via `references/feedback.md`.
|
|
397
|
+
|
|
398
|
+
## Reference
|
|
399
|
+
|
|
400
|
+
- Run `pnpm prisma contract --help` for the live command surface.
|
|
401
|
+
- PSL feature surface and what the interpreter accepts: `packages/2-sql/2-authoring/contract-psl/README.md`.
|
|
402
|
+
- TS builder surface and the callback-helper vocabulary: `packages/2-sql/2-authoring/contract-ts/README.md`.
|
|
403
|
+
- Layouts (where `contract.prisma`, `contract.json`, `contract.d.ts`, and `migrations/` live):
|
|
404
|
+
- **App layout** (`src/prisma/...` + `migrations/app/...`) — what `examples/prisma-8-demo` demonstrates; the canonical shape consuming applications use.
|
|
405
|
+
- **Contract-space-package layout** (`src/contract.{prisma,ts}` directly, `migrations/<timestamp>_<slug>/` without a space-id segment) — for extensions and aggregate-root packages, documented in `.cursor/rules/contract-space-package-layout.mdc` and ADR 212.
|
|
406
|
+
|
|
407
|
+
## Checklist
|
|
408
|
+
|
|
409
|
+
- [ ] Read `prisma.config.ts` and identified the contract source (path string ending in `.prisma` or `.ts`) and the installed `extensions: [...]`.
|
|
410
|
+
- [ ] All user-authored imports resolve to `@internal/<target>/<subpath>` (e.g. `@internal/postgres/config`) or `@internal/extension-<name>/<subpath>`. No imports from `@internal/cli/*`, `@internal/family-*`, `@internal/target-*`, `@internal/adapter-*`, `@internal/driver-*`, or `@internal/sql-contract-*` in user files.
|
|
411
|
+
- [ ] Edited the contract source (`contract.prisma` or `contract.ts`), not an emitted artefact.
|
|
412
|
+
- [ ] For new extension namespaces: added the package, imported its control descriptor (`@internal/extension-<name>/control`), added it to `extensions: [...]` in `defineConfig({...})` (and the matching pack descriptor to `defineContract({extensions: {...}})` if using the TS builder).
|
|
413
|
+
- [ ] For renames: hand-edited `migration.ts` after `migration plan` (or used the keep-then-drop two-migration pattern) — Prisma Next has no rename hint today.
|
|
414
|
+
- [ ] Ran `pnpm prisma contract emit` after the edit (or let the Vite plugin re-emit on save).
|
|
415
|
+
- [ ] Confirmed `contract.json` and `contract.d.ts` updated next to the source.
|
|
416
|
+
- [ ] Did **not** hand-edit `contract.json` / `contract.d.ts`.
|
|
417
|
+
- [ ] Did **not** confabulate a missing feature (validations, callbacks, soft delete, scopes, in-contract rename hint) — referred the user to *What Prisma Next doesn't do yet* + `references/feedback.md`.
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
|
|
2
|
+
# Prisma Next — Debug
|
|
3
|
+
|
|
4
|
+
> **Edit your data contract. Prisma handles the rest.**
|
|
5
|
+
|
|
6
|
+
When a Prisma Next call fails, the framework returns a **structured envelope**. The agent's job is to read the envelope, route on the `code`, and chain to the right authoring skill for the actual fix. This skill teaches the envelope shapes and the routing — it does not duplicate sibling-skill workflows.
|
|
7
|
+
|
|
8
|
+
## When to Use
|
|
9
|
+
|
|
10
|
+
- User pastes an error envelope (CLI failure, runtime exception, `--json` output).
|
|
11
|
+
- User says *"my query won't typecheck"*, *"my migration won't apply"*, *"my emit failed"*, *"the runtime crashed"*.
|
|
12
|
+
- User mentions a stable code (`PN-CLI-*`, `PN-MIG-*`, `PN-RUN-*`, `PN-SCHEMA-*`, `MIGRATION.*`, `CONTRACT.*`, `LINT.*`, `BUDGET.*`, `PLAN.*`, `RUNTIME.*`).
|
|
13
|
+
- User mentions: *Studio, EXPLAIN, query log, prepared statements, drift, hash mismatch, capability, planner*.
|
|
14
|
+
|
|
15
|
+
## When Not to Use
|
|
16
|
+
|
|
17
|
+
- User wants to author a query / model / migration → the matching authoring skill.
|
|
18
|
+
- User wants to *prevent* errors (lints, budgets, type-level guards) → `references/runtime.md`.
|
|
19
|
+
- User wants the framework changed because the surface itself is the problem (no envelope to route on, capability genuinely missing) → `references/feedback.md`.
|
|
20
|
+
|
|
21
|
+
## Key Concepts
|
|
22
|
+
|
|
23
|
+
### Two envelope shapes
|
|
24
|
+
|
|
25
|
+
Prisma Next emits **two distinct envelopes** depending on which seam threw. Read which one you have *before* routing.
|
|
26
|
+
|
|
27
|
+
**1. CLI envelope** — produced by `prisma ...` commands (emit, db init/update/verify/sign/schema, migration plan/apply/show/status, init). Shape (see `CliErrorEnvelope` in `packages/1-framework/1-core/errors/src/control.ts`):
|
|
28
|
+
|
|
29
|
+
```json
|
|
30
|
+
{
|
|
31
|
+
"ok": false,
|
|
32
|
+
"code": "PN-MIG-2001",
|
|
33
|
+
"domain": "MIG",
|
|
34
|
+
"severity": "error",
|
|
35
|
+
"summary": "Unfilled migration placeholder",
|
|
36
|
+
"why": "...",
|
|
37
|
+
"fix": "...",
|
|
38
|
+
"where": { "path": "...", "line": 42 },
|
|
39
|
+
"meta": { "slot": "..." },
|
|
40
|
+
"docsUrl": "https://prisma-next.dev/..."
|
|
41
|
+
}
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
The full code is `PN-<domain>-<NNNN>`. Domains in use: `CLI`, `MIG`, `RUN`, `CON`, `SCHEMA`. Severity is `error | warn | info` — `migration status` exits 0 when its diagnostics are `warn`, so route on **severity + code together**, not on exit code alone.
|
|
45
|
+
|
|
46
|
+
**2. Runtime envelope** — thrown by the in-process runtime when executing a query (see `RuntimeErrorEnvelope` in `packages/1-framework/1-core/framework-components/src/execution/runtime-error.ts`):
|
|
47
|
+
|
|
48
|
+
```ts
|
|
49
|
+
{ name: 'RuntimeError', code: 'BUDGET.TIME_EXCEEDED', category: 'BUDGET', severity: 'error', message: '...', details: { ... } }
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
`category` is one of `PLAN | CONTRACT | LINT | BUDGET | RUNTIME` (the prefix of `code`). `details` holds the structured context (`details` is the runtime envelope's equivalent of the CLI envelope's `meta`).
|
|
53
|
+
|
|
54
|
+
**3. SQL driver errors** — surface as `SqlQueryError` / `SqlConnectionError` (see `packages/2-sql/1-core/errors/`). Fields on `SqlQueryError`: `kind: 'sql_query'`, `sqlState` (Postgres SQLSTATE, e.g. `'23505'`), `constraint`, `table`, `column`, `detail`, `cause`. These are *not* `PN-*` codes — route on `sqlState` and the constraint metadata. SQL driver errors are typically wrapped by middleware before reaching the user, but raw-SQL paths can surface them directly.
|
|
55
|
+
|
|
56
|
+
### Wrapped errors and `meta.code`
|
|
57
|
+
|
|
58
|
+
Some commands re-wrap a downstream error into a `PN-RUN-3000` (`errorRuntime`) envelope and stash the original code on `meta.code`. The most important case: `db migrate` wraps `MigrationToolsError` (which has codes like `MIGRATION.HASH_MISMATCH`, `MIGRATION.STALE_CONTRACT_BOOKENDS`, `MIGRATION.AMBIGUOUS_TARGET`) via `mapMigrationToolsError`. The envelope you see is `code: 'PN-RUN-3000'` with `meta.code: 'MIGRATION.HASH_MISMATCH'`. **Always check `meta.code` when `code` is `PN-RUN-3000`** — that's where the routing-quality information lives.
|
|
59
|
+
|
|
60
|
+
### How to ask for the full envelope
|
|
61
|
+
|
|
62
|
+
If the user only pasted the human summary, ask for `--json` output (machine envelope) or re-run with `-v` (CLI prints the full structured fields). `--json` and `-v` are global flags on every CLI command.
|
|
63
|
+
|
|
64
|
+
## Routing — script teardown and closed client
|
|
65
|
+
|
|
66
|
+
These symptoms are not `PN-*` envelopes — route on the message text and chain to `references/runtime.md` § *Running as a script (teardown)*.
|
|
67
|
+
|
|
68
|
+
| Symptom | Next move |
|
|
69
|
+
|---|---|
|
|
70
|
+
| `TypeError: db.end is not a function` | The runtime client does not expose `db.end()` — that's the `node-postgres` pool API (`pool.end()`). The right call is `await db.close()`. See `references/runtime.md` § *Running as a script (teardown)*. |
|
|
71
|
+
| Script hangs after queries print / process won't exit | On Postgres the façade-owned `pg.Pool` keeps the event loop alive. Call `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` inside a request handler — block-scoped, would close per-request). See `references/runtime.md` § *Running as a script (teardown)*. |
|
|
72
|
+
| `Error('Postgres client is closed')` / `Error('SQLite client is closed')` / `Error('Mongo client is closed')` | The client was closed via `db.close()` (terminal state). Remove the early `close()`, reorder so `close()` runs last after all queries, or construct a new `db` if reconnection is intended. See `references/runtime.md` § *Running as a script (teardown)*. |
|
|
73
|
+
|
|
74
|
+
## Routing — symptom and code → next move
|
|
75
|
+
|
|
76
|
+
The single source of truth: read the envelope, find the row by `code` (or `meta.code` for wrapped errors), follow the next move.
|
|
77
|
+
|
|
78
|
+
| Code | Where it surfaces | Next move |
|
|
79
|
+
|---|---|---|
|
|
80
|
+
| `PN-CLI-4001` *Config file not found* | Most `prisma` commands | Run `prisma orm init`, or pass `--config <path>`. |
|
|
81
|
+
| `PN-CLI-4002` *Contract configuration missing* | `contract emit`, `db *` | Add `contract: { ... }` to `prisma.config.ts`. See `references/contract.md`. |
|
|
82
|
+
| `PN-CLI-4003` *Contract validation failed* | `contract emit`, `db *` | Re-run `pnpm prisma-cli contract emit` after fixing the contract source named in `where.path`. See `references/contract.md`. |
|
|
83
|
+
| `PN-CLI-4005` *Database connection is required* | `db *`, `db migrate`, `migration status` | Pass `--db <url>` or set `db.connection` in `prisma.config.ts`. |
|
|
84
|
+
| `PN-CLI-4011` *Missing extension packs in config* | `contract emit` (e.g. contract uses `pgvector.Vector(...)` but config does not list the pgvector pack) | Add the descriptors named in `meta.missingExtensions` to `extensions` in `prisma.config.ts`. See `references/contract.md`. |
|
|
85
|
+
| `PN-CLI-4020` *Migration planning failed* | `db init`, `db update` | Inspect `meta.conflicts`. Recovery is per-conflict — chain to `references/migrations.md`. |
|
|
86
|
+
| `PN-CLI-5002/5003/5004/…` *Init errors* | `prisma orm init` | Re-run with the missing/invalid flags listed in `meta.missingFlags` or `meta.allowed`. |
|
|
87
|
+
| `PN-MIG-2001` *Unfilled migration placeholder* | `node migrations/app/<dir>/migration.ts` (self-emit) or `db migrate` | Edit `migration.ts`, replace the named `placeholder("<slot>")` with a real query closure, self-emit. See `references/migrations.md`. |
|
|
88
|
+
| `PN-MIG-2002` *migration.ts not found* | Reading a migration package | Restore from version control or scaffold a fresh package with `migration plan`. |
|
|
89
|
+
| `PN-MIG-2003` *Invalid default export* | Loading `migration.ts` | Use `export default class extends Migration { ... }` (or factory `() => ({ ... })`). See `references/migrations.md`. |
|
|
90
|
+
| `PN-MIG-2005` *dataTransform contract mismatch* | Building a data-transform query plan | Pass the same `endContract` reference to both `dataTransform(endContract, …)` and the query-builder context. |
|
|
91
|
+
| `PN-RUN-3001` *Database not signed* | `db verify`, runtime startup | DB has no marker yet. Run `prisma db init --db <url>` (baseline empty DB) or `db update --db <url>` (apply contract directly). |
|
|
92
|
+
| `PN-RUN-3002` *Hash mismatch* | `db verify`, runtime startup | Marker disagrees with contract hash. Either migrate forward (`db migrate` / `db update`), or — if the DB is correct after a manual fix-up — `db sign`. See `references/migrations.md`. |
|
|
93
|
+
| `PN-RUN-3003` *Target mismatch* | Runtime startup | Contract target ≠ config target; align them (see `meta.expected` / `meta.actual`). |
|
|
94
|
+
| `PN-RUN-3004` *Schema verification failed* | `db verify` (full mode) | Inspect `meta.verificationResult`. Run `db update` to reconcile, or adjust contract. |
|
|
95
|
+
| `PN-RUN-3010` *Schema verification failed (CLI surface)* | `db verify` schema-only | Same as 3004. |
|
|
96
|
+
| `PN-RUN-3020` *Migration runner failed* | `db migrate`, `db update`, `db init` | Inspect `meta` for the conflict; reconcile schema drift, then re-run. Previously applied migrations are preserved. |
|
|
97
|
+
| `PN-RUN-3030` *Destructive changes require confirmation* | `db update` (interactive prompt fires; non-interactive returns this code) | Re-run with `-y` (or `--yes`) to apply, or `--dry-run` to preview. **Only `db update` has this flow** — `db migrate` does not gate destructive ops on a flag. |
|
|
98
|
+
| `PN-RUN-3000` *(wrapper)* | `db migrate`, others wrapping `MigrationToolsError` | Read `meta.code`. Cases: `MIGRATION.HASH_MISMATCH` (re-emit: `node migrations/app/<dir>/migration.ts`); `MIGRATION.AMBIGUOUS_TARGET` (concurrent migrations — `references/migration-review.md`); `MIGRATION.STALE_CONTRACT_BOOKENDS` (re-run `migration plan`); `MIGRATION.NO_INVARIANT_PATH` / `MIGRATION.UNKNOWN_INVARIANT` (`references/migration-review.md`); `MIGRATION.PATH_UNREACHABLE` / `MIGRATION.MARKER_MISMATCH` (run `db migrate --show --db $URL` to inspect the path, then `migration plan --from <from> --to <target>` or `migration list` to audit the graph — see `references/migration-review.md`). |
|
|
99
|
+
| `PN-SCHEMA-0001` | `db verify` schema check | Live schema does not satisfy contract. `meta.verificationResult` has the diff. Run `db update` or adjust the contract. |
|
|
100
|
+
| `MIGRATION.UP_TO_DATE` / `.DATABASE_BEHIND` | `migration status` `info` diagnostics | Informational; exit 0. See `references/migration-review.md`. |
|
|
101
|
+
| `MIGRATION.MISSING_INVARIANTS` | `migration status` `info` diagnostic | The live marker reached the destination hash structurally but doesn't carry all invariants the target ref requires. Run `db migrate --to <name> --db $URL` to take a path that covers the missing invariants. See `references/migration-review.md`. |
|
|
102
|
+
| `MIGRATION.NO_MARKER` / `.MARKER_NOT_IN_HISTORY` / `.DIVERGED` / `CONTRACT.AHEAD` / `CONTRACT.UNREADABLE` | `migration status` `warn` diagnostics (exit 0; CI gates parse `--json`) | Read `severity` *and* `code`. `references/migration-review.md` covers the diamond/diverged/marker-out-of-history flows. |
|
|
103
|
+
| `BUDGET.ROWS_EXCEEDED` / `BUDGET.TIME_EXCEEDED` | Runtime, when the `budgets` middleware is active | Tune `budgets({ maxRows, maxLatencyMs, ... })` or rewrite the query. See `references/runtime.md`. |
|
|
104
|
+
| `LINT.SELECT_STAR` / `LINT.NO_LIMIT` / `LINT.DELETE_WITHOUT_WHERE` / `LINT.UPDATE_WITHOUT_WHERE` / `LINT.READ_ONLY_MUTATION` | Runtime, when the `lints` middleware is active | Fix the query (add a `WHERE` / `LIMIT` / explicit columns), or relax the lint config. See `references/runtime.md`. |
|
|
105
|
+
| `PLAN.HASH_MISMATCH` | Runtime, executing a precompiled plan | The contract the plan was built against does not match the runtime contract. Re-emit, rebuild, redeploy. |
|
|
106
|
+
| `CONTRACT.MARKER_MISSING` / `CONTRACT.MARKER_MISMATCH` | Runtime, marker check before executing | Same family as `PN-RUN-3001` / `PN-RUN-3002` but raised in-process by the runtime rather than a CLI. Recovery is the same. |
|
|
107
|
+
| `RUNTIME.ABORTED` (`details.phase` = `encode\|decode\|stream\|beforeExecute\|afterExecute\|onRow`) | Runtime, when an `AbortSignal` fires mid-execute | Cancellation, not a bug; surface to the caller. |
|
|
108
|
+
| `SqlQueryError` (no `PN-` code) | Raw-SQL paths surfacing a driver error | Inspect `sqlState` + `constraint` + `table` + `column`. Postgres `23505` = unique violation, `23503` = foreign-key violation, etc. Fix the data or the schema. |
|
|
109
|
+
| TypeScript error mentioning a capability (e.g. `returning()` not on the type, `include` of a many-relation off a many-load) | Authoring-time, before any envelope fires | Capability gates are declared in the **contract** (`capabilities` block, namespaced by target/family), not in `prisma.config.ts`. Route to `references/contract.md` for capability declaration and to `references/queries.md` for which method gates on which capability. Re-emit (`pnpm prisma-cli contract emit`) after enabling. |
|
|
110
|
+
| TypeScript error mentioning a missing field/method on `db.orm.<Model>` or a stale `Contract` shape | Authoring-time | Re-emit (`pnpm prisma-cli contract emit`); confirm `db.ts` instantiates with `postgres<Contract, TypeMaps>(...)` (the type parameters propagate the contract types). See `references/runtime.md` and `references/contract.md`. |
|
|
111
|
+
|
|
112
|
+
If the envelope's `code` is not in this table, follow the envelope's `fix` field literally — it's the framework's first-party next move. If `fix` is empty or unhelpful, escalate via `references/feedback.md`.
|
|
113
|
+
|
|
114
|
+
## Common Pitfalls
|
|
115
|
+
|
|
116
|
+
1. **Reading only `summary`, not the rest of the envelope.** `code`, `severity`, `why`, `fix`, `meta`/`details`, and (for CLI errors) `where` are all load-bearing. The agent routes on `code`; the user sees `summary`.
|
|
117
|
+
2. **Ignoring `severity`.** `migration status` emits warn-level diagnostics and **exits 0**. An agent that only checks exit code misses every concurrent-migration warning.
|
|
118
|
+
3. **Skipping `meta.code` on `PN-RUN-3000`.** That envelope is a wrapper — the real code lives on `meta.code`.
|
|
119
|
+
4. **Treating drift as something to silence with `db sign`.** `db sign` writes the marker from the current contract hash, but it requires schema verification to pass first. Run `db verify` before reaching for `db sign`.
|
|
120
|
+
5. **Re-running `db migrate` after a partial failure without inspecting state.** `db schema --db <url>` shows the live shape; `migration status --db <url> --json` shows where the marker actually is.
|
|
121
|
+
|
|
122
|
+
## What Prisma Next doesn't do yet
|
|
123
|
+
|
|
124
|
+
- **Studio / GUI database browser.** No first-party Studio. Workaround: `prisma db schema` for a CLI tree of the live schema, or use a third-party tool (TablePlus, DataGrip, `psql`) against your `DATABASE_URL`. If you need a built-in GUI, file a feature request via `references/feedback.md`.
|
|
125
|
+
- **First-class query logger middleware.** No built-in "log every query" middleware ships with the framework. Workaround: write a small custom middleware that wraps each operation (see `references/runtime.md` for middleware composition). If you need a built-in query log, file a feature request via `references/feedback.md`.
|
|
126
|
+
- **`EXPLAIN` integration.** No first-class `.explain()` on plans. Workaround: write the EXPLAIN as a raw query (``db.raw.sql`EXPLAIN ANALYZE ...` ``; see `references/queries.md`). If you need first-class EXPLAIN, file a feature request via `references/feedback.md`.
|
|
127
|
+
- **Prepared-statement caching as a user-facing surface.** Adapters prepare under the hood for parameterized queries, but you cannot pre-prepare and re-execute a statement by name. Workaround: use TypedSQL (see `references/queries.md`). If you need prepared statements as a first-class API, file a feature request via `references/feedback.md`.
|
|
128
|
+
|
|
129
|
+
## Asking for help when the envelope doesn't route
|
|
130
|
+
|
|
131
|
+
1. Re-run with `-v` (or `--json` for machine output) to get the full envelope.
|
|
132
|
+
2. If the envelope is genuinely uninformative — empty `fix`, missing `meta`, generic `summary` — that's a framework affordance gap; route to `references/feedback.md` with the envelope, the contract source (sanitised), and the reproduction steps.
|
|
133
|
+
|
|
134
|
+
## Checklist
|
|
135
|
+
|
|
136
|
+
- [ ] Identified which envelope shape (`CliErrorEnvelope`, `RuntimeErrorEnvelope`, `SqlQueryError`).
|
|
137
|
+
- [ ] Read every field — `code`, `severity`, `why`, `fix`, `meta` (or `details`), `where` if present.
|
|
138
|
+
- [ ] If `code` is `PN-RUN-3000`, also read `meta.code`.
|
|
139
|
+
- [ ] Routed on `code` to the next move (and chained to the matching authoring skill where the table says so).
|
|
140
|
+
- [ ] Re-verified with the relevant CLI command (`db verify`, `migration status --json`, `contract emit`, `db migrate`).
|
|
141
|
+
- [ ] Did not confabulate a Studio / EXPLAIN / query-log API — used the documented workaround and routed unmet capability gaps to `references/feedback.md`.
|