diff --git a/packages/9-public/@prisma/orm-family-sql/README.md b/packages/9-public/@prisma/orm-family-sql/README.md index 925ebab96906..596af3d3a385 100644 --- a/packages/9-public/@prisma/orm-family-sql/README.md +++ b/packages/9-public/@prisma/orm-family-sql/README.md @@ -17,6 +17,27 @@ An application on a SQL database lists this package beside its database package | `/runtime` | SQL runtime | | `/orm-client` | the fluent, type-safe ORM client over SQL model collections | | `/family/*` | the family pack: control, migration, diff, IR, verification | +| `/errors` | the SQL driver error classes: `SqlQueryError` (`kind: 'sql_query'` with `sqlState`, `constraint`, `table`, `column`, `detail`), `SqlConnectionError` (`kind: 'sql_connection'`, `transient`), and `isUniqueConstraintViolation(error)` | + +## SQL driver errors + +A SQL statement that fails surfaces as a `SqlQueryError`, or as a `SqlConnectionError` for a connection-related failure, which is not always a lost connection (SQLite reports a busy or locked database, `SQLITE_BUSY` and `SQLITE_LOCKED`, this way with the connection still open), and a connection that fails to open surfaces as the class the error's own code gives it, the same as anywhere else — an invalid password (`28P01`) is a `SqlQueryError`, not a `SqlConnectionError` — so route on `kind` and the metadata fields, not on which call failed; both carry no dotted code. The drivers classify from the underlying error's own code, so an error that carries none (a plain pg `Error`, for example) can surface unchanged — it then matches neither `kind` nor `instanceof` checks; treat an unclassified `Error` on a SQL path as unknown and inspect the error itself. The exception is a failure the Postgres driver knows is a connection failure — a `connect()` that rejects, or an error raised on a client that has already lost its connection — whose error no code classifies: it becomes a `SqlConnectionError`, keeping the original error as its `cause`. The classes are the same modules every SQL facade's driver throws, so `instanceof` and `SqlQueryError.is(...)` hold across the family. `isUniqueConstraintViolation(error)` classifies a unique or primary-key violation from the driver-normalized `sqlState` (`'23505'`), without knowing any target's own error shape: + +```ts +import { SqlQueryError, isUniqueConstraintViolation } from '@prisma/orm-family-sql/errors'; + +try { + await db.execute(plan); +} catch (error) { + if (isUniqueConstraintViolation(error)) { + // sqlState === '23505'; error.constraint, error.table name the violated key. + } else if (error instanceof SqlQueryError) { + // Other query failure: route on error.sqlState and error.constraint. + } +} +``` + +An application that imports from `/errors` directly declares `@prisma/orm-family-sql` as a dependency of its own, pinned to the version the facade uses, so the application and the driver share one copy of the module. ## Responsibilities diff --git a/packages/9-public/@prisma/orm-postgres/README.md b/packages/9-public/@prisma/orm-postgres/README.md index da1c4acecdfa..0c6d1511efd8 100644 --- a/packages/9-public/@prisma/orm-postgres/README.md +++ b/packages/9-public/@prisma/orm-postgres/README.md @@ -60,6 +60,41 @@ The full list is the `exports` field of this package's `package.json`. These forward; they do not copy. `@prisma/orm-postgres/contract/types` and `@prisma/orm-framework/contract/types` are the same module, so a value made through either is recognised by both, and `instanceof` checks hold across the boundary. +## Lower-level entry points + +Beneath the client factories the facade also publishes the layers they are built from, as stable subpaths code names directly when it needs the layer beneath the client: an expression the raw-SQL lane cannot infer a codec for, a caller-owned pool, a decomposed install, a script that audits migrations. + +| Entrypoint | Surface | +| --- | --- | +| `/relational-core/expression` | the expression helpers: `param(value, { codecId })` wraps a literal value whose codec the raw-SQL lane cannot infer (the fix `RUNTIME.RAW_SQL_UNSUPPORTED_INTERPOLATION` names; a query fragment interpolates directly and must not be wrapped), `toExpr(value, codec?)` lifts an expression or a raw value into an AST expression — a raw value requires `codec` (without one it throws `RUNTIME.PARAM_REF_CODEC_REQUIRED`), an expression does not, `buildOperation(spec)` builds a custom operation's AST | +| `/relational-core/ast` | the relational AST classes a plan's query is built from (`ColumnRef`, `ParamRef`, `LiteralExpr`, `BinaryExpr`, `TableSource`, …) | +| `/relational-core/types` | the plan and scope types: `SqlOrmPlan`, the shape `db.query(plan)` and `db.execute(plan)` accept | +| `/driver/runtime` | `createPgPool(config, sessionSettings)` and `createPgClient(config, sessionSettings)` — a pool or client whose every session starts with the session settings the target declares | +| `/target/runtime` | the Postgres runtime target descriptor (the default export), with `sessionSettings` and the codec, query-operation and collection-method contributions a decomposed install composes | +| `/migration-tools/io` | the migration package reader: `readMigrationPackage(dir, options)` reads one package, `readMigrationsDir(root, options)` reads the graph directory, returns per-package load problems in `problems`, skips directories without `migration.json` silently, returns empty `packages` and `problems` when the root does not exist, and throws for any other filesystem error while listing the root or stat-ing an entry | + +```ts +import { param } from '@prisma/orm-postgres/relational-core/expression'; +import { createPgPool } from '@prisma/orm-postgres/driver/runtime'; +import postgresTarget from '@prisma/orm-postgres/target/runtime'; + +// A value the raw-SQL lane would refuse (anything not number, bigint, string, +// boolean or Uint8Array) is wrapped with an explicit codec: +const plan = db.raw + .sql`SELECT id FROM event WHERE at > ${param(myTimestamp, { codecId: 'pg/timestamptz-temporal@1' })}` + .returnsRow({ id: 'pg/int8@1' }) + .build(); + +// A caller-owned pool whose sessions start with the same settings the +// facade-owned pool gets: +const pool = createPgPool( + { connectionString: process.env['DATABASE_URL'] }, + postgresTarget.sessionSettings ?? {}, +); +``` + +A decomposed install (see *Decomposing* below) composes the runtime stack from the descriptors these entry points carry: the target, the driver, and the adapter of its choice passed to `createSqlExecutionStack`. Under the facade the stack builder is `@prisma/orm-postgres/family-runtime`; a decomposed install composes the same modules through the platform packages (`@prisma/orm-target-postgres/target/runtime`, `@prisma/orm-target-postgres/driver/runtime`, `@prisma/orm-family-sql/runtime`), which are the exact-pinned dependencies the facade would have installed. + ## The CLI This package ships no bin. The ORM commands run inside the unified `prisma` CLI, which mounts the command family published at `@prisma/orm-toolchain/cli`. diff --git a/skills/prisma-8/SKILL.md b/skills/prisma-8/SKILL.md index c946f65bacfe..762199229dc5 100644 --- a/skills/prisma-8/SKILL.md +++ b/skills/prisma-8/SKILL.md @@ -63,11 +63,11 @@ Open the reference whose triggers match the task. If more than one matches, open | --- | --- | --- | | Adopt / set up / first steps | [`references/quickstart.md`](references/quickstart.md) | new project, existing database, "what can I do with Prisma 8", "where do I start", "just ran createprisma", `npx create-prisma`, first steps, first query, `prisma orm init` greenfield setup, `contract infer` + `db sign` brownfield adoption, connect-write-read first arc, day-to-day commands (`contract emit`, `db init`, `db update`, `migration plan`, `db migrate`, `db schema`, `db verify`), flags `--target` / `--authoring` / `--schema-path` / `--probe-db` / `--output` | | Edit the data contract | [`references/contract.md`](references/contract.md) | schema, models, fields, attributes, relations, indexes, enums, value objects (composite types), type aliases, namespaces (Postgres schemas), cross-contract foreign keys (cross-space FK), polymorphic types (`@@discriminator` / `@@base`), extension namespaces (`pgvector.Vector(...)`, `postgis.Geometry(...)`), `prisma.config.ts` / `definePrismaConfig` / `ormConfig`, `prisma contract emit`, PSL, `contract.prisma`, `contract.ts`, `contract.json`, `contract.d.ts`, `@prisma/orm-postgres/config`, `@prisma/orm-postgres/contract-builder`, `@prisma/orm-mongo/config`, `extensions:`, pgvector, postgis, Temporal / `temporal-polyfill` / `RUNTIME.TEMPORAL_UNAVAILABLE`, `@@control`, control policy (managed / tolerated / external / observed), soft delete, validations, callbacks | -| Author migrations | [`references/migrations.md`](references/migrations.md) | "no migration path", "migration path not found", "no authored path", `MIGRATION.SIGNATURE_NOT_IN_GRAPH`, `MIGRATION.CHANGE_POLICY_FORBIDS`, `MIGRATION.DATA_PROTECTION_FORBIDS`, `MIGRATION.POLICY_MISMATCH`, change policy, data protection policy, `migration ref policy show` / `set` / `delete`, declaring a ref's policies, `--permit-policy-change`, "reset the database", "drop the database", `db update` vs `migration plan`, `db migrate`, `migration new`, `migration show`, `db update --dry-run`, `db verify`, `db sign`, data migration, `dataTransform`, placeholder sentinels in framework-rendered `migration.ts`, `MIGRATION.HASH_MISMATCH`, `MIGRATION.UNFILLED_PLACEHOLDER`, data-loss questions (`--delete`, `--rename`, `--allow`, `CLI.CONSENT_REQUIRED`), schema drift | +| Author migrations | [`references/migrations.md`](references/migrations.md) | "no migration path", "migration path not found", "no authored path", `MIGRATION.SIGNATURE_NOT_IN_GRAPH`, `MIGRATION.CHANGE_POLICY_FORBIDS`, `MIGRATION.DATA_PROTECTION_FORBIDS`, `MIGRATION.POLICY_MISMATCH`, change policy, data protection policy, `migration ref policy show` / `set` / `delete`, declaring a ref's policies, `--permit-policy-change`, "reset the database", "drop the database", `db update` vs `migration plan`, `db migrate`, `migration new`, `migration show`, `db update --dry-run`, `db verify`, `db sign`, data migration, `dataTransform`, placeholder sentinels in framework-rendered `migration.ts`, `MIGRATION.HASH_MISMATCH`, `MIGRATION.UNFILLED_PLACEHOLDER`, data-loss questions (`--delete`, `--rename`, `--allow`, `CLI.CONSENT_REQUIRED`), schema drift, reading migration packages in a script (`readMigrationPackage` / `readMigrationsDir`, `migration-tools/io`) | | Migration graph, refs, plan origin | [`references/migration-model.md`](references/migration-model.md) | migration graph, refs, `migration ref set` / `list` / `delete`, the `db` ref, `--advance-ref`, `--no-advance-ref`, `migration plan --from`, `from: (baseline)` in plan output, greenfield / from-scratch plan, baseline, first migration before deploy (Composer / CD-managed databases), chaining migrations, retrofitting migrations onto an existing database, `MIGRATION.HASH_NOT_IN_GRAPH`, `MIGRATION.PATH_UNREACHABLE` at plan/chain time | | Review migrations on deploy | [`references/migration-review.md`](references/migration-review.md) | "what migrations are going to run", "what runs on deploy / merge", merge conflict, diamond convergence, concurrent migrations, migration status, ref management for CI, staging / production environment refs, `MIGRATION.SIGNATURE_NOT_IN_GRAPH`, `MIGRATION.MISSING_INVARIANTS`, `db migrate --show` | | Write queries | [`references/queries.md`](references/queries.md) | query, where, select, project, orderBy, limit, offset, take, skip, include, lookup, first, all, count, aggregate, groupBy, create, update, delete, upsert, returning, transaction, `db.orm`, `db.sql`, `runtime.query(plan)` vs `runtime.execute(plan)`, `db.prepare` / prepared statements, streaming / `for await`, many-to-many `include` and nested `connect`, `and` / `or` / `not` from `@prisma/orm-postgres/orm-client`, `db.query.from(...)` (Mongo pipeline), namespace-aware accessors, `.all()` Thenable, single-use iterators (`RUNTIME.ITERATOR_CONSUMED`), target-declared aggregate types (`count`, integer `sum`, and integer `avg` are `number`; `count` and integer `sum` throw outside ±(2^53 − 1) rather than round, while `avg` is a fraction already and carries no guard; `countBigInt` / `sumBigInt` / `avgDecimal` are the lossless forms, `avgDecimal` on PostgreSQL only), custom collection class (`extends Collection`), `with` and query fragments (`QueryFragment`, `Filtered`, `Ordered`), shared query fragments and scopes (`db.fragment(fields, body)` for a filter on every model with given fields, `CodecField`, `db.orm.public.Post.fragment(...)` for a shared `select` / `include`, `orderByField` for an order or sort parameter from a request), drizzle-style, kysely-style. Naming types (§ *Naming model and result types*): "type of my model", "return type of a query", `ResultType`, `Scalars`, `Shape`, `models` / `Models` namespace in `contract.d.ts`, `Models.public_User`, Prisma 7 `Prisma.User` / `GetPayload` / `UserGetPayload` equivalents. Postgres/SQLite specifics: [`references/queries-postgres.md`](references/queries-postgres.md); Mongo specifics: [`references/queries-mongo.md`](references/queries-mongo.md) | -| Wire the runtime | [`references/runtime.md`](references/runtime.md) | `db.ts`, `contractFromJson(...)`, `postgres({ contract })` / `sqlite({ contract })` / `mongo({ contract })` clients, middleware composition (lints, budgets, cache via `@prisma/orm-extension-middleware-cache`, custom `activityEnded` middleware, `@prisma/orm-postgres/family-runtime`), `DATABASE_URL`, `.env`, connection pool / `poolOptions`, dev vs prod config, transactions, read replicas, multi-database, script won't exit / hangs, `db.close` / `pool.end`, `await using` / `[Symbol.asyncDispose]` | +| Wire the runtime | [`references/runtime.md`](references/runtime.md) | `db.ts`, `contractFromJson(...)`, `postgres({ contract })` / `sqlite({ contract })` / `mongo({ contract })` clients, middleware composition (lints, budgets, cache via `@prisma/orm-extension-middleware-cache`, custom `activityEnded` middleware, `@prisma/orm-postgres/family-runtime`), `DATABASE_URL`, `.env`, connection pool / `poolOptions` / `createPgPool` / caller-owned `pg.Pool`, dev vs prod config, transactions, read replicas, multi-database, script won't exit / hangs, `db.close` / `pool.end`, `await using` / `[Symbol.asyncDispose]` | | Build-tool integration | [`references/build.md`](references/build.md) | Vite plugin (`@prisma/orm-/vite-plugin-contract-emit`, Vite 7/8), `vite.config.ts`, contract emit on save, HMR / dev server, Next.js / Webpack / esbuild / Rollup / Turbopack (named gaps, not fabricated) | | Supabase | [`references/supabase.md`](references/supabase.md) | `@prisma/orm-extension-supabase`, RLS, row level security, policies (`policy_select` / `policy_update` / `@@rls`, `auth.uid()`), role binding (`asUser(jwt)` / `asAnon()` / `asServiceRole()`), `auth.users`, cross-space FKs to `supabase:auth.AuthUser`, JWT / JWKS (`SUPABASE_JWKS_URL`, `SUPABASE_JWT_SECRET`), `SUPABASE.JWT_INVALID`, `SUPABASE.CONFIG_INVALID`, `RoleBoundDb`, session pooler | | Debug an error | [`references/debug.md`](references/debug.md) | any structured error envelope (code, severity, why, fix, nextActions, meta), emit failed, query won't typecheck, query crashed, migration won't apply, `MIGRATION.HASH_MISMATCH`, `MIGRATION.SCHEMA_VERIFY_FAILED`, `MIGRATION.PRECHECK_FAILED`, `BUDGET.ROWS_EXCEEDED`, `BUDGET.TIME_EXCEEDED`, `RUNTIME.ABORTED`, `RUNTIME.TEMPORAL_UNAVAILABLE`, `PLAN.HASH_MISMATCH`, `CONTRACT.SIGNATURE_MISSING`, `CONFIG.*` / `CLI.*` / `CONTRACT.*` / `MIGRATION.*` / `ORM.*` / `RUNTIME.*` codes, legacy `PN-*` codes, exit code 4 findings, drift, capability missing, planner conflict, EXPLAIN, query log, script won't exit / close connection | diff --git a/skills/prisma-8/references/build-a-target-package.md b/skills/prisma-8/references/build-a-target-package.md index 77197490c6d3..b5b87dcd91ac 100644 --- a/skills/prisma-8/references/build-a-target-package.md +++ b/skills/prisma-8/references/build-a-target-package.md @@ -14,7 +14,7 @@ This reference is for the author of a package that adds a database target to Pri | `/init` | the init contribution | `prisma orm init` | | `/runtime` | your client factory | the application's `db.ts` | -`/contract-builder` (the TypeScript contract builder bound to your target) and `/control` (a client for scripts) are conventions Prisma's packages follow. The Postgres package is the reference for all of these: `packages/3-targets/postgres/` in the prisma/orm repository, whose `9-facade` folder is the package applications install. +`/contract-builder` (the TypeScript contract builder bound to your target) and `/control` (a client for scripts) are conventions Prisma's packages follow. Two more are, at the layer beneath the client factory: `/target/runtime` (the runtime target descriptor a decomposed install composes — for Postgres, `@prisma/orm-postgres/target/runtime`, whose default export carries `sessionSettings`, the codec, query-operation and collection-method contributions) and `/driver/runtime` (the runtime driver descriptor, plus the pool factory — `createPgPool(config, sessionSettings)` on Postgres). The Postgres package is the reference for all of these: `packages/3-targets/postgres/` in the prisma/orm repository, whose `9-facade` folder is the package applications install. ## Generated files import from your package diff --git a/skills/prisma-8/references/debug.md b/skills/prisma-8/references/debug.md index a182c3ec1d45..3a73460415c4 100644 --- a/skills/prisma-8/references/debug.md +++ b/skills/prisma-8/references/debug.md @@ -51,7 +51,7 @@ Every code is a dotted `NAMESPACE.SUBCODE`; the namespace is the prefix (`CONFIG `category` is the prefix of `code` (`PLAN`, `CONTRACT`, `LINT`, `BUDGET`, `RUNTIME`, `ORM`, …). `details` holds the structured context (`details` is the runtime envelope's equivalent of the CLI envelope's `meta`). Recognise a thrown runtime error with `isStructuredError`, imported from the database package's `runtime` (`import { isStructuredError } from '@prisma/orm-postgres/runtime'`), and match on `error.code` — never `instanceof`. The CLI envelope is JSON output, with `summary` and no `message`, so `isStructuredError` does not recognise it; a script reads `code` from the parsed JSON instead. -**3. SQL driver errors** — surface as `SqlQueryError` / `SqlConnectionError` (see `packages/2-sql-family/1-core/errors/`). Fields on `SqlQueryError`: `kind: 'sql_query'`, `sqlState` (Postgres SQLSTATE, e.g. `'23505'`), `constraint`, `table`, `column`, `detail`, `cause`. These carry no dotted code — 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. +**3. SQL driver errors** — surface as `SqlQueryError` / `SqlConnectionError`, exported from `@prisma/orm-family-sql/errors` (the same classes every SQL facade's driver throws. `instanceof` holds only when the application's `@prisma/orm-family-sql` matches the version its facade uses — that direct-dependency pin is what gives both one module copy; a different version can load separate copies of the classes, and `instanceof` then misses errors from the other copy). Fields on `SqlQueryError`: `kind: 'sql_query'`, `sqlState` (Postgres SQLSTATE, e.g. `'23505'`), `constraint`, `table`, `column`, `detail`, `cause`; on `SqlConnectionError`: `kind: 'sql_connection'`, `transient`, `sqlState`, `cause`. `isUniqueConstraintViolation(error)`, from the same entry point, classifies a unique or primary-key violation from the driver-normalized `sqlState` (`'23505'`) without any target-specific error shape. These carry no dotted code — 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. ### Migration apply failures @@ -119,7 +119,7 @@ The single source of truth: read the envelope, find the row by `code`, follow th | `ORM.OPERATION_UNSUPPORTED` with `reason: 'required-foreign-key'` | ORM nested `disconnect()` on a relation whose foreign key is required, or `deleteFirst()` on a relation the record holds a required key for (`meta.model`, `meta.fields`) | For `disconnect`: if `meta.model` is the model being updated, the record holds the key (a many-to-one relation, such as `Post.author`): `connect` it to another row or delete the record. Otherwise the related rows hold it (one-to-many, or one-to-one from the side without the key): connect them to another record or delete them. For `deleteFirst` (the record holds the key): `connect` the record to another row, or delete the record, before deleting the related row through its own collection. Or make the key optional. | | `ORM.ARGUMENT_INVALID` with `problem: 'missing-where'` | ORM nested `updateFirst()` / `deleteFirst()` on a to-many relation without a `where` that filters | Add `where(...)` naming the related row to change. | | `RUNTIME.ABORTED` (`details.phase` = `encode\|decode\|stream\|beforeEncode\|onRow`) | Runtime, when an `AbortSignal` fires mid-execute | Cancellation, not a bug; surface to the caller. | -| `SqlQueryError` (no dotted 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. | +| `SqlQueryError` (no dotted 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. Catch it with `SqlQueryError` from `@prisma/orm-family-sql/errors`; classify a unique violation with `isUniqueConstraintViolation(error)` from the same entry point. Importing `/errors` directly requires `@prisma/orm-family-sql` as a direct dependency pinned to the facade's version (the family README's requirement) — a transitive install is not importable, and a mismatched version breaks `instanceof`. | | 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 | A method is offered only when the contract requires its capability. On PostgreSQL the contract's `requiredCapabilities` list (in `defineContract`, or beside the path in the config's contract entry) is that list; the error message names the key to add. Route to `references/contract.md` for the list and to `references/queries.md` for which method gates on which capability. Re-emit (`pnpm prisma contract emit`) after adding it. | | TypeScript error mentioning a missing field/method on `db.orm..` or a stale `Contract` shape | Authoring-time | Re-emit (`pnpm prisma contract emit`); confirm `db.ts` builds its contract with `contractFromJson(contractJson)` and passes it to `postgres({ contract })` (the client infers the contract types from it). See `references/runtime.md` and `references/contract.md`. | diff --git a/skills/prisma-8/references/migrations.md b/skills/prisma-8/references/migrations.md index 8ef7ca51a678..a9b7472bc706 100644 --- a/skills/prisma-8/references/migrations.md +++ b/skills/prisma-8/references/migrations.md @@ -760,6 +760,33 @@ After planning or applying, you can inspect the migration graph offline: For the full graph topology: `pnpm prisma migration graph` (also supports `--legend`, `--ascii`, `--dot`, `--json`). +## Reading migration packages in a script + +The same on-disk format the commands above render is readable programmatically, from `@prisma/orm-/migration-tools/io` (e.g. `@prisma/orm-postgres/migration-tools/io`) — the reader the CLI itself uses, for a script that audits a project's migrations or checks a migration package's integrity outside the CLI: + +- `readMigrationPackage(dir, options)` reads one package directory and returns its `OnDiskMigrationPackage` (`migration.json` + `ops.json`, validated). `options` takes `migrationsDir` — the project's top-level migrations directory, which the contract snapshots resolve against — and an optional `verifySnapshotContent` check for the end-contract snapshot. On a snapshot-content mismatch, the tolerant read omits `endContractJson` without adding a `PackageLoadProblem`, and the migration hash still passes because it covers only the manifest and operations — so an audit that checks only `problems` misses it; snapshot-integrity checks must read through the strict store instead: `readContractSnapshotJson(migrationsDir, storageHash, verifier)` from `@prisma/orm-/migration-tools/contract-snapshot-store` reports the mismatch as `MIGRATION.CONTRACT_SNAPSHOT_CONTENT_MISMATCH`, but only when its third argument is a verifier — called without one it only reads and parses the file and returns its content unchecked, a mismatched snapshot included. Build it with `createSnapshotContentVerifier(hooks)` from the same entry point, with `hooks` the ones the target's contract serializer declares — `contractSerializer.hashCanonicalizationHooks` on the default export of `@prisma/orm-/target/control` — since they are the canonicalization the published hash was computed with; a serializer that declares none (Mongo) cannot be recomputed from a snapshot, so its snapshots read without content verification, as they do in the CLI. +- `readMigrationsDir(migrationsRoot, options)` reads a graph directory. It never throws on a bad package: the result's `packages` keeps every package it could read (hash-mismatched ones included, represented rather than fatal) and `problems` carries one `PackageLoadProblem` per package it could not — `hashMismatch` (stored vs recomputed `migrationHash`), `providedInvariantsMismatch`, or `packageUnloadable` (that one is omitted from `packages`). A directory that does not exist reads as an empty graph, not an error. A subdirectory without `migration.json` (one that lost its manifest but keeps `ops.json`, say) is skipped before loading — no `packageUnloadable` is reported for it — so an audit that relies on `problems` should also check that each package directory it expects still has its `migration.json` — the directory existing proves nothing, since a directory that lost its manifest is exactly what gets skipped — or compare the directories it expects with the `dirName`s the read reports across `packages` and `problems`. Filesystem errors do throw when listing the root (other than its absence) or stat-ing an entry (a broken symlink, say). The manifest check is the exception: it catches every error from stat-ing `migration.json`, not only the file's absence, so a failure there (a permission error, say) skips the directory exactly as a missing manifest does — no `PackageLoadProblem`, the package in neither `packages` nor `problems` — and the check against the expected directories above covers that case too. + +Migration packages live per contract space, under `//` (`app` is the application's own space id), so a script reads the space's directory and passes the top-level migrations directory as the option. The default `migrations.dir` is `migrations` (relative to the config file); on a project that keeps the default, both paths are `migrations`-rooted as below — on a project that configures `migrations.dir`, pass paths that match it, or the read sees a directory that does not exist and audits nothing. Where the script is started from matters the same way: the reader takes paths as given and resolves relative ones against the working directory, never against the config file (anchoring `migrations.dir` to the config file's directory is something the CLI does before it calls the reader), so a script started from another directory reads a directory that does not exist and — since a missing root reads as an empty graph — audits nothing. Start it from the config file's directory, or anchor both paths to that directory yourself: + +```typescript +import { resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { readMigrationsDir } from '@prisma/orm-postgres/migration-tools/io'; + +// Anchored to this script's own directory (here: the project root, next to +// the config file) rather than to the working directory it is started from: +const migrationsDir = fileURLToPath(new URL('migrations', import.meta.url)); +const { packages, problems } = await readMigrationsDir(resolve(migrationsDir, 'app'), { + migrationsDir, +}); +for (const problem of problems) { + console.error(`${problem.dirName}: ${problem.kind}`); +} +``` + +A `hashMismatch` problem is the programmatic form of `MIGRATION.HASH_MISMATCH`: `ops.json` / `migration.json` were edited without self-emitting, and the fix is the same (see *Workflow — Recover from `MIGRATION.HASH_MISMATCH`*). Editing the files directly is still not supported — the reader is for auditing, not for authoring. + ## `@@control` and DDL scope Objects whose `@@control` policy excludes them from Prisma 8's managed surface are omitted from planned DDL. The four policies are: `managed` (Prisma plans and applies DDL), `tolerated` (object may exist, no DDL emitted), `external` (object is expected to exist, no DDL), `observed` (Prisma reads but never writes). Declare `@@control(managed|tolerated|external|observed)` in your schema; see `references/contract.md` and [`packages/2-sql-family/2-authoring/contract-psl/README.md`](https://github.com/prisma/orm/blob/main/packages/2-sql-family/2-authoring/contract-psl/README.md) for authoring syntax. diff --git a/skills/prisma-8/references/queries-postgres.md b/skills/prisma-8/references/queries-postgres.md index 432e9e449608..0e7a7394e6b1 100644 --- a/skills/prisma-8/references/queries-postgres.md +++ b/skills/prisma-8/references/queries-postgres.md @@ -654,6 +654,28 @@ db.sql.public.post The SQL builder's `.orderBy(column, { direction, nulls })` takes the same null placement: `.orderBy('invited_by_id', { direction: 'asc', nulls: 'first' })` renders `ORDER BY "invited_by_id" ASC NULLS FIRST`. +### The relational-AST layer beneath the builder + +The builder lowers into the relational AST, and the AST's surfaces are published entry points for code that works at that level — an extension operation's implementation, a plan inspector, a fragment the builder cannot spell: + +- `@prisma/orm-postgres/relational-core/expression` — the expression helpers. `param(value, { codecId })` wraps a value whose codec cannot be inferred from context, as in `param(cutoff, { codecId: 'pg/timestamptz-temporal@1' })` — the fix `RUNTIME.RAW_SQL_UNSUPPORTED_INTERPOLATION` names for a raw-SQL interpolation of anything other than `number`, `bigint`, `string`, `boolean` or `Uint8Array`. `toExpr(value, codec?)` lifts a value or expression into an AST expression. `buildOperation(spec)` turns an operation's arguments into the AST node the pipeline lowers. +- `@prisma/orm-postgres/relational-core/ast` — the AST node classes a plan's query is built from (`ColumnRef`, `ParamRef`, `LiteralExpr`, `BinaryExpr`, `TableSource`, …), plus the visitor and rewriter interfaces over them. +- `@prisma/orm-postgres/relational-core/types` — the plan and scope types. `SqlOrmPlan` is the shape `db.query(plan)` and `db.execute(plan)` accept. + +```typescript +import { param } from '@prisma/orm-postgres/relational-core/expression'; + +// A Timestamp value the raw lane cannot infer a codec for — wrapped, not refused. +const plan = db.raw.sql` + UPDATE "event" + SET "archived" = true + WHERE "at" < ${param(cutoff, { codecId: 'pg/timestamptz-temporal@1' })} +` + .affectedCount() + .build(); +const { affectedRows } = await db.execute(plan); +``` + ## Workflow — Transactions The concept: `db.transaction(fn)` opens a transaction and passes a `tx` context to the callback. `tx` offers the client's query members with the same types, and each runs inside the transaction: `sql`, `orm` (with the client's custom collection classes), `raw`, `prepare`, `query(plan)` (rows) and `execute(plan)` (affected count), plus `toSql`, `enums` and `nativeEnums`. A prepared statement runs on what it is given, so `ps.query(tx, params)` runs inside the transaction. See *Workflow — Transactions* in `references/runtime.md` for raw SQL and `tx.prepare`. The transaction commits on the callback's successful return and rolls back on any thrown error. diff --git a/skills/prisma-8/references/queries.md b/skills/prisma-8/references/queries.md index 552ab66eedec..dc230960eae2 100644 --- a/skills/prisma-8/references/queries.md +++ b/skills/prisma-8/references/queries.md @@ -229,7 +229,7 @@ Target-specific pitfalls live in the per-target guides. - **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. - **Ordering grouped aggregates by an aggregate alias (Postgres).** `db.orm...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..` 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. - **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`. -- **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, ending it with `.returns(codecId)`; an expression that holds an array, such as ``fns.raw`array_append(${f.tags}, 'x')` ``, ends with `.returns({ codecId: 'pg/text@1', many: { elementNullable: false } })`, so a list column's `update` value or `fns.eq` accepts it. +- **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, ending it with `.returns(codecId)`; an expression that holds an array, such as ``fns.raw`array_append(${f.tags}, 'x')` ``, ends with `.returns({ codecId: 'pg/text@1', many: { elementNullable: false } })`, so a list column's `update` value or `fns.eq` accepts it. A literal value the lane cannot infer a codec for (anything other than `number`, `bigint`, `string`, `boolean` or `Uint8Array`) is wrapped with `param(value, { codecId })` from `@prisma/orm-/relational-core/expression` (e.g. `@prisma/orm-postgres/relational-core/expression`) — the fix `RUNTIME.RAW_SQL_UNSUPPORTED_INTERPOLATION` names. The rule covers literal values only: a query fragment — a row-returning raw query, a builder subquery, or a row-returning builder mutation — interpolates directly, and wrapping one in `param(...)` would bind the fragment object itself as a parameter value instead of splicing in its SQL. - **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`. - **`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`. - **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`. diff --git a/skills/prisma-8/references/runtime.md b/skills/prisma-8/references/runtime.md index 35f67eed25a6..fcb5d3295533 100644 --- a/skills/prisma-8/references/runtime.md +++ b/skills/prisma-8/references/runtime.md @@ -329,10 +329,22 @@ postgres({ import { Pool } from 'pg'; const pool = new Pool({ connectionString: process.env['DATABASE_URL'] }); postgres({ contract, pg: pool }); + +// BYO pool with the target's session settings baked in — createPgPool is the +// same helper the factory itself uses for a url binding. +import { createPgPool } from '@prisma/orm-postgres/driver/runtime'; +import postgresTarget from '@prisma/orm-postgres/target/runtime'; +const settingsPool = createPgPool( + { connectionString: process.env['DATABASE_URL'] }, + postgresTarget.sessionSettings ?? {}, +); +postgres({ contract, pg: settingsPool }); ``` The `url` and `pg` keys are mutually exclusive at the type level; passing both errors. +A pool made with `new Pool(...)` works: the driver sets the session settings the Postgres target declares (`DateStyle: 'ISO'`) on each client it uses, at the cost of an extra round trip when a client is first used (and again after it was handed out for exclusive use, whose holder may have changed its session). `createPgPool(config, sessionSettings)` from `@prisma/orm-postgres/driver/runtime` instead makes a pool whose every session starts with the settings as startup options — no extra round trip, and `RESET ALL` keeps them. It takes the same `PoolConfig` `pg` takes plus the settings, and `postgresTarget.sessionSettings` from `@prisma/orm-postgres/target/runtime` is the settings the target declares. `createPgClient(config, sessionSettings)` does the same for a single `pg.Client`. + `DATABASE_URL` lives in `.env`. The CLI reads it for emit / verify / migration commands; the runtime reads it through `process.env` at `db.ts` load time. ## Workflow — Per-environment config (dev vs prod)