Skip to content
21 changes: 21 additions & 0 deletions packages/9-public/@prisma/orm-family-sql/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
35 changes: 35 additions & 0 deletions packages/9-public/@prisma/orm-postgres/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
4 changes: 2 additions & 2 deletions skills/prisma-8/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<Contract>(...)`, `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<Contract>(...)`, `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-<target>/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 |
Expand Down
2 changes: 1 addition & 1 deletion skills/prisma-8/references/build-a-target-package.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Loading