@prisma/orm-mongo 8.0.0-rc.25-dev.9 → 8.0.0-rc.25-dev.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,9 +1,10 @@
1
1
  # @prisma/orm-mongo
2
2
 
3
- The one package a MongoDB application installs. It wires the framework, the Mongo family, and the Mongo target into a single lazy client, and brings the rest of the stack along as exact-pinned dependencies:
3
+ The package a MongoDB application installs for its database. It wires the framework, the Mongo family, and the Mongo target into a single lazy client. It names the platform packages it is built on as peer dependencies, each at this package's own exact version, so the application lists them beside it, every `@prisma/orm-*` line naming the same version. `prisma orm init` writes that list, in the form the project's package manager writes a version it is given. To install them by hand, give every `@prisma/orm-*` package the same version, the release you want:
4
4
 
5
5
  ```sh
6
- pnpm add @prisma/orm-mongo mongodb
6
+ pnpm add @prisma/orm-mongo@<version> @prisma/orm-framework@<version> @prisma/orm-family-mongo@<version> @prisma/orm-target-mongo@<version> @prisma/orm-toolchain@<version>
7
+ pnpm add mongodb
7
8
  ```
8
9
 
9
10
  ```
@@ -14,6 +15,10 @@ pnpm add @prisma/orm-mongo mongodb
14
15
  └── @prisma/orm-toolchain ORM command family for the `prisma` CLI, emitter, config loader
15
16
  ```
16
17
 
18
+ The application lists the platform packages because it must hold exactly one copy of each: the platform packages recognise a data-type value by which copy made it. A data-type value made by a second copy is refused with an error that does not name the cause, and TypeScript reports errors where the two copies' types meet. A package manager never gives a package its own copy of a peer dependency; it uses the one the application lists, and it reports a version that does not match. When the packages that disagree are ones the application lists itself, npm refuses the install, and pnpm, Yarn and Bun install and print a peer dependency warning. A successful install does not prove the versions match, so read the peer warnings it prints. Application code still imports only from `@prisma/orm-mongo` and from the extensions, never from a platform package. The decision record explains this in full: [ADR 329](https://github.com/prisma/orm/blob/main/docs/architecture%20docs/adrs/ADR%20329%20-%20An%20application%20lists%20the%20platform%20packages%20and%20our%20packages%20name%20each%20other%20as%20peers.md).
19
+
20
+ In a repository with several applications on different Prisma versions, npm workspaces and Bun with its hoisted linker can give one application two copies of a platform package without a warning. Keep the applications on one Prisma version, or use pnpm, Yarn, or Bun with its isolated linker.
21
+
17
22
  `mongodb` is a peer dependency: the driver is the application's, so a single connection pool and a single BSON implementation serve both Prisma 8 and any direct `mongodb` use in the same process.
18
23
 
19
24
  `temporal-polyfill` is a required peer dependency. The control plane, such as the `prisma` commands, loads it as a fallback `Temporal` when the runtime has none, and a project that already installs it for its own code has one copy. npm, pnpm and bun install it automatically; with Yarn, add `temporal-polyfill` to your dependencies.
@@ -32,7 +37,7 @@ pnpm add @prisma/orm-mongo mongodb
32
37
  | `/migration`, `/control` | migration planning and the control client |
33
38
  | `/init` | the init contribution `prisma orm init` writes a project from |
34
39
 
35
- A generated `contract.d.ts` imports every framework, family and target type it names from `/contract-types`, and a generated `migration.ts` imports from `/migration`: the modules this package's `defineConfig` sets as `contract.typesModule` and `migrations.module`. The facade also forwards the namespaces of the packages it is built from, so an application never has to depend on a package it did not install:
40
+ A generated `contract.d.ts` imports every framework, family and target type it names from `/contract-types`, and a generated `migration.ts` imports from `/migration`: the modules this package's `defineConfig` sets as `contract.typesModule` and `migrations.module`. This package also forwards the namespaces of the packages it is built from, so application code imports from this package alone, even though the application lists those packages too:
36
41
 
37
42
  | Namespace | Forwards |
38
43
  | --- | --- |
@@ -42,7 +47,7 @@ A generated `contract.d.ts` imports every framework, family and target type it n
42
47
  | `/target/*` | `@prisma/orm-target-mongo/target` |
43
48
  | `/adapter`, `/adapter/*` | `@prisma/orm-target-mongo/adapter` |
44
49
 
45
- These forward; they do not copy. `@prisma/orm-mongo/contract/types` and `@prisma/orm-framework/contract/types` are the same module, so shared registries and `instanceof` checks hold across the boundary.
50
+ These forward; they do not copy. `@prisma/orm-mongo/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.
46
51
 
47
52
  ## Prepared statements
48
53
 
@@ -8,8 +8,8 @@ import { buildNamespacedEnums } from "@prisma/orm-framework/contract/enum-access
8
8
  import { UNBOUND_NAMESPACE_ID } from "@prisma/orm-framework/components/ir";
9
9
  import { mongoQuery } from "@prisma/orm-family-mongo/query-builder";
10
10
  import { assertDefined } from "@prisma/orm-framework/utils/assertions";
11
- //#region ../../../3-targets/mongo/9-facade/dist/mongo-static-DU3UYNCF.mjs
12
- var version = "8.0.0-rc.25-dev.9";
11
+ //#region ../../../3-targets/mongo/9-facade/dist/mongo-static-pko2uoKk.mjs
12
+ var version = "8.0.0-rc.25-dev.10";
13
13
  const serializer = new MongoContractSerializer();
14
14
  const validator = `${mongoRuntimeTarget.targetId}@${version}`;
15
15
  /**
@@ -69,4 +69,4 @@ function mongoStatic(options) {
69
69
  //#endregion
70
70
  export { validateMongoContract as i, contractFromJson as n, mongoStatic as r, buildMongoStaticContext as t };
71
71
 
72
- //# sourceMappingURL=mongo-static-DU3UYNCF-BrYN5Wtc.mjs.map
72
+ //# sourceMappingURL=mongo-static-pko2uoKk-kw9nHizD.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mongo-static-pko2uoKk-kw9nHizD.mjs","names":[],"sources":["../../../../3-targets/mongo/9-facade/dist/mongo-static-pko2uoKk.mjs"],"sourcesContent":["import mongoRuntimeAdapter from \"@internal/adapter-mongo/runtime\";\nimport { mongoRaw } from \"@internal/mongo-orm\";\nimport { createMongoExecutionContext, createMongoExecutionStack, enumMemberCodecFor } from \"@internal/mongo-runtime\";\nimport mongoRuntimeTarget from \"@internal/target-mongo/runtime\";\nimport { validateContractOnce } from \"@internal/contract/validate-once\";\nimport { MongoContractSerializer } from \"@internal/family-mongo/ir\";\nimport { buildNamespacedEnums } from \"@internal/contract/enum-accessor\";\nimport { UNBOUND_NAMESPACE_ID } from \"@internal/framework-components/ir\";\nimport { mongoQuery } from \"@internal/mongo-query-builder\";\nimport { assertDefined } from \"@internal/utils/assertions\";\n//#region package.json\nvar version = \"8.0.0-rc.25-dev.10\";\n//#endregion\n//#region src/static/contract-from-json.ts\nconst serializer = new MongoContractSerializer();\nconst validator = `${mongoRuntimeTarget.targetId}@${version}`;\n/**\n* Validates an emitted Mongo `contract.json` and returns it as the contract type the application\n* names, ready to pass to `mongo({ contract })` and `mongoStatic({ contract })`. Clients built from\n* the result do not validate it again.\n*\n* The returned value's top level is frozen; its nested objects are not. Do not change `json` or the\n* returned value after the call: clients built from the value later do not validate it again.\n*\n* @example\n* ```ts\n* import type { Contract } from './contract.d';\n* import contractJson from './contract.json' with { type: 'json' };\n*\n* export const contract = contractFromJson<Contract>(contractJson);\n* ```\n*/\nfunction contractFromJson(json) {\n\treturn validateContractOnce(json, validator, (input) => serializer.deserializeContract(input));\n}\nfunction validateMongoContract(contract) {\n\treturn contractFromJson(contract);\n}\n//#endregion\n//#region src/static/mongo-static.ts\nfunction buildMongoStaticContext(contract, stack) {\n\tconst context = createMongoExecutionContext({\n\t\tcontract,\n\t\tstack\n\t});\n\tconst enums = Object.freeze(buildNamespacedEnums(context.contract.domain, enumMemberCodecFor(context.codecs)))[UNBOUND_NAMESPACE_ID];\n\tassertDefined(enums, \"the unbound namespace always exists on a mongo builder output\");\n\treturn {\n\t\tcontext,\n\t\tcontract,\n\t\tenums,\n\t\tquery: mongoQuery({ context }),\n\t\traw: mongoRaw({ context })\n\t};\n}\n/**\n* The query surfaces of a Mongo client without a driver: `query`, `raw` and `enums`. Use it where\n* loading `mongodb` is not wanted.\n*\n* @example\n* ```ts\n* const { enums } = mongoStatic({ contract: contractFromJson<Contract>(contractJson) });\n* ```\n*/\nfunction mongoStatic(options) {\n\tconst stack = createMongoExecutionStack({\n\t\ttarget: mongoRuntimeTarget,\n\t\tadapter: mongoRuntimeAdapter,\n\t\textensions: options.extensions ?? []\n\t});\n\treturn buildMongoStaticContext(validateMongoContract(options.contract), stack);\n}\n//#endregion\nexport { validateMongoContract as i, mongoStatic as n, contractFromJson as r, buildMongoStaticContext as t };\n\n//# sourceMappingURL=mongo-static-pko2uoKk.mjs.map"],"mappings":";;;;;;;;;;;AAWA,IAAI,UAAU;AAGd,MAAM,aAAa,IAAI,wBAAwB;AAC/C,MAAM,YAAY,GAAG,mBAAmB,SAAS,GAAG;;;;;;;;;;;;;;;;;AAiBpD,SAAS,iBAAiB,MAAM;CAC/B,OAAO,qBAAqB,MAAM,YAAY,UAAU,WAAW,oBAAoB,KAAK,CAAC;AAC9F;AACA,SAAS,sBAAsB,UAAU;CACxC,OAAO,iBAAiB,QAAQ;AACjC;AAGA,SAAS,wBAAwB,UAAU,OAAO;CACjD,MAAM,UAAU,4BAA4B;EAC3C;EACA;CACD,CAAC;CACD,MAAM,QAAQ,OAAO,OAAO,qBAAqB,QAAQ,SAAS,QAAQ,mBAAmB,QAAQ,MAAM,CAAC,CAAC,CAAC,CAAC;CAC/G,cAAc,OAAO,+DAA+D;CACpF,OAAO;EACN;EACA;EACA;EACA,OAAO,WAAW,EAAE,QAAQ,CAAC;EAC7B,KAAK,SAAS,EAAE,QAAQ,CAAC;CAC1B;AACD;;;;;;;;;;AAUA,SAAS,YAAY,SAAS;CAC7B,MAAM,QAAQ,0BAA0B;EACvC,QAAQ;EACR,SAAS;EACT,YAAY,QAAQ,cAAc,CAAC;CACpC,CAAC;CACD,OAAO,wBAAwB,sBAAsB,QAAQ,QAAQ,GAAG,KAAK;AAC9E"}
package/dist/runtime.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { i as validateMongoContract, t as buildMongoStaticContext } from "./mongo-static-DU3UYNCF-BrYN5Wtc.mjs";
1
+ import { i as validateMongoContract, t as buildMongoStaticContext } from "./mongo-static-pko2uoKk-kw9nHizD.mjs";
2
2
  import { ifDefined } from "@prisma/orm-framework/utils/defined";
3
3
  import mongoRuntimeAdapter from "@prisma/orm-target-mongo/adapter/runtime";
4
4
  import { mongoOrm } from "@prisma/orm-family-mongo/orm";
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.mjs","names":[],"sources":["../../../../3-targets/mongo/9-facade/dist/runtime.mjs"],"sourcesContent":["import { i as validateMongoContract, t as buildMongoStaticContext } from \"./mongo-static-DU3UYNCF.mjs\";\nimport { ifDefined } from \"@internal/utils/defined\";\nimport mongoRuntimeAdapter from \"@internal/adapter-mongo/runtime\";\nimport mongoRuntimeDriver from \"@internal/driver-mongo/runtime\";\nimport { AsyncIterableResult } from \"@internal/framework-components/runtime\";\nimport { mongoOrm } from \"@internal/mongo-orm\";\nimport { createMongoExecutionStack, createMongoRuntime } from \"@internal/mongo-runtime\";\nimport mongoRuntimeTarget from \"@internal/target-mongo/runtime\";\nimport { InternalError } from \"@internal/utils/internal-error\";\nimport { ConnectionString } from \"mongodb-connection-string-url\";\nimport { structuredError } from \"@internal/utils/structured-error\";\nimport { blindCast } from \"@internal/utils/casts\";\n//#region src/runtime/mongo-errors.ts\nfunction mongoError(code, message, options) {\n\treturn structuredError(code, message, {\n\t\t...options,\n\t\tmeta: {\n\t\t\t...options?.meta,\n\t\t\textension: \"mongo\"\n\t\t}\n\t});\n}\n//#endregion\n//#region src/runtime/binding.ts\nconst URL_SCHEME_PATTERN = /^([a-z][a-z\\d+.-]*):\\/\\//i;\nconst MONGO_SCHEMES = /* @__PURE__ */ new Set([\"mongodb\", \"mongodb+srv\"]);\nfunction validateMongoUrl(url) {\n\tconst trimmed = url.trim();\n\tif (trimmed.length === 0) throw mongoError(\"RUNTIME.BINDING_INVALID\", \"Mongo URL must be a non-empty string\");\n\tconst scheme = URL_SCHEME_PATTERN.exec(trimmed)?.[1];\n\tif (scheme === void 0) throw mongoError(\"RUNTIME.BINDING_INVALID\", \"Mongo URL must be a valid URL\");\n\tif (!MONGO_SCHEMES.has(scheme)) throw mongoError(\"RUNTIME.BINDING_INVALID\", \"Mongo URL must use mongodb:// or mongodb+srv://\");\n\ttry {\n\t\treturn new ConnectionString(trimmed);\n\t} catch {\n\t\tthrow mongoError(\"RUNTIME.BINDING_INVALID\", \"Mongo URL must be a valid URL\");\n\t}\n}\nfunction extractDbNameFromUrl(parsed) {\n\tconst [encodedDbName = \"\"] = parsed.pathname.slice(1).split(\"/\");\n\tif (encodedDbName.length === 0) return;\n\ttry {\n\t\treturn decodeURIComponent(encodedDbName);\n\t} catch {\n\t\tthrow mongoError(\"RUNTIME.BINDING_INVALID\", \"Mongo URL must be a valid URL\");\n\t}\n}\nfunction resolveMongoBinding(options) {\n\tconst providedCount = Number(options.binding !== void 0) + Number(options.url !== void 0) + Number(options.uri !== void 0) + Number(options.mongoClient !== void 0);\n\tif (providedCount !== 1) throw mongoError(\"RUNTIME.BINDING_INVALID\", \"Provide one binding input: binding, url, uri+dbName, or mongoClient+dbName\", { meta: { received: providedCount } });\n\tif (options.binding !== void 0) return options.binding;\n\tif (options.url !== void 0) {\n\t\tconst parsed = validateMongoUrl(options.url);\n\t\tif (options.dbName !== void 0 && options.dbName.trim().length === 0) throw mongoError(\"RUNTIME.BINDING_INVALID\", \"Mongo binding via { url, dbName } requires a non-empty dbName\");\n\t\tconst explicitDbName = options.dbName?.trim();\n\t\tconst dbName = explicitDbName !== void 0 && explicitDbName.length > 0 ? explicitDbName : extractDbNameFromUrl(parsed);\n\t\tif (dbName === void 0 || dbName.length === 0) throw mongoError(\"RUNTIME.BINDING_INVALID\", \"Mongo URL must include a database name in its path (e.g. mongodb://host:27017/mydb), or pass dbName explicitly\");\n\t\treturn {\n\t\t\tkind: \"url\",\n\t\t\turl: options.url.trim(),\n\t\t\tdbName\n\t\t};\n\t}\n\tif (options.uri !== void 0) {\n\t\tvalidateMongoUrl(options.uri);\n\t\tconst dbName = options.dbName?.trim();\n\t\tif (dbName === void 0 || dbName.length === 0) throw mongoError(\"RUNTIME.BINDING_INVALID\", \"Mongo binding via { uri, dbName } requires a non-empty dbName\");\n\t\treturn {\n\t\t\tkind: \"url\",\n\t\t\turl: options.uri.trim(),\n\t\t\tdbName\n\t\t};\n\t}\n\tconst mongoClient = options.mongoClient;\n\tif (mongoClient === void 0) throw new InternalError(\"Invariant violation: expected mongo binding after validation\");\n\tconst dbName = options.dbName?.trim();\n\tif (dbName === void 0 || dbName.length === 0) throw mongoError(\"RUNTIME.BINDING_INVALID\", \"Mongo binding via { mongoClient, dbName } requires a non-empty dbName\");\n\treturn {\n\t\tkind: \"mongoClient\",\n\t\tclient: mongoClient,\n\t\tdbName\n\t};\n}\nfunction resolveOptionalMongoBinding(options) {\n\tconst providedCount = Number(options.binding !== void 0) + Number(options.url !== void 0) + Number(options.uri !== void 0) + Number(options.mongoClient !== void 0);\n\tif (providedCount === 0) return;\n\tif (providedCount !== 1) throw mongoError(\"RUNTIME.BINDING_INVALID\", \"Provide one binding input: binding, url, uri+dbName, or mongoClient+dbName\", { meta: { received: providedCount } });\n\tif (options.binding !== void 0) return resolveMongoBinding({ binding: options.binding });\n\tif (options.url !== void 0) return resolveMongoBinding(options.dbName !== void 0 ? {\n\t\turl: options.url,\n\t\tdbName: options.dbName\n\t} : { url: options.url });\n\tif (options.uri !== void 0) return resolveMongoBinding({\n\t\turi: options.uri,\n\t\tdbName: options.dbName ?? \"\"\n\t});\n\tif (options.mongoClient !== void 0) return resolveMongoBinding({\n\t\tmongoClient: options.mongoClient,\n\t\tdbName: options.dbName ?? \"\"\n\t});\n\tthrow new InternalError(\"Invariant violation: expected one mongo binding branch\");\n}\n//#endregion\n//#region src/runtime/prepared-row-query.ts\nasync function prepareMongoQuery(runtime, declaration, callback) {\n\tlet description;\n\tconst statement = await runtime.prepare(declaration, (placeholders) => {\n\t\tconst authored = callback(placeholders);\n\t\tif (\"plan\" in authored) {\n\t\t\tdescription = authored;\n\t\t\treturn authored.plan;\n\t\t}\n\t\treturn authored;\n\t});\n\treturn blindCast(description ? createMongoPreparedRowQuery(description, statement) : statement);\n}\nfunction createMongoPreparedRowQuery(description, statement) {\n\treturn Object.freeze({ query(target, params, options) {\n\t\treturn description.consume(statement.query(target, params, options));\n\t} });\n}\n//#endregion\n//#region src/runtime/mongo.ts\n/**\n* Creates a lazy Mongo client. The client infers its contract type from `contract`: a value from\n* `contractFromJson` for an emitted contract, or a TypeScript-authored contract. A contract is\n* validated once, however many clients are built from it. The `orm` and `query` surfaces are\n* available at once; the driver connects on the first query or `connect()`.\n*\n* @example\n* ```ts\n* import { contractFromJson } from '@prisma/orm-mongo/static';\n* import mongo from '@prisma/orm-mongo/runtime';\n* import type { Contract } from './contract.d';\n* import contractJson from './contract.json' with { type: 'json' };\n*\n* export const contract = contractFromJson<Contract>(contractJson);\n* export const db = mongo({ contract, url: process.env['MONGODB_URL']! });\n* ```\n*/\nfunction mongo(options) {\n\tconst contract = validateMongoContract(options.contract);\n\tlet binding = resolveOptionalMongoBinding(options);\n\tconst stack = createMongoExecutionStack({\n\t\ttarget: mongoRuntimeTarget,\n\t\tadapter: mongoRuntimeAdapter,\n\t\tdriver: mongoRuntimeDriver,\n\t\textensions: options.extensions ?? []\n\t});\n\tconst { context, query, enums, raw } = buildMongoStaticContext(contract, stack);\n\tlet runtimePromise;\n\tlet closed = false;\n\tlet runtimeInstance;\n\tconst closedError = () => mongoError(\"DRIVER.NOT_CONNECTED\", \"Mongo client is closed\");\n\tconst createRuntime = () => {\n\t\tif (runtimeInstance !== void 0) return runtimeInstance;\n\t\tconst driver = stack.driver.create();\n\t\truntimeInstance = {\n\t\t\truntime: createMongoRuntime({\n\t\t\t\tcontext,\n\t\t\t\tadapter: stack.adapter.create(stack),\n\t\t\t\tdriver,\n\t\t\t\t...ifDefined(\"mode\", options.mode),\n\t\t\t\t...ifDefined(\"middleware\", options.middleware)\n\t\t\t}),\n\t\t\tdriver\n\t\t};\n\t\treturn runtimeInstance;\n\t};\n\tconst buildRuntime = async (resolvedBinding) => {\n\t\tconst { runtime, driver } = createRuntime();\n\t\tawait driver.connect(resolvedBinding);\n\t\treturn runtime;\n\t};\n\tconst getRuntime = () => {\n\t\tif (closed) return Promise.reject(closedError());\n\t\tif (runtimePromise !== void 0) return runtimePromise;\n\t\tif (binding === void 0) return Promise.reject(mongoError(\"RUNTIME.BINDING_MISSING\", \"Mongo binding not configured. Pass url/uri+dbName/mongoClient+dbName/binding to mongo(...) or call db.connect({ ... }).\"));\n\t\truntimePromise = buildRuntime(binding).catch((err) => {\n\t\t\truntimePromise = void 0;\n\t\t\tthrow err;\n\t\t});\n\t\treturn runtimePromise;\n\t};\n\tfunction queryRows(plan) {\n\t\tasync function* iterate() {\n\t\t\tyield* (await getRuntime()).query(plan);\n\t\t}\n\t\treturn new AsyncIterableResult(iterate());\n\t}\n\tasync function executeStats(plan) {\n\t\treturn (await getRuntime()).execute(plan);\n\t}\n\treturn {\n\t\torm: mongoOrm({\n\t\t\tcontext,\n\t\t\truntime: {\n\t\t\t\tquery: queryRows,\n\t\t\t\texecute: executeStats\n\t\t\t}\n\t\t}),\n\t\tquery,\n\t\traw,\n\t\tcontract,\n\t\tenums,\n\t\tcontext,\n\t\tasync connect(bindingInput) {\n\t\t\tif (closed) throw closedError();\n\t\t\tif (runtimePromise !== void 0) {\n\t\t\t\tif (bindingInput !== void 0) throw mongoError(\"DRIVER.ALREADY_CONNECTED\", \"Mongo client is already bound\", {\n\t\t\t\t\twhy: \"connect() was given options after the client was bound to a database.\",\n\t\t\t\t\tfix: \"Call connect() without options, or create a new client for another database.\"\n\t\t\t\t});\n\t\t\t\tconst runtime = await runtimePromise;\n\t\t\t\tif (closed) throw closedError();\n\t\t\t\treturn runtime;\n\t\t\t}\n\t\t\tif (bindingInput !== void 0) binding = resolveMongoBinding(bindingInput);\n\t\t\tif (binding === void 0) throw mongoError(\"RUNTIME.BINDING_MISSING\", \"Mongo binding not configured. Pass url/uri+dbName/mongoClient+dbName/binding to mongo(...) or call db.connect({ ... }).\");\n\t\t\tconst runtime = await getRuntime();\n\t\t\tif (closed) throw closedError();\n\t\t\treturn runtime;\n\t\t},\n\t\truntime() {\n\t\t\treturn getRuntime();\n\t\t},\n\t\tasync prepare(declaration, callback) {\n\t\t\tif (closed) throw closedError();\n\t\t\treturn prepareMongoQuery(createRuntime().runtime, declaration, callback);\n\t\t},\n\t\tasync close() {\n\t\t\tif (closed) return;\n\t\t\tclosed = true;\n\t\t\tawait runtimePromise?.catch(() => void 0);\n\t\t\tawait runtimeInstance?.runtime.close();\n\t\t},\n\t\t[Symbol.asyncDispose]() {\n\t\t\treturn this.close();\n\t\t}\n\t};\n}\n//#endregion\nexport { mongo as default };\n\n//# sourceMappingURL=runtime.mjs.map"],"mappings":"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"}
1
+ {"version":3,"file":"runtime.mjs","names":[],"sources":["../../../../3-targets/mongo/9-facade/dist/runtime.mjs"],"sourcesContent":["import { i as validateMongoContract, t as buildMongoStaticContext } from \"./mongo-static-pko2uoKk.mjs\";\nimport { ifDefined } from \"@internal/utils/defined\";\nimport mongoRuntimeAdapter from \"@internal/adapter-mongo/runtime\";\nimport mongoRuntimeDriver from \"@internal/driver-mongo/runtime\";\nimport { AsyncIterableResult } from \"@internal/framework-components/runtime\";\nimport { mongoOrm } from \"@internal/mongo-orm\";\nimport { createMongoExecutionStack, createMongoRuntime } from \"@internal/mongo-runtime\";\nimport mongoRuntimeTarget from \"@internal/target-mongo/runtime\";\nimport { InternalError } from \"@internal/utils/internal-error\";\nimport { ConnectionString } from \"mongodb-connection-string-url\";\nimport { structuredError } from \"@internal/utils/structured-error\";\nimport { blindCast } from \"@internal/utils/casts\";\n//#region src/runtime/mongo-errors.ts\nfunction mongoError(code, message, options) {\n\treturn structuredError(code, message, {\n\t\t...options,\n\t\tmeta: {\n\t\t\t...options?.meta,\n\t\t\textension: \"mongo\"\n\t\t}\n\t});\n}\n//#endregion\n//#region src/runtime/binding.ts\nconst URL_SCHEME_PATTERN = /^([a-z][a-z\\d+.-]*):\\/\\//i;\nconst MONGO_SCHEMES = /* @__PURE__ */ new Set([\"mongodb\", \"mongodb+srv\"]);\nfunction validateMongoUrl(url) {\n\tconst trimmed = url.trim();\n\tif (trimmed.length === 0) throw mongoError(\"RUNTIME.BINDING_INVALID\", \"Mongo URL must be a non-empty string\");\n\tconst scheme = URL_SCHEME_PATTERN.exec(trimmed)?.[1];\n\tif (scheme === void 0) throw mongoError(\"RUNTIME.BINDING_INVALID\", \"Mongo URL must be a valid URL\");\n\tif (!MONGO_SCHEMES.has(scheme)) throw mongoError(\"RUNTIME.BINDING_INVALID\", \"Mongo URL must use mongodb:// or mongodb+srv://\");\n\ttry {\n\t\treturn new ConnectionString(trimmed);\n\t} catch {\n\t\tthrow mongoError(\"RUNTIME.BINDING_INVALID\", \"Mongo URL must be a valid URL\");\n\t}\n}\nfunction extractDbNameFromUrl(parsed) {\n\tconst [encodedDbName = \"\"] = parsed.pathname.slice(1).split(\"/\");\n\tif (encodedDbName.length === 0) return;\n\ttry {\n\t\treturn decodeURIComponent(encodedDbName);\n\t} catch {\n\t\tthrow mongoError(\"RUNTIME.BINDING_INVALID\", \"Mongo URL must be a valid URL\");\n\t}\n}\nfunction resolveMongoBinding(options) {\n\tconst providedCount = Number(options.binding !== void 0) + Number(options.url !== void 0) + Number(options.uri !== void 0) + Number(options.mongoClient !== void 0);\n\tif (providedCount !== 1) throw mongoError(\"RUNTIME.BINDING_INVALID\", \"Provide one binding input: binding, url, uri+dbName, or mongoClient+dbName\", { meta: { received: providedCount } });\n\tif (options.binding !== void 0) return options.binding;\n\tif (options.url !== void 0) {\n\t\tconst parsed = validateMongoUrl(options.url);\n\t\tif (options.dbName !== void 0 && options.dbName.trim().length === 0) throw mongoError(\"RUNTIME.BINDING_INVALID\", \"Mongo binding via { url, dbName } requires a non-empty dbName\");\n\t\tconst explicitDbName = options.dbName?.trim();\n\t\tconst dbName = explicitDbName !== void 0 && explicitDbName.length > 0 ? explicitDbName : extractDbNameFromUrl(parsed);\n\t\tif (dbName === void 0 || dbName.length === 0) throw mongoError(\"RUNTIME.BINDING_INVALID\", \"Mongo URL must include a database name in its path (e.g. mongodb://host:27017/mydb), or pass dbName explicitly\");\n\t\treturn {\n\t\t\tkind: \"url\",\n\t\t\turl: options.url.trim(),\n\t\t\tdbName\n\t\t};\n\t}\n\tif (options.uri !== void 0) {\n\t\tvalidateMongoUrl(options.uri);\n\t\tconst dbName = options.dbName?.trim();\n\t\tif (dbName === void 0 || dbName.length === 0) throw mongoError(\"RUNTIME.BINDING_INVALID\", \"Mongo binding via { uri, dbName } requires a non-empty dbName\");\n\t\treturn {\n\t\t\tkind: \"url\",\n\t\t\turl: options.uri.trim(),\n\t\t\tdbName\n\t\t};\n\t}\n\tconst mongoClient = options.mongoClient;\n\tif (mongoClient === void 0) throw new InternalError(\"Invariant violation: expected mongo binding after validation\");\n\tconst dbName = options.dbName?.trim();\n\tif (dbName === void 0 || dbName.length === 0) throw mongoError(\"RUNTIME.BINDING_INVALID\", \"Mongo binding via { mongoClient, dbName } requires a non-empty dbName\");\n\treturn {\n\t\tkind: \"mongoClient\",\n\t\tclient: mongoClient,\n\t\tdbName\n\t};\n}\nfunction resolveOptionalMongoBinding(options) {\n\tconst providedCount = Number(options.binding !== void 0) + Number(options.url !== void 0) + Number(options.uri !== void 0) + Number(options.mongoClient !== void 0);\n\tif (providedCount === 0) return;\n\tif (providedCount !== 1) throw mongoError(\"RUNTIME.BINDING_INVALID\", \"Provide one binding input: binding, url, uri+dbName, or mongoClient+dbName\", { meta: { received: providedCount } });\n\tif (options.binding !== void 0) return resolveMongoBinding({ binding: options.binding });\n\tif (options.url !== void 0) return resolveMongoBinding(options.dbName !== void 0 ? {\n\t\turl: options.url,\n\t\tdbName: options.dbName\n\t} : { url: options.url });\n\tif (options.uri !== void 0) return resolveMongoBinding({\n\t\turi: options.uri,\n\t\tdbName: options.dbName ?? \"\"\n\t});\n\tif (options.mongoClient !== void 0) return resolveMongoBinding({\n\t\tmongoClient: options.mongoClient,\n\t\tdbName: options.dbName ?? \"\"\n\t});\n\tthrow new InternalError(\"Invariant violation: expected one mongo binding branch\");\n}\n//#endregion\n//#region src/runtime/prepared-row-query.ts\nasync function prepareMongoQuery(runtime, declaration, callback) {\n\tlet description;\n\tconst statement = await runtime.prepare(declaration, (placeholders) => {\n\t\tconst authored = callback(placeholders);\n\t\tif (\"plan\" in authored) {\n\t\t\tdescription = authored;\n\t\t\treturn authored.plan;\n\t\t}\n\t\treturn authored;\n\t});\n\treturn blindCast(description ? createMongoPreparedRowQuery(description, statement) : statement);\n}\nfunction createMongoPreparedRowQuery(description, statement) {\n\treturn Object.freeze({ query(target, params, options) {\n\t\treturn description.consume(statement.query(target, params, options));\n\t} });\n}\n//#endregion\n//#region src/runtime/mongo.ts\n/**\n* Creates a lazy Mongo client. The client infers its contract type from `contract`: a value from\n* `contractFromJson` for an emitted contract, or a TypeScript-authored contract. A contract is\n* validated once, however many clients are built from it. The `orm` and `query` surfaces are\n* available at once; the driver connects on the first query or `connect()`.\n*\n* @example\n* ```ts\n* import { contractFromJson } from '@prisma/orm-mongo/static';\n* import mongo from '@prisma/orm-mongo/runtime';\n* import type { Contract } from './contract.d';\n* import contractJson from './contract.json' with { type: 'json' };\n*\n* export const contract = contractFromJson<Contract>(contractJson);\n* export const db = mongo({ contract, url: process.env['MONGODB_URL']! });\n* ```\n*/\nfunction mongo(options) {\n\tconst contract = validateMongoContract(options.contract);\n\tlet binding = resolveOptionalMongoBinding(options);\n\tconst stack = createMongoExecutionStack({\n\t\ttarget: mongoRuntimeTarget,\n\t\tadapter: mongoRuntimeAdapter,\n\t\tdriver: mongoRuntimeDriver,\n\t\textensions: options.extensions ?? []\n\t});\n\tconst { context, query, enums, raw } = buildMongoStaticContext(contract, stack);\n\tlet runtimePromise;\n\tlet closed = false;\n\tlet runtimeInstance;\n\tconst closedError = () => mongoError(\"DRIVER.NOT_CONNECTED\", \"Mongo client is closed\");\n\tconst createRuntime = () => {\n\t\tif (runtimeInstance !== void 0) return runtimeInstance;\n\t\tconst driver = stack.driver.create();\n\t\truntimeInstance = {\n\t\t\truntime: createMongoRuntime({\n\t\t\t\tcontext,\n\t\t\t\tadapter: stack.adapter.create(stack),\n\t\t\t\tdriver,\n\t\t\t\t...ifDefined(\"mode\", options.mode),\n\t\t\t\t...ifDefined(\"middleware\", options.middleware)\n\t\t\t}),\n\t\t\tdriver\n\t\t};\n\t\treturn runtimeInstance;\n\t};\n\tconst buildRuntime = async (resolvedBinding) => {\n\t\tconst { runtime, driver } = createRuntime();\n\t\tawait driver.connect(resolvedBinding);\n\t\treturn runtime;\n\t};\n\tconst getRuntime = () => {\n\t\tif (closed) return Promise.reject(closedError());\n\t\tif (runtimePromise !== void 0) return runtimePromise;\n\t\tif (binding === void 0) return Promise.reject(mongoError(\"RUNTIME.BINDING_MISSING\", \"Mongo binding not configured. Pass url/uri+dbName/mongoClient+dbName/binding to mongo(...) or call db.connect({ ... }).\"));\n\t\truntimePromise = buildRuntime(binding).catch((err) => {\n\t\t\truntimePromise = void 0;\n\t\t\tthrow err;\n\t\t});\n\t\treturn runtimePromise;\n\t};\n\tfunction queryRows(plan) {\n\t\tasync function* iterate() {\n\t\t\tyield* (await getRuntime()).query(plan);\n\t\t}\n\t\treturn new AsyncIterableResult(iterate());\n\t}\n\tasync function executeStats(plan) {\n\t\treturn (await getRuntime()).execute(plan);\n\t}\n\treturn {\n\t\torm: mongoOrm({\n\t\t\tcontext,\n\t\t\truntime: {\n\t\t\t\tquery: queryRows,\n\t\t\t\texecute: executeStats\n\t\t\t}\n\t\t}),\n\t\tquery,\n\t\traw,\n\t\tcontract,\n\t\tenums,\n\t\tcontext,\n\t\tasync connect(bindingInput) {\n\t\t\tif (closed) throw closedError();\n\t\t\tif (runtimePromise !== void 0) {\n\t\t\t\tif (bindingInput !== void 0) throw mongoError(\"DRIVER.ALREADY_CONNECTED\", \"Mongo client is already bound\", {\n\t\t\t\t\twhy: \"connect() was given options after the client was bound to a database.\",\n\t\t\t\t\tfix: \"Call connect() without options, or create a new client for another database.\"\n\t\t\t\t});\n\t\t\t\tconst runtime = await runtimePromise;\n\t\t\t\tif (closed) throw closedError();\n\t\t\t\treturn runtime;\n\t\t\t}\n\t\t\tif (bindingInput !== void 0) binding = resolveMongoBinding(bindingInput);\n\t\t\tif (binding === void 0) throw mongoError(\"RUNTIME.BINDING_MISSING\", \"Mongo binding not configured. Pass url/uri+dbName/mongoClient+dbName/binding to mongo(...) or call db.connect({ ... }).\");\n\t\t\tconst runtime = await getRuntime();\n\t\t\tif (closed) throw closedError();\n\t\t\treturn runtime;\n\t\t},\n\t\truntime() {\n\t\t\treturn getRuntime();\n\t\t},\n\t\tasync prepare(declaration, callback) {\n\t\t\tif (closed) throw closedError();\n\t\t\treturn prepareMongoQuery(createRuntime().runtime, declaration, callback);\n\t\t},\n\t\tasync close() {\n\t\t\tif (closed) return;\n\t\t\tclosed = true;\n\t\t\tawait runtimePromise?.catch(() => void 0);\n\t\t\tawait runtimeInstance?.runtime.close();\n\t\t},\n\t\t[Symbol.asyncDispose]() {\n\t\t\treturn this.close();\n\t\t}\n\t};\n}\n//#endregion\nexport { mongo as default };\n\n//# sourceMappingURL=runtime.mjs.map"],"mappings":"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"}
package/dist/static.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import { n as contractFromJson, r as mongoStatic } from "./mongo-static-DU3UYNCF-BrYN5Wtc.mjs";
1
+ import { n as contractFromJson, r as mongoStatic } from "./mongo-static-pko2uoKk-kw9nHizD.mjs";
2
2
  export { contractFromJson, mongoStatic as default };
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "@prisma/orm-mongo",
3
- "version": "8.0.0-rc.25-dev.9",
3
+ "version": "8.0.0-rc.25-dev.10",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "sideEffects": false,
7
- "description": "Prisma 8 for MongoDB: the one package a MongoDB application installs",
7
+ "description": "Prisma 8 for MongoDB: the package a MongoDB application installs for its database, beside the platform packages it names as peers",
8
8
  "keywords": [
9
9
  "prisma-orm-extension"
10
10
  ],
@@ -13,23 +13,27 @@
13
13
  "skills"
14
14
  ],
15
15
  "dependencies": {
16
- "@prisma/orm-family-mongo": "8.0.0-rc.25-dev.9",
17
- "@prisma/orm-framework": "8.0.0-rc.25-dev.9",
18
- "@prisma/orm-target-mongo": "8.0.0-rc.25-dev.9",
19
- "@prisma/orm-toolchain": "8.0.0-rc.25-dev.9",
20
16
  "mongodb-connection-string-url": "^7.0.2",
21
17
  "pathe": "^2.0.3",
22
18
  "tinyglobby": "^0.2.17",
23
19
  "temporal-spec": "1.0.1"
24
20
  },
25
21
  "devDependencies": {
26
- "@internal/mongo": "8.0.0-rc.25-dev.9",
27
- "@repo/tsconfig": "8.0.0-rc.25-dev.9",
28
- "@repo/tsdown": "8.0.0-rc.25-dev.9",
22
+ "@internal/mongo": "8.0.0-rc.25-dev.10",
23
+ "@prisma/orm-family-mongo": "8.0.0-rc.25-dev.10",
24
+ "@prisma/orm-framework": "8.0.0-rc.25-dev.10",
25
+ "@prisma/orm-target-mongo": "8.0.0-rc.25-dev.10",
26
+ "@prisma/orm-toolchain": "8.0.0-rc.25-dev.10",
27
+ "@repo/tsconfig": "8.0.0-rc.25-dev.10",
28
+ "@repo/tsdown": "8.0.0-rc.25-dev.10",
29
29
  "tsdown": "0.22.14",
30
30
  "typescript": "5.9.3"
31
31
  },
32
32
  "peerDependencies": {
33
+ "@prisma/orm-family-mongo": "8.0.0-rc.25-dev.10",
34
+ "@prisma/orm-framework": "8.0.0-rc.25-dev.10",
35
+ "@prisma/orm-target-mongo": "8.0.0-rc.25-dev.10",
36
+ "@prisma/orm-toolchain": "8.0.0-rc.25-dev.10",
33
37
  "mongodb": "^7.0.0",
34
38
  "temporal-polyfill": "^1.0.8",
35
39
  "typescript": ">=5.9"
@@ -15,7 +15,7 @@ description: >-
15
15
  ORM 7 or earlier (schema.prisma + @prisma/client).
16
16
  metadata:
17
17
  library: '@prisma/orm-mongo'
18
- library_version: '8.0.0-rc.25-dev.9'
18
+ library_version: '8.0.0-rc.25-dev.10'
19
19
  version: '2026-09-12'
20
20
  ---
21
21
 
@@ -29,7 +29,7 @@ Prisma 8 moves fast, and your training data about it is very likely outdated. Th
29
29
 
30
30
  Check these before acting on anything below. Halt on the first one that fails and tell the user what is missing. Pre-conditions 1 and 3 describe an application that is already set up. Check only pre-condition 2 in a package that builds a target or is a Prisma extension, and when setting up a new project, which creates what 1 and 3 check.
31
31
 
32
- 1. **The project is on Prisma 8.** `prisma.config.ts` exports `definePrismaConfig({ orm: ... })`, and `package.json` depends on a target package: `@prisma/orm-postgres`, `@prisma/orm-mongo`, `@prisma/orm-sqlite`, `@prisma/orm-mysql`, `@prisma/orm-mariadb`, or another package that `prisma.config.ts` imports `defineConfig` from. A project with `schema.prisma` and `@prisma/client` is Prisma 7 or earlier; this skill does not apply to it, and its instructions will break such a project.
32
+ 1. **The project is on Prisma 8.** `prisma.config.ts` exports `definePrismaConfig({ orm: ... })`, and `package.json` depends on the package for its database: `@prisma/orm-postgres`, `@prisma/orm-mongo`, `@prisma/orm-sqlite`, `@prisma/orm-mysql`, `@prisma/orm-mariadb`, or another package that `prisma.config.ts` imports `defineConfig` from. A project with `schema.prisma` and `@prisma/client` is Prisma 7 or earlier; this skill does not apply to it, and its instructions will break such a project.
33
33
  2. **The skill matches the installed version.** Compare `metadata.library_version` in this file's frontmatter with the installed `@prisma/orm-*` version in `package.json`. If they differ, run `prisma skills sync` and re-read this file before continuing. If no `@prisma/orm-*` package is installed, as in a project not set up yet, this check passes.
34
34
  3. **The contract artefacts exist.** `contract.json` and `contract.d.ts` sit next to the contract source named by `prisma.config.ts`. If they are missing or older than the source, run `prisma contract emit` first; every query and migration instruction below assumes current artefacts.
35
35
 
@@ -67,13 +67,13 @@ Open the reference whose triggers match the task. If more than one matches, open
67
67
  | 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 |
68
68
  | 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.MARKER_NOT_IN_HISTORY`, `MIGRATION.MISSING_INVARIANTS`, `db migrate --show` |
69
69
  | 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.orm.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) |
70
- | Wire the runtime | [`references/runtime.md`](references/runtime.md) | `db.ts`, `contractFromJson<Contract>(...)`, `postgres({ contract })` / `sqlite({ contract })` / `mongo({ contract })` façades, 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]` |
70
+ | 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]` |
71
71
  | 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) |
72
72
  | 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 |
73
73
  | 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.MARKER_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 |
74
74
  | Upgrade Prisma in an app | [`references/upgrade-app.md`](references/upgrade-app.md) | "upgrade Prisma", "upgrade Prisma 8", "bump Prisma 8", "move to Prisma 8 X.Y", `@prisma/orm-*` version bump in an application, per-transition upgrade instructions in [`upgrading/app/upgrades/`](upgrading/app/upgrades/), extension-pin pre-flight, `PN-UPGRADE-*` |
75
75
  | Upgrade Prisma in an extension | [`references/upgrade-extension.md`](references/upgrade-extension.md) | the same request in a package that *is* a Prisma extension (`@prisma/orm-framework` / SPI dependency, `^@.*/extension-` name), `prisma-8-check-pins`, exact-pin rule, per-transition instructions in [`upgrading/extension/upgrades/`](upgrading/extension/upgrades/) |
76
- | Build a target package | [`references/build-a-target-package.md`](references/build-a-target-package.md) | a new database target outside Prisma's repository, `prisma-orm-<name>`, `defineConfig` with `contract.typesModule` and `migrations.module`, `/contract-types`, `restateTypeDeclarations`, the `/init` entrypoint, `InitContribution`, `prisma orm init --target <package>`, `CONFIG.CONTRACT_TYPES_MODULE_MISSING`, `CONFIG.MIGRATION_MODULE_MISSING` |
76
+ | Build the package for a new database | [`references/build-a-target-package.md`](references/build-a-target-package.md) | a new database target outside Prisma's repository, `prisma-orm-<name>`, `defineConfig` with `contract.typesModule` and `migrations.module`, `/contract-types`, `restateTypeDeclarations`, the `/init` entrypoint, `InitContribution`, `prisma orm init --target <package>`, `CONFIG.CONTRACT_TYPES_MODULE_MISSING`, `CONFIG.MIGRATION_MODULE_MISSING` |
77
77
  | File feedback / ask the team | [`references/feedback.md`](references/feedback.md) | bug report, file an issue, feature request, missing feature, capability gap, "this is broken", surprising behaviour, Q&A / design discussion, ask the Prisma team, Prisma Discord (pris.ly/discord), extension-author questions |
78
78
 
79
79
  ## Routing rules
@@ -1,6 +1,6 @@
1
- # Build a target package
1
+ # Build the package for a new database
2
2
 
3
- This reference is for the author of a package that adds a database target to Prisma 8, outside Prisma's repository. An application installs the package, imports `defineConfig` from it in `prisma.config.ts`, and runs `prisma orm init --target <your package>` and `prisma contract emit` exactly as an application on `@prisma/orm-postgres` does. Prisma's own target packages use the mechanisms below, with no path an outside package lacks.
3
+ This reference is for the author of a package that adds a database target to Prisma 8, outside Prisma's repository. An application installs the package, imports `defineConfig` from it in `prisma.config.ts`, and runs `prisma orm init --target <your package>` and `prisma contract emit` exactly as an application on `@prisma/orm-postgres` does. Prisma's own database packages use the mechanisms below, with no path an outside package lacks.
4
4
 
5
5
  `prisma-orm-acmedb` stands for your package throughout.
6
6
 
@@ -97,15 +97,14 @@ Rules:
97
97
 
98
98
  - **No framework code runs in `/init`.** Types are fine. The CLI that loads it may be a different installed copy of the framework from the one your package depends on, and two copies in one process do not recognise each other's values.
99
99
  - **The connection string is `DATABASE_URL`.** `prisma.config.ts`, `db.ts` and `--probe-db` read it, and `dotenv` is installed with your package, so `db.ts` may import `dotenv/config`. `--probe-db` reads it from the shell's environment, not from `.env`.
100
- - **Drivers.** `init` reads `peerPackages` only after your package is installed. The first install is your package and `dotenv`; the package manager handles your package's required peers its own way, and a configuration that refuses a package without its peers makes that install fail, which `init` reports. Declare your driver as a required peer dependency, and list it in `peerPackages` so `init` declares it in the application.
101
- - **`/init` loads without the driver.** For a package that is not in the CLI's list, the driver is installed after `/init` is loaded, so import the driver inside `probe`, when it runs, and report `driver-missing` if that import fails.
100
+ - **Drivers.** The first install is your package and `dotenv`; the package manager handles your package's required peers its own way, and a configuration that refuses a package without its peers makes that install fail, which `init` reports. `init` then installs the required peers your manifest declares, before it loads `/init`, and reads `peerPackages` after. Declare your driver as a required peer dependency, and list it in `peerPackages` too.
101
+ - **`/init` loads without the driver.** A driver your manifest does not declare as a required peer is installed only after `/init` is loaded, so import the driver inside `probe`, when it runs, and report `driver-missing` if that import fails.
102
102
  - **The probe** resolves to the server's version, `driver-missing`, `driver-failed`, or `version-unreadable` once connected, and rejects only when it cannot connect. Bound its connect and query with your driver's own timeouts. `init` aborts `signal` after 60 seconds; close your client when it fires.
103
103
 
104
104
  ## Package rules
105
105
 
106
106
  - Name the package `prisma-orm-<name>`, under your scope if you have one, and add the keyword `prisma-orm-extension` to its `package.json`. The keyword is required: `prisma orm init --target` reads it before installing your package and refuses a package without it. `init` checks the copy it is about to load: the registry's `latest` version when it will install your package, and the installed `package.json` when it will not: under `--skip-install`, or when the project already declares your package and has it on disk. It asks the registry without credentials, so a user of a package on a registry that needs them, or on a scope's own registry, installs the package first and then runs `init`.
107
- - Depend on the Prisma packages your code imports at run time (`@prisma/orm-framework`, your family's package), each pinned to one exact version; see [`upgrade-extension.md`](upgrade-extension.md) § *Exact-pin rule*.
108
- - `/init` imports only the `InitContribution` type from `@prisma/orm-toolchain`. If that is your package's only use of it, make it a development dependency: as a pinned dependency it gives the application a second copy of the toolchain whenever its `prisma` is another version.
107
+ - Name every Prisma package your code or its type declarations use (`@prisma/orm-framework`, your family's package, and `@prisma/orm-toolchain`, whose `InitContribution` type `/init` uses) as a peer dependency at one exact version, and again as a development dependency so your own build and tests install them. None of them is an ordinary dependency: an ordinary dependency at another version than the application's gives the application a second copy. `prisma orm init` reads your package's `peerDependencies` and adds to the application every required peer it finds there: the `@prisma/orm-*` packages, followed through their own peers, and every other package your manifest does not mark optional in `peerDependenciesMeta`, your driver included, at the version or range you give. So declare everything an application must install as a required peer dependency in your package's own manifest. `peerPackages` in your init contribution still names your driver, which `init` installs as well; a driver that is also a required peer is installed once. See [`upgrade-extension.md`](upgrade-extension.md) § *Exact-pin rule*.
109
108
  - Import or name no module beginning `@internal/`. Those are Prisma's private workspace names.
110
109
 
111
110
  ## Check it from outside
@@ -116,7 +116,7 @@ See [`examples/react-router-demo`](https://github.com/prisma/prisma/tree/main/ex
116
116
  ## What Prisma 8 doesn't do yet
117
117
 
118
118
  - **Next.js plugin.** No first-party Next.js plugin exists. Workaround: run `prisma contract emit` from a `prebuild` script in `package.json` and run it manually during development when the contract changes. Many Next.js projects also run a dev-time `tsx --watch` against a small script that calls the CLI on contract-source change. If you want a first-party Next.js plugin, file a feature request via the `references/feedback.md` skill.
119
- - **Webpack, esbuild, Rollup, Turbopack plugins.** None exist yet as first-party. `executeContractEmit`, the function the Vite plugin calls, is exported only by the platform package `@prisma/orm-toolchain` (`cli/control-api`), and no database package re-exports it; an application should not depend on a platform package (it depends on its database package and extension packs only), so do not build a plugin on it. Workaround: run `prisma contract emit` from the bundler's prebuild step (or a `prebuild` script in `package.json`), and rerun it when the contract changes during development. If you want a first-party plugin for your bundler, or a public entry for contract emission, file a feature request via the `references/feedback.md` skill.
119
+ - **Webpack, esbuild, Rollup, Turbopack plugins.** None exist yet as first-party. `executeContractEmit`, the function the Vite plugin calls, is exported only by the platform package `@prisma/orm-toolchain` (`cli/control-api`), and no database package re-exports it; application code imports only from its database package and extension packs, never from a platform package, even though `package.json` lists the platform packages; so do not build a plugin on it. Workaround: run `prisma contract emit` from the bundler's prebuild step (or a `prebuild` script in `package.json`), and rerun it when the contract changes during development. If you want a first-party plugin for your bundler, or a public entry for contract emission, file a feature request via the `references/feedback.md` skill.
120
120
  - **`vite build` integration.** The plugin runs in `vite dev` only. Workaround: a `prebuild` script that runs `prisma contract emit`. If you want the plugin to also run during `vite build`, file a feature request via the `references/feedback.md` skill.
121
121
  - **Vite 6 or earlier.** Not on the support matrix. Workaround: upgrade Vite to 7 or 8. If you have a hard reason to stay on Vite 6, file a feature request via the `references/feedback.md` skill.
122
122
 
@@ -9,7 +9,7 @@ The data contract is the single source of truth for your data layer. You edit a
9
9
  2. **The system plans the migrations for you.** (`references/migrations.md`)
10
10
  3. **If you need a data migration, you write a `dataTransform` in `migration.ts` and execute it.** Inserts, updates and deletes never go in a `rawSql` step. (`references/migrations.md`)
11
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:
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 database package picks based on the file extension of `contract:` in `prisma.config.ts`, then writes two artefacts colocated with the source:
13
13
 
14
14
  - `contract.json` — the canonical, content-hashed Contract IR. Read by the planner, the runtime, and `db verify`.
15
15
  - `contract.d.ts` — the precise TypeScript types the runtime + lanes propagate when you import `Contract` from it.
@@ -27,7 +27,7 @@ Both files are **emitted artefacts**. Edit the source; never the JSON or `.d.ts`
27
27
  - User wants to install or configure an extension via `extensions: [...]` in `prisma.config.ts`, including `@prisma/orm-extension-supabase`.
28
28
  - User is migrating between authoring sources (PSL ↔ TypeScript builder).
29
29
  - User received `CONFIG.CONTRACT_MISSING`, `CONTRACT.VALIDATION_FAILED`, or `CONFIG.MISSING_EXTENSION_PACKS` from `contract emit`.
30
- - User mentions: *schema, fields, models, attributes, prisma schema, PSL, contract.prisma, contract.ts, contract.json, contract.d.ts, contract emit, façade imports, `@prisma/orm-postgres/config`, `@prisma/orm-postgres/contract-builder`, extensions, pgvector, 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 8 doesn't do yet* below.)
30
+ - User mentions: *schema, fields, models, attributes, prisma schema, PSL, contract.prisma, contract.ts, contract.json, contract.d.ts, contract emit, database package imports, `@prisma/orm-postgres/config`, `@prisma/orm-postgres/contract-builder`, extensions, pgvector, 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 8 doesn't do yet* below.)
31
31
 
32
32
  ## When Not to Use
33
33
 
@@ -41,11 +41,11 @@ Both files are **emitted artefacts**. Edit the source; never the JSON or `.d.ts`
41
41
 
42
42
  ## Key Concepts
43
43
 
44
- - **The `@prisma/orm-<target>` façade is the only surface user-authored code imports from.** For a Postgres app: `@prisma/orm-postgres/config`, `@prisma/orm-postgres/contract-builder`, `@prisma/orm-postgres/control`, `@prisma/orm-postgres/runtime`, `@prisma/orm-postgres/static`. Mongo has the same layout (`@prisma/orm-mongo/config`, `@prisma/orm-mongo/contract-builder`, `@prisma/orm-mongo/runtime`, `@prisma/orm-mongo/static`). Each extension publishes its own façade — `@prisma/orm-extension-pgvector/control`, `@prisma/orm-extension-postgis/control`, `@prisma/orm-extension-paradedb/control`. **Never import the platform packages (`@prisma/orm-framework`, `@prisma/orm-family-*`, `@prisma/orm-target-*`, `@prisma/orm-toolchain`) from user code.** The façade bakes the family / target / adapter / driver wiring in. See *Common Pitfalls* #4.
44
+ - **The `@prisma/orm-<target>` package is the only surface user-authored code imports from.** For a Postgres app: `@prisma/orm-postgres/config`, `@prisma/orm-postgres/contract-builder`, `@prisma/orm-postgres/control`, `@prisma/orm-postgres/runtime`, `@prisma/orm-postgres/static`. Mongo has the same layout (`@prisma/orm-mongo/config`, `@prisma/orm-mongo/contract-builder`, `@prisma/orm-mongo/runtime`, `@prisma/orm-mongo/static`). Each extension publishes its own entry points — `@prisma/orm-extension-pgvector/control`, `@prisma/orm-extension-postgis/control`, `@prisma/orm-extension-paradedb/control`. **Never import the platform packages (`@prisma/orm-framework`, `@prisma/orm-family-*`, `@prisma/orm-target-*`, `@prisma/orm-toolchain`) from user code.** The database package bakes the family / target / adapter / driver wiring in. See *Common Pitfalls* #4.
45
45
  - **Contract source.** A file the framework reads and lowers to the canonical Contract IR. Two flavours, both first-class:
46
46
  - **`contract.prisma` (PSL)** — schema-flavoured DSL. Canonical for typical apps and brownfield Prisma users. Wired by `contract: './<path>/contract.prisma'` — the target config (`ormConfig`, below) detects the `.prisma` extension and routes through the PSL provider. The first line of every `.prisma` file is `// use prisma-8`; `orm init` and `contract infer` write it, and the language server only serves diagnostics, completion, and formatting on files that carry it (it still recognises the header earlier releases wrote and rewrites it on Format).
47
- - **`contract.ts` (TypeScript builder)** — programmatic authoring with `defineContract({...}, ({ field, model, rel, type }) => ({...}))` from `@prisma/orm-postgres/contract-builder` (or `@prisma/orm-mongo/contract-builder`, `@prisma/orm-sqlite/contract-builder`, `@prisma/orm-mysql/contract-builder`, `@prisma/orm-mariadb/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).
48
- - **An existing Prisma schema, during adoption.** A project that still runs an earlier Prisma can point `contract:` at its current `schema.prisma` instead of writing a Prisma 8 contract: `contract: prisma6Schema('prisma/schema.prisma')` from `@prisma/orm-mongo/config` reads a Prisma 6 MongoDB schema, and `prisma7Schema` from `@prisma/orm-postgres/config` reads a Prisma 7 Postgres schema. The earlier Prisma keeps owning the database; after each change there, run `contract emit` and `db sign`. A construct Prisma 8 cannot express fails `contract emit` with a `PSL.PRISMA6_MONGO_*` or `PSL.PRISMA7_*` diagnostic. See the façade READMEs for the details.
47
+ - **`contract.ts` (TypeScript builder)** — programmatic authoring with `defineContract({...}, ({ field, model, rel, type }) => ({...}))` from `@prisma/orm-postgres/contract-builder` (or `@prisma/orm-mongo/contract-builder`, `@prisma/orm-sqlite/contract-builder`, `@prisma/orm-mysql/contract-builder`, `@prisma/orm-mariadb/contract-builder`). Wired by `contract: './<path>/contract.ts'` — the database package 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).
48
+ - **An existing Prisma schema, during adoption.** A project that still runs an earlier Prisma can point `contract:` at its current `schema.prisma` instead of writing a Prisma 8 contract: `contract: prisma6Schema('prisma/schema.prisma')` from `@prisma/orm-mongo/config` reads a Prisma 6 MongoDB schema, and `prisma7Schema` from `@prisma/orm-postgres/config` reads a Prisma 7 Postgres schema. The earlier Prisma keeps owning the database; after each change there, run `contract emit` and `db sign`. A construct Prisma 8 cannot express fails `contract emit` with a `PSL.PRISMA6_MONGO_*` or `PSL.PRISMA7_*` diagnostic. See the database package READMEs for the details.
49
49
  - **`prisma.config.ts`.** Wires the contract source, the database connection, the migrations directory, and any installed extensions. The file is an *envelope*: the unified CLI's `definePrismaConfig({...})` from `@prisma/cli-engine` wraps an `orm:` section built by the target's `defineConfig` — conventionally imported as `ormConfig` from `@prisma/orm-postgres/config` (or `@prisma/orm-mongo/config`). There is no flat form; a bare `defineConfig({ contract, ... })` default export fails with `CONFIG.VERSION_MARKER_MISSING`. Pass `formatter: { indent, newline }` to `ormConfig` to set how `prisma contract format` and the language server lay out PSL files: `indent` is a whole number of spaces, 1 or more (default 2), or `'tab'`. `newline` is `'LF'` or `'CRLF'`; without it, `contract format` uses the operating system's line ending and the language server uses LF.
50
50
 
51
51
  ```typescript
@@ -63,9 +63,9 @@ Both files are **emitted artefacts**. Edit the source; never the JSON or `.d.ts`
63
63
  ```
64
64
 
65
65
  The fields `ormConfig` accepts: `contract` (path string — `.prisma` or `.ts`), `output` (optional override for where `contract.json` lands), `db` (`{ connection?: string }`), `extensions` (array of control descriptors), `migrations` (`{ dir?: string }`), `formatter` (`{ indent?: number | 'tab'; newline?: 'LF' | 'CRLF' }`). Without `output`, the path for `contract.json` is derived from `contract` (e.g. `./src/prisma/contract.prisma` → `./src/prisma/contract.json`). Keep `import 'dotenv/config'` when the config reads `process.env`.
66
- - **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.
66
+ - **Emit pipeline.** `prisma contract emit --config <path>?` reads `prisma.config.ts`, calls the provider the database package picked, validates the resulting Contract, then atomically writes `contract.json` + `contract.d.ts` colocated with the source.
67
67
  - **Extension namespaces.** Extensions contribute namespaced constructors (`pgvector.Vector(length: 1536)`, `postgis.Geometry(...)`) and type aliases. 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:
68
- - **In the config (façade and core):** `extensions: [pgvector]` — array of *control* descriptors imported from `@prisma/orm-extension-<name>/control`.
68
+ - **In the config (database package and core):** `extensions: [pgvector]` — array of *control* descriptors imported from `@prisma/orm-extension-<name>/control`.
69
69
  - **In the TS builder's `defineContract` (only when authoring `contract.ts`):** `extensions: { pgvector }` — record of *pack* descriptors imported from `@prisma/orm-extension-<name>/pack`.
70
70
  - **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.):
71
71
  - **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 and what `prisma orm init` scaffolds by default (`src/prisma/contract.prisma` with `db.ts` beside it).
@@ -86,7 +86,7 @@ Both files are **emitted artefacts**. Edit the source; never the JSON or `.d.ts`
86
86
 
87
87
  ## Workflow — Read the contract source of truth
88
88
 
89
- 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: [...]`.
89
+ 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 database package), and open the file it points at. The same field tells you the installed `extensions: [...]`.
90
90
 
91
91
  ```bash
92
92
  cat prisma.config.ts
@@ -171,7 +171,7 @@ Note: scalar lists (e.g. `String[]`) are gated on the target's `sql.scalarList`
171
171
 
172
172
  ## Workflow — Edit a model / field / relation (TS builder)
173
173
 
174
- 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 `@prisma/orm-postgres/family` and `@prisma/orm-postgres/target`. Use the callback overload (`defineContract({...}, ({ field, model, rel, type, gen }) => ({...}))`) to get the type constructors, type aliases and generator calls (`field.column(type.String())`, `field.column(type.Uuid()).id().onCreate(gen.uuid(7))`, `field.column(type.temporal.CreatedAt())`, `type.sql.Varchar(35)`).
174
+ The concept: same model, different authoring surface. The database package re-exports `defineContract`, `field`, `model`, `rel`, plus the `family`/`target` packs as default exports of `@prisma/orm-postgres/family` and `@prisma/orm-postgres/target`. Use the callback overload (`defineContract({...}, ({ field, model, rel, type, gen }) => ({...}))`) to get the type constructors, type aliases and generator calls (`field.column(type.String())`, `field.column(type.Uuid()).id().onCreate(gen.uuid(7))`, `field.column(type.temporal.CreatedAt())`, `type.sql.Varchar(35)`).
175
175
 
176
176
  ```typescript
177
177
  import sqlFamily from '@prisma/orm-postgres/family';
@@ -197,7 +197,7 @@ export const contract = defineContract(
197
197
  );
198
198
  ```
199
199
 
200
- Then `pnpm prisma contract emit`. Every facade's `contract-builder` entry exports `field` and `gen`. The Postgres, SQLite and MongoDB entries also export `type`. These are the helpers the callback receives, without the ones an extension adds (such as pgvector's `type.pgvector.Vector`); for those, use the callback's helpers. On MySQL and MariaDB, `type` is only available inside the callback overload.
200
+ Then `pnpm prisma contract emit`. Every database package's `contract-builder` entry exports `field` and `gen`. The Postgres, SQLite and MongoDB entries also export `type`. These are the helpers the callback receives, without the ones an extension adds (such as pgvector's `type.pgvector.Vector`); for those, use the callback's helpers. On MySQL and MariaDB, `type` is only available inside the callback overload.
201
201
 
202
202
  For Mongo, swap every `@prisma/orm-postgres/*` import for `@prisma/orm-mongo/*`. The Mongo builder also exposes `index` and `valueObject`.
203
203
 
@@ -514,8 +514,8 @@ Infer captures indexes at full fidelity — expression, partial (`where:`), uniq
514
514
 
515
515
  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`).
516
516
  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.
517
- 3. **Wrong factory/import path for the TS builder.** `defineContract`, `field`, `model`, `rel` come from `@prisma/orm-postgres/contract-builder` (or the `contract-builder` entry of the SQLite, MySQL, MariaDB or Mongo facade). Every facade's `contract-builder` exports `gen` (`.onCreate(gen.uuid())`). The Postgres, SQLite and Mongo facades also export `type` (`field.column(type.TimestamptzTemporal())` on Postgres); on MySQL and MariaDB, outside the callback overload, the available field constructors are `field.column(...)` and `field.namedType(...)`.
518
- 4. **Reaching into internal packages from user code.** User-authored files (`prisma.config.ts`, `contract.ts`, `db.ts`, control clients) import only from `@prisma/orm-<target>/<subpath>` and `@prisma/orm-extension-<name>/<subpath>`. Imports from the platform packages (`@prisma/orm-framework`, `@prisma/orm-family-*`, `@prisma/orm-target-*`, `@prisma/orm-toolchain`) are framework wiring — the façade composes them for you, and an application that depends on a façade does not install them directly. If a façade subpath you need is missing for your target, see *What Prisma 8 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`.
517
+ 3. **Wrong factory/import path for the TS builder.** `defineContract`, `field`, `model`, `rel` come from `@prisma/orm-postgres/contract-builder` (or the `contract-builder` entry of the SQLite, MySQL, MariaDB or Mongo package). Every database package's `contract-builder` exports `gen` (`.onCreate(gen.uuid())`). The Postgres, SQLite and Mongo package also export `type` (`field.column(type.TimestamptzTemporal())` on Postgres); on MySQL and MariaDB, outside the callback overload, the available field constructors are `field.column(...)` and `field.namedType(...)`.
518
+ 4. **Reaching into internal packages from user code.** User-authored files (`prisma.config.ts`, `contract.ts`, `db.ts`, control clients) import only from `@prisma/orm-<target>/<subpath>` and `@prisma/orm-extension-<name>/<subpath>`. Imports from the platform packages (`@prisma/orm-framework`, `@prisma/orm-family-*`, `@prisma/orm-target-*`, `@prisma/orm-toolchain`) are framework wiring — the database package composes them for you. The application lists them in `package.json` beside its database package, so it holds one copy of each (a monorepo whose applications are on different Prisma versions can still get two; see [ADR 329](https://github.com/prisma/orm/blob/main/docs/architecture%20docs/adrs/ADR%20329%20-%20An%20application%20lists%20the%20platform%20packages%20and%20our%20packages%20name%20each%20other%20as%20peers.md#consequences)), but user code never imports them. If a database package subpath you need is missing for your target, see *What Prisma 8 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`.
519
519
  5. **Confusing the config `extensions` with the TS builder's `extensions`.** Same packs, two surfaces, one field name but two shapes: `ormConfig({ extensions: [pgvector] })` (array of *control* descriptors from `@prisma/orm-extension-<name>/control`) versus `defineContract({ extensions: { pgvector } })` (record of *pack* descriptors from `@prisma/orm-extension-<name>/pack`).
520
520
  6. **Writing a flat `prisma.config.ts`.** `export default defineConfig({ contract, extensions })` from the target config alone is the pre-rc.4 shape and fails with `CONFIG.VERSION_MARKER_MISSING`. Wrap it: `definePrismaConfig({ orm: ormConfig({...}) })`.
521
521
  7. **Renaming a model or field and expecting the planner to detect it.** The contract does not record renames, so the planner sees a destructive drop+add. State the rename on the command line with `--rename old:new` on `migration plan` or `db update` (see `references/migrations.md`); the planner then renames instead of dropping. Do not invent a rename attribute in the contract source.
@@ -68,7 +68,7 @@ These symptoms are not structured envelopes — route on the message text and ch
68
68
  | Symptom | Next move |
69
69
  |---|---|
70
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)*. |
71
+ | Script hangs after queries print / process won't exit | On Postgres the `pg.Pool` that the database package owns 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
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
73
 
74
74
  ## Routing — symptom and code → next move
@@ -273,7 +273,7 @@ MigrationCLI.run(import.meta.url, M);
273
273
 
274
274
  Replace both `placeholder(...)` calls with query-plan closures built with the SQL query builder. The `check` closure must return a **rowset query whose presence of any row signals "work remains"** — conventionally `<table>.select('id').where(<violation predicate>).limit(1)`. Scalar/aggregate shapes (`count(*)`, `bool_and(...)`) silently break the contract: the runner wraps `check` twice (`EXISTS(...)` for precheck, `NOT EXISTS(...)` for postcheck), and a query that always returns one row makes `EXISTS` always true and `NOT EXISTS` always false.
275
275
 
276
- Build the query builder over the end contract, and pass the same client's `contract` to `this.dataTransform`; a plan built over a different contract raises `MIGRATION.DATA_TRANSFORM_CONTRACT_MISMATCH`. The cheapest way to get a typed SQL builder over the end contract is the façade itself: `postgres({ contract: contractFromJson<End>(endContract) })` connects lazily, so constructing it inside `migration.ts` opens no connection; its `sql` is the builder and its `contract` is the validated contract to hand to `this.dataTransform`. The filled-in shape is the rendered scaffold above with two changes: the two `placeholder(...)` arrows are replaced, and the first argument of `this.dataTransform` is the client's `contract` instead of the imported `endContract`. The planner renders `endContract`, the raw JSON, which is not a validated contract ([prisma/orm#30504](https://github.com/prisma/orm/issues/30504)). The operation list, including the `this.setNotNull({...})` the planner rendered after the transform, stays as rendered:
276
+ Build the query builder over the end contract, and pass the same client's `contract` to `this.dataTransform`; a plan built over a different contract raises `MIGRATION.DATA_TRANSFORM_CONTRACT_MISMATCH`. The cheapest way to get a typed SQL builder over the end contract is the database package itself: `postgres({ contract: contractFromJson<End>(endContract) })` connects lazily, so constructing it inside `migration.ts` opens no connection; its `sql` is the builder and its `contract` is the validated contract to hand to `this.dataTransform`. The filled-in shape is the rendered scaffold above with two changes: the two `placeholder(...)` arrows are replaced, and the first argument of `this.dataTransform` is the client's `contract` instead of the imported `endContract`. The planner renders `endContract`, the raw JSON, which is not a validated contract ([prisma/orm#30504](https://github.com/prisma/orm/issues/30504)). The operation list, including the `this.setNotNull({...})` the planner rendered after the transform, stays as rendered:
277
277
 
278
278
  ```typescript
279
279
  import { col, Migration, MigrationCLI } from '@prisma/orm-postgres/migration';
@@ -51,7 +51,7 @@ const recent = await db.orm.posts
51
51
 
52
52
  **`.where(...)`** accepts a plain object whose keys are model field names and values are compared with equality (codec-aware — `ObjectId` fields accept string ids from the contract). Chain multiple `.where({ ... })` calls to AND-compose filters.
53
53
 
54
- For operators the object form doesn't cover (`.in([...])`, range comparisons, nested logic), pass a `MongoFilterExpr` — today that means importing filter helpers from `@prisma/orm-mongo/query-ast/execution` (a façade-completeness gap; see *What Prisma 8 doesn't do yet* in [`queries.md`](./queries.md)). Prefer the object form whenever equality suffices.
54
+ For operators the object form doesn't cover (`.in([...])`, range comparisons, nested logic), pass a `MongoFilterExpr` — today that means importing filter helpers from `@prisma/orm-mongo/query-ast/execution` (a gap in the database package; see *What Prisma 8 doesn't do yet* in [`queries.md`](./queries.md)). Prefer the object form whenever equality suffices.
55
55
 
56
56
  **Polymorphic roots.** When the contract declares variants on a model, narrow before querying. `.variant()` takes the discriminator value a variant declares (`"article"` from `@@base(Post, "article")`), not the variant's model name. Call it once, on the base collection; a second `.variant()` on a variant collection is refused:
57
57
 
@@ -247,8 +247,8 @@ In an ORM read, a placeholder goes in `limit`, `offset`, a scalar field's value
247
247
  2. **Using `.all()` when you wanted one row.** Use `.where({ ... }).first()` — not `.all()`.
248
248
  3. **Calling `.update()` / `.delete()` without `.where()`.** Mutations other than `.create` / `.createAll` require a filter — the compiler enforces this at the type level where possible.
249
249
  4. **Using PascalCase model names on ORM.** Roots are lowercased plurals from the contract (`db.orm.users`, not `db.orm.User`).
250
- 5. **Expecting Postgres-style lambda `.where((u) => u.email.eq(...))` on ORM.** Prefer object equality `.where({ email: '...' })`; richer operators need `MongoFilterExpr` helpers (façade gap today).
251
- 6. **Expecting `db.transaction(...)`.** The Mongo façade does not expose it today. Multi-document atomicity requires MongoDB transactions on a replica set via the driver — not yet wrapped in the Prisma 8 façade. Route to *What Prisma 8 doesn't do yet* / `references/feedback.md` if the user needs this.
250
+ 5. **Expecting Postgres-style lambda `.where((u) => u.email.eq(...))` on ORM.** Prefer object equality `.where({ email: '...' })`; richer operators need `MongoFilterExpr` helpers (a gap in the database package today).
251
+ 6. **Expecting `db.transaction(...)`.** The Mongo package does not expose it today. Multi-document atomicity requires MongoDB transactions on a replica set via the driver — not yet wrapped in the Prisma 8 database package. Route to *What Prisma 8 doesn't do yet* / `references/feedback.md` if the user needs this.
252
252
  7. **Trying to use `db.sql`.** There is no `db.sql` on Mongo.
253
253
  8. **Trying to `db.execute(plan)` directly, or reading documents with `execute`.** Run query-builder plans via `(await db.runtime()).query(plan)`. `execute(plan)` resolves statistics only and throws `RUNTIME.MONGO_STATISTICS_UNSUPPORTED` for a find or aggregate.
254
254
  9. **Expecting ORM `.aggregate(...)` / `.groupBy(...)`.** Use `db.query.from(...).group(...).build()` instead.
@@ -186,7 +186,7 @@ await db.orm.public.Sale
186
186
 
187
187
  The two forms emit the same SQL. Pick chained `.where()` when each clause adds a separate condition that reads as its own thought; pick `and(...)` when one logical predicate happens to have two parts and you want the visual grouping. Don't reach for a `between` helper — there isn't one.
188
188
 
189
- **Combinators** (`and`, `or`, `not`) compose predicates, and **relation predicates** (`.some(...)`, `.none(...)`, `.every(...)`) recurse into a relation. `.some()` and `.none()` take an optional predicate — `u.posts.none()` means "has no posts", `u.posts.some()` means "has at least one" — while `.every(...)` requires one: `u.posts.every((p) => p.published.eq(true))`. The combinators are exported from the façade's `orm-client` subpath:
189
+ **Combinators** (`and`, `or`, `not`) compose predicates, and **relation predicates** (`.some(...)`, `.none(...)`, `.every(...)`) recurse into a relation. `.some()` and `.none()` take an optional predicate — `u.posts.none()` means "has no posts", `u.posts.some()` means "has at least one" — while `.every(...)` requires one: `u.posts.every((p) => p.published.eq(true))`. The combinators are exported from the database package's `orm-client` subpath:
190
190
 
191
191
  ```typescript
192
192
  import { and, or, not } from '@prisma/orm-postgres/orm-client';
@@ -431,7 +431,7 @@ await db.orm.public.User.with(createdSince(since)).all();
431
431
  await db.orm.public.Post.with(createdSince(since)).deleteAll();
432
432
  ```
433
433
 
434
- Pick the builder whose codec matches the field's codec in `contract.d.ts`: a PSL `TimestamptzTemporal` is `field.column(type.TimestamptzTemporal())` (`pg/timestamptz-temporal@1`), a `String` is `field.column(type.String())` (`pg/text@1`), a `Uuid` is `field.column(type.Uuid())` (`pg/uuid@1`). `field.column(columnType)` is the explicit form. A package that offers a fragment and does not import the facade writes `{ codecId: 'pg/text@1', nullable: false }`, with a codec of the contract. For a list field such as `String[]`, add `.many()` to the builder or `many: { elementNullable: false }` to the object; for a `String?[]`, whose elements may be null, add `.many({ elementsNullable: true })` or `many: { elementNullable: true }`. Without it the declaration does not match a list field, and with it the element nullability must match too. A list of value objects such as `Address[]` is stored as one `jsonb` value and is still a list: `field.column(jsonbColumn).many()`. The body may call `where`, `orderBy`, `limit` and `offset`. The result keeps the collection's class and records the filter, so `update` and `delete` are allowed after a fragment that filters. `updateAll`, `deleteAll` and their `AndCount` forms change every matching row and throw `ORM.ARGUMENT_INVALID` when the chain has a `limit`, `offset`, `cursor`, `distinct` or `distinctOn`, so do not put a limit in a fragment that will be followed by one of them. `update` and `delete` change the one row `first()` returns, so the order, offset, cursor, `distinct` and `distinctOn` choose it, and after `limit(0)` they change nothing and return `null`; `update` with a relation callback throws on an order, a limit, an offset, a cursor, `distinct` or `distinctOn`, because it finds its row by the filter alone. A model without the field, or with the field under another codec or nullability, is a compile error, and a run-time `ORM.FIELD_UNKNOWN`. A custom collection class carries no namespace in its type, so at compile time it matches only a field that every model of that name has, with the same codec and nullability, and its real namespace is checked at run time. The codec, the nullability, whether the field is a list and the nullability of its elements are compared; the column type's parameters are not, so `field.column(type.Char(36))` (`char(36)`) also matches a `char(10)` field.
434
+ Pick the builder whose codec matches the field's codec in `contract.d.ts`: a PSL `TimestamptzTemporal` is `field.column(type.TimestamptzTemporal())` (`pg/timestamptz-temporal@1`), a `String` is `field.column(type.String())` (`pg/text@1`), a `Uuid` is `field.column(type.Uuid())` (`pg/uuid@1`). `field.column(columnType)` is the explicit form. A package that offers a fragment and does not import the database package writes `{ codecId: 'pg/text@1', nullable: false }`, with a codec of the contract. For a list field such as `String[]`, add `.many()` to the builder or `many: { elementNullable: false }` to the object; for a `String?[]`, whose elements may be null, add `.many({ elementsNullable: true })` or `many: { elementNullable: true }`. Without it the declaration does not match a list field, and with it the element nullability must match too. A list of value objects such as `Address[]` is stored as one `jsonb` value and is still a list: `field.column(jsonbColumn).many()`. The body may call `where`, `orderBy`, `limit` and `offset`. The result keeps the collection's class and records the filter, so `update` and `delete` are allowed after a fragment that filters. `updateAll`, `deleteAll` and their `AndCount` forms change every matching row and throw `ORM.ARGUMENT_INVALID` when the chain has a `limit`, `offset`, `cursor`, `distinct` or `distinctOn`, so do not put a limit in a fragment that will be followed by one of them. `update` and `delete` change the one row `first()` returns, so the order, offset, cursor, `distinct` and `distinctOn` choose it, and after `limit(0)` they change nothing and return `null`; `update` with a relation callback throws on an order, a limit, an offset, a cursor, `distinct` or `distinctOn`, because it finds its row by the filter alone. A model without the field, or with the field under another codec or nullability, is a compile error, and a run-time `ORM.FIELD_UNKNOWN`. A custom collection class carries no namespace in its type, so at compile time it matches only a field that every model of that name has, with the same codec and nullability, and its real namespace is checked at run time. The codec, the nullability, whether the field is a list and the nullability of its elements are compared; the column type's parameters are not, so `field.column(type.Char(36))` (`char(36)`) also matches a `char(10)` field.
435
435
 
436
436
  For a filter used inside a larger `where`, a plain function of the row works too. Type the field with `CodecField<Contract, CodecId, Nullable>`, the type of any field with that codec:
437
437
 
@@ -683,7 +683,7 @@ const user = await db.orm.public.User.create({ id: 1, email: 'a@x.io' });
683
683
  const authUser = await db.orm.auth.User.create({ id: 2, token: 'tok' });
684
684
  ```
685
685
 
686
- There is no flat `db.sql.user` / `db.orm.User` on the Postgres façade (`Db` is "one facet per storage namespace, and nothing else"); reaching for one is a type error. The flat spelling belongs to SQLite, whose façade exposes its single unbound namespace directly — see `references/queries.md` § *Namespace-aware accessors*.
686
+ There is no flat `db.sql.user` / `db.orm.User` on the Postgres package (`Db` is "one facet per storage namespace, and nothing else"); reaching for one is a type error. The flat spelling belongs to SQLite, whose database package exposes its single unbound namespace directly — see `references/queries.md` § *Namespace-aware accessors*.
687
687
 
688
688
  Cross-namespace relations (e.g. `public.Profile` → `auth.User`) follow the same `.include()` syntax; the ORM resolves the correct schema-qualified join automatically.
689
689
 
@@ -43,7 +43,7 @@ On Postgres, models and tables are **always** addressed by namespace coordinate
43
43
  - **ORM**: `db.orm.<namespace>.<Model>` — e.g. `db.orm.public.User`, `db.orm.auth.User`
44
44
  - **SQL builder**: `db.sql.<namespace>.<table>` — e.g. `db.sql.public.user`, `db.sql.auth.users`
45
45
 
46
- There is no flat `db.orm.User` / `db.sql.user` on the Postgres façade: `db.sql` is one facet per storage namespace and nothing else, and `db.orm` is keyed the same way (`examples/prisma-8-demo` uses `db.orm.public.User` and `db.sql.public.user` throughout). SQLite has no schemas, so its façade exposes the single unbound namespace directly — `db.orm.User` and `db.sql.user` are the SQLite spellings (`examples/prisma-8-demo-sqlite`). Mongo is keyed by collection storage name (`db.orm.users`).
46
+ There is no flat `db.orm.User` / `db.sql.user` on the Postgres package: `db.sql` is one facet per storage namespace and nothing else, and `db.orm` is keyed the same way (`examples/prisma-8-demo` uses `db.orm.public.User` and `db.sql.public.user` throughout). SQLite has no schemas, so its database package exposes the single unbound namespace directly — `db.orm.User` and `db.sql.user` are the SQLite spellings (`examples/prisma-8-demo-sqlite`). Mongo is keyed by collection storage name (`db.orm.users`).
47
47
 
48
48
  See [`queries-postgres.md` § Namespace-aware accessors](./queries-postgres.md#namespace-aware-accessors) for a worked example.
49
49
 
@@ -105,7 +105,7 @@ If you've seen `collect(...)` / `toArray(...)` helpers in a codebase wrapping `.
105
105
 
106
106
  ## Running queries from a short script
107
107
 
108
- When the user is running a one-off `tsx my-script.ts` (not a long-lived server), call `await db.close()` at the end so the process exits cleanly — on Postgres the façade-owned pool keeps Node's event loop alive; on Mongo the façade-owned `MongoClient` does the same. See `references/runtime.md` § *Running as a script (teardown)* for the full pattern including `await using`.
108
+ When the user is running a one-off `tsx my-script.ts` (not a long-lived server), call `await db.close()` at the end so the process exits cleanly — on Postgres the pool the database package owns keeps Node's event loop alive; on Mongo the `MongoClient` it owns does the same. See `references/runtime.md` § *Running as a script (teardown)* for the full pattern including `await using`.
109
109
 
110
110
  ```typescript
111
111
  // src/scripts/seed.ts
@@ -233,9 +233,9 @@ Target-specific pitfalls live in the per-target guides.
233
233
  - **TypedSQL (`.sql` files compiled into typed callables).** Not implemented. For a repeated query, use `db.prepare(...)` (see *Prepared statements* above) or a function that returns the built plan and `db.query(plan)` at the call site. If you want a `.sql`-file compile path, file a feature request via `references/feedback.md`.
234
234
  - **`EXPLAIN` / query-plan inspection.** Prisma 8 does not expose an `.explain()` method. Workaround: connect a `pg.Pool` you control via the runtime's `pg:` binding (see `references/runtime.md`) and issue `EXPLAIN ANALYZE` through it. If you want a first-class plan-inspection surface, file a feature request via `references/feedback.md`.
235
235
  - **Multi-statement batching (Prisma-7-style `db.$transaction([call1, call2])`).** Prisma 8 runs each call sequentially. Workaround: wrap atomically-related work in `db.transaction(async (tx) => { ... })` on Postgres. If you want batch-as-array semantics, file a feature request via `references/feedback.md`.
236
- - **Mongo façade transactions.** `@prisma/orm-mongo/runtime` does not expose `db.transaction(...)`. Multi-document atomicity is not yet wrapped in the Prisma 8 Mongo façade. Workaround: use the MongoDB driver's session API directly if you control the client binding (`mongoClient:` option). File a feature request via `references/feedback.md` if you need a first-class façade surface.
236
+ - **Mongo package transactions.** `@prisma/orm-mongo/runtime` does not expose `db.transaction(...)`. Multi-document atomicity is not yet wrapped in the Prisma 8 Mongo package. Workaround: use the MongoDB driver's session API directly if you control the client binding (`mongoClient:` option). File a feature request via `references/feedback.md` if you need a first-class surface in the database package.
237
237
  - **Mongo ORM aggregates.** No `.aggregate(...)` / `.groupBy(...)` on `db.orm.<root>`. Workaround: express aggregations through `db.query.from(...).group(...).build()` and `runtime.query(plan)`.
238
- - **Mongo filter helpers on the façade.** Rich filters (`.in`, ranges, boolean composition) are filter expressions built with `MongoFieldFilter` and its siblings from `@prisma/orm-mongo/query-ast/execution`, not from `@prisma/orm-mongo/runtime`, and the ORM's `.where(...)` takes no callback. Use object equality `.where({ field: value })` where it is enough.
238
+ - **Mongo filter helpers on the database package.** Rich filters (`.in`, ranges, boolean composition) are filter expressions built with `MongoFieldFilter` and its siblings from `@prisma/orm-mongo/query-ast/execution`, not from `@prisma/orm-mongo/runtime`, and the ORM's `.where(...)` takes no callback. Use object equality `.where({ field: value })` where it is enough.
239
239
  - **Automatic N+1 detection.** Prisma 8 does not warn when an `.include(...)` is missing. Workaround: be deliberate about `.include(...)` in code review; the `lints` middleware (see `references/runtime.md`) catches the more common authoring slips (missing `WHERE` on a `DELETE` / `UPDATE`, missing `LIMIT` on a `SELECT`).
240
240
 
241
241
  ## Reference Files
@@ -251,6 +251,6 @@ This skill is split for selective loading. Target-specific reference paths live
251
251
  - [ ] On Postgres, used `db.orm.<ns>.<Model>` / `db.sql.<ns>.<table>` coordinates (usually `public`) — not a flat `db.orm.User`, which exists only on SQLite.
252
252
  - [ ] Chose the right lane (ORM by default; lower-level builder for shapes the ORM doesn't express).
253
253
  - [ ] Used `.first()` / `.first({ pk })` (Postgres) or `.where({ ... }).first()` (Mongo) for single-row reads — not `.all()`.
254
- - [ ] Consumed `.all()` with plain `await` (not a `collect()` / `toArray()` helper). Used `for await` only when per-row handling is actually wanted — and did not promise it bounds memory on the long-lived façade — and never iterated the same result twice.
254
+ - [ ] Consumed `.all()` with plain `await` (not a `collect()` / `toArray()` helper). Used `for await` only when per-row handling is actually wanted — and did not promise it bounds memory on the long-lived client — and never iterated the same result twice.
255
255
  - [ ] Did NOT use `db.sql` on a Mongo project or `db.query` where the Postgres SQL builder is meant.
256
256
  - [ ] Completed the target-specific checklist in the loaded guide.
@@ -30,9 +30,9 @@ This skill does **not** cover migrating from another ORM (Drizzle, Prisma 6/7, S
30
30
  ## Key Concepts
31
31
 
32
32
  - **Contract**: the data model. Authored as `contract.prisma` (PSL, the canonical surface) or `contract.ts` (TypeScript builder). The framework reads it and emits two artefacts: `contract.json` (runtime IR) and `contract.d.ts` (types).
33
- - **Target**: the backing store. Today: `postgres` or `mongodb`. Picked at `init` time; baked into the `@prisma/orm-<target>` façade the scaffold imports from.
33
+ - **Target**: the backing store. Today: `postgres` or `mongodb`. Picked at `init` time; baked into the `@prisma/orm-<target>` package the scaffold imports from.
34
34
  - **Authoring mode**: how you write the contract. `psl` (Prisma Schema Language, default) or `typescript` (programmatic builder, optionally paired with the Vite plugin for auto-emit during `vite dev` — see `references/build.md`).
35
- - **Façade packages.** The scaffold installs exactly one façade per target — `@prisma/orm-postgres` (or `@prisma/orm-mongo`). User code imports from façade subpaths (`@prisma/orm-postgres/config`, `@prisma/orm-postgres/runtime`, `@prisma/orm-postgres/static`, `@prisma/orm-postgres/contract-builder`). The façade bakes in the family / target / adapter / driver wiring; never reach past it. See `references/contract.md` for the full list.
35
+ - **Database packages.** The scaffold installs one database package per target — `@prisma/orm-postgres` (or `@prisma/orm-mongo`) — and, beside it at the same version, the platform packages the database package names as peer dependencies (`@prisma/orm-framework`, the family, the target, `@prisma/orm-toolchain`). The application lists them so it holds exactly one copy of each: the platform packages recognise a data-type value by which copy made it, and a package manager takes a peer dependency only from the application's own list. A monorepo whose applications are on different Prisma versions can still get two copies under npm workspaces and Bun's hoisted linker; keep such applications on one version, or use pnpm, Yarn or Bun's isolated linker. Installing by hand, name every one of them; `init` writes the list for you, with the other packages the database package needs as required peers, such as `temporal-polyfill`. `prisma orm init` does not support Yarn Plug'n'Play; with Yarn, set `nodeLinker: node-modules` in `.yarnrc.yml` first. User code imports from database package subpaths (`@prisma/orm-postgres/config`, `@prisma/orm-postgres/runtime`, `@prisma/orm-postgres/static`, `@prisma/orm-postgres/contract-builder`). The database package bakes in the family / target / adapter / driver wiring; never reach past it. See `references/contract.md` for the full list.
36
36
  - **`db.ts`**: the runtime entry point. Lives next to the contract source at `src/prisma/db.ts`. Imports the contract artefacts and exports a `db` value the rest of the app uses.
37
37
  - **Marker**: a row in the `prisma_contract.marker` table (Postgres) or a document in the `_prisma_migrations` collection (Mongo) that records the contract hash per contract space. Lets Prisma 8 detect drift between contract and live DB. Created by `db init` (greenfield / first-touch orientation) or `db sign` (brownfield).
38
38
 
@@ -96,7 +96,7 @@ If that prints `[{ id: 1, email: 'alice@example.com' }]`, the project is wired e
96
96
 
97
97
  `db.orm.<ns>.<Model>` is the default ORM lane — model-shaped, fully typed against the contract, lazily connects to the database on first use (it picks up `DATABASE_URL` from `.env` via the runtime's `dotenv/config`-loaded environment). The deeper `references/queries.md` reference covers the rest of the supported surface (filters, joins, transactions, the SQL builder, raw SQL via `db.raw.sql`, prepared statements) when the user is ready — and names the gaps (TypedSQL is not available).
98
98
 
99
- > **SQLite target:** `prisma orm init` scaffolds only `postgres` and `mongodb`; a SQLite project is wired by hand with the `@prisma/orm-sqlite` façade (`references/runtime.md` § *Switch between Postgres, SQLite, and Mongo*; `examples/prisma-8-demo-sqlite`). SQLite has no schemas, so that façade exposes the unbound namespace directly — write `db.orm.User` rather than `db.orm.public.User`.
99
+ > **SQLite target:** `prisma orm init` scaffolds only `postgres` and `mongodb`; a SQLite project is wired by hand with the `@prisma/orm-sqlite` package (`references/runtime.md` § *Switch between Postgres, SQLite, and Mongo*; `examples/prisma-8-demo-sqlite`). SQLite has no schemas, so that database package exposes the unbound namespace directly — write `db.orm.User` rather than `db.orm.public.User`.
100
100
  >
101
101
  > **Mongo target:** the snippet above is SQL-target shape. On `@prisma/orm-mongo`, `db.orm` is keyed by the collection's storage name (`@@map(...)`, or the lowercased model name if no `@@map`), so the same arc reads `await db.orm.users.create(...)` / `await db.orm.users.select('id', 'email').all()` — not `db.orm.public.User`. Full rule and rewrite recipe in `references/queries.md` § *MongoDB ORM addressing*.
102
102
 
@@ -186,7 +186,7 @@ pnpm dlx prisma@latest orm init --yes --target postgres --authoring psl
186
186
 
187
187
  The flags `init` accepts (run `prisma orm init --help` for the source of truth):
188
188
 
189
- - `--target <package>` — `postgres`, `mongodb`, or the name of another target package, such as `@prisma/orm-sqlite`.
189
+ - `--target <package>` — `postgres`, `mongodb`, or the name of another database package, such as `@prisma/orm-sqlite`.
190
190
  - `--authoring <style>` — `psl` or `typescript`.
191
191
  - `--schema-path <path>` — where to write the starter schema. Defaults to `src/prisma/contract.prisma` (or `src/prisma/contract.ts` with `--authoring typescript`), the canonical layout above. The extension must agree with `--authoring` (`CLI.INIT_AUTHORING_SCHEMA_PATH_MISMATCH` otherwise).
192
192
  - `--confirm <directory name>` — grant the reinit consent non-interactively. Re-running init in a scaffolded directory asks you to type the directory name back before it overwrites; non-interactive runs pass the name with this flag instead (`--yes` does not grant it).
@@ -194,7 +194,7 @@ The flags `init` accepts (run `prisma orm init --help` for the source of truth):
194
194
  - `--probe-db` — connect to `DATABASE_URL` once and check the server version against the target's minimum.
195
195
  - `--strict-probe` — fail init if the probe fails (errors without `--probe-db`).
196
196
  - `--skip-install` — skip dependency install + initial contract emit.
197
- - `--keep-previous-facade` — when re-running init to switch targets, keep the previous target package in `package.json`.
197
+ - `--keep-previous-facade` — when re-running init to switch targets, keep the previous database package in `package.json`.
198
198
 
199
199
  `init` does not install agent skills and has no `--skip-skills` flag: the `prisma-8` skill ships inside the `@prisma/orm-*` package the project installs, and the family-level `prisma init` / `prisma skills sync` commands copy it into the agent harness directories.
200
200
 
@@ -10,7 +10,7 @@ This skill covers the **runtime entry point** — `db.ts` — and how to compose
10
10
  - User is wiring up `db.ts` for the first time (post-init).
11
11
  - User wants to add middleware (lints, budgets, cache, custom).
12
12
  - User wants per-environment config (dev vs prod, multi-region).
13
- - User wants to switch between the Postgres, SQLite, and Mongo façades.
13
+ - User wants to switch between the Postgres, SQLite, and Mongo package.
14
14
  - User wants to wrap operations in `db.transaction(...)` (Postgres, SQLite, MySQL, MariaDB and Supabase role-bound clients).
15
15
  - User is running a one-off script (`tsx my-script.ts`, Node CLI, CI task) and the process won't exit after queries finish, or they need script teardown (`db.close()`, `await using`).
16
16
  - User is deploying to a per-request runtime (Cloudflare Workers + Hyperdrive, AWS Lambda, Vercel Edge, Deno Deploy, Bun edge) and needs `postgresServerless()` with `postgres.connect({ url })` per request.
@@ -27,8 +27,8 @@ This skill covers the **runtime entry point** — `db.ts` — and how to compose
27
27
 
28
28
  ## Key Concepts
29
29
 
30
- - **`db.ts` is the runtime entry point.** Imports the runtime factory from the `@prisma/orm-<target>` façade (`@prisma/orm-postgres/runtime`, `@prisma/orm-sqlite/runtime`, or `@prisma/orm-mongo/runtime`), `contractFromJson` from the same façade's `/static` entry point, the contract artefacts (`contract.json` + the `Contract` type from `contract.d.ts`), and any middleware. Exports the typed `contract` and a `db` value the rest of your app imports. On a per-request runtime, `db.ts` imports `postgresServerless` from `@prisma/orm-postgres/serverless` instead and exports the serverless client `postgres`; see *Workflow — Serverless and per-request runtimes*.
31
- - **`db.ts` imports only from the façade's `/runtime` and `/static` entry points.** Each factory is a *default* export. For Postgres: `import postgres from '@prisma/orm-postgres/runtime'`; SQLite: `import sqlite from '@prisma/orm-sqlite/runtime'`; Mongo: `import mongo from '@prisma/orm-mongo/runtime'`. The factory takes one options object and no type argument: it infers the contract type from `contract`. Turn the emitted JSON into a typed value once with `contractFromJson<Contract>(contractJson)` from the façade's `/static` entry point (`@prisma/orm-postgres/static`, `@prisma/orm-sqlite/static`, `@prisma/orm-mongo/static`; Supabase uses the Postgres one). That call is the only place you write the `Contract` type argument. A contract written in TypeScript with `defineContract` is already a typed value and goes to `{ contract }` directly. A contract value is validated once, however many clients use it.
30
+ - **`db.ts` is the runtime entry point.** Imports the runtime factory from the `@prisma/orm-<target>` package (`@prisma/orm-postgres/runtime`, `@prisma/orm-sqlite/runtime`, or `@prisma/orm-mongo/runtime`), `contractFromJson` from the same database package's `/static` entry point, the contract artefacts (`contract.json` + the `Contract` type from `contract.d.ts`), and any middleware. Exports the typed `contract` and a `db` value the rest of your app imports. On a per-request runtime, `db.ts` imports `postgresServerless` from `@prisma/orm-postgres/serverless` instead and exports the serverless client `postgres`; see *Workflow — Serverless and per-request runtimes*.
31
+ - **`db.ts` imports only from the database package's `/runtime` and `/static` entry points.** Each factory is a *default* export. For Postgres: `import postgres from '@prisma/orm-postgres/runtime'`; SQLite: `import sqlite from '@prisma/orm-sqlite/runtime'`; Mongo: `import mongo from '@prisma/orm-mongo/runtime'`. The factory takes one options object and no type argument: it infers the contract type from `contract`. Turn the emitted JSON into a typed value once with `contractFromJson<Contract>(contractJson)` from the database package's `/static` entry point (`@prisma/orm-postgres/static`, `@prisma/orm-sqlite/static`, `@prisma/orm-mongo/static`; Supabase uses the Postgres one). That call is the only place you write the `Contract` type argument. A contract written in TypeScript with `defineContract` is already a typed value and goes to `{ contract }` directly. A contract value is validated once, however many clients use it.
32
32
  - **Lazy connect.** The factory does not connect to the database synchronously. `db.sql` and `db.orm` are available immediately; the driver / pool is instantiated on the first call that needs a runtime (or when you explicitly call `await db.connect({ url })`, which binds the client to that URL), and the pool opens its first database connection on the first query. This is why `db.ts` can be imported in modules that load before the env is ready.
33
33
  - **Middleware composes in order.** Every hook runs in the order of the `middleware: [...]` array — the first middleware's `beforeEncode` sees the statement first, and `intercept.onQuery` handlers are consulted in registration order with the first non-`undefined` result winning. Register a cache first so it gets first claim on a hit. Every middleware's `activityEnded` still fires on a cache hit, with `result.source: 'middleware'`.
34
34
  - **`prisma.config.ts` vs `.env`.** The config (`definePrismaConfig({ orm: ormConfig({ contract, db, extensions, migrations }) })` — see `references/contract.md`) is for static project shape: contract path, installed extensions, migrations directory, default connection string. `.env` is for per-environment values (`DATABASE_URL`, secrets). Nothing reads `.env` on its own: the scaffolded `prisma.config.ts` starts with `import 'dotenv/config'`, and that import is what loads `.env` into `process.env` before the config (and the CLI running it) reads `process.env['DATABASE_URL']`. Keep the import; a config without it sees no `.env` values. Hardcoding `DATABASE_URL` in the config file leaks credentials and bypasses per-env overrides.
@@ -36,7 +36,7 @@ This skill covers the **runtime entry point** — `db.ts` — and how to compose
36
36
 
37
37
  ## Workflow — Basic `db.ts`
38
38
 
39
- The concept: `db.ts` is the seam between the emitted contract artefacts (target-shaped) and the runtime that executes queries against them. Four imports are required — the runtime factory, `contractFromJson` from the façade's `/static` entry point, the `Contract` type (so the static query surfaces are typed), and the JSON artefact (which `contractFromJson` validates once).
39
+ The concept: `db.ts` is the seam between the emitted contract artefacts (target-shaped) and the runtime that executes queries against them. Four imports are required — the runtime factory, `contractFromJson` from the database package's `/static` entry point, the `Contract` type (so the static query surfaces are typed), and the JSON artefact (which `contractFromJson` validates once).
40
40
 
41
41
  `init` scaffolds something like this (for `--target postgres`):
42
42
 
@@ -63,7 +63,7 @@ Three things to know:
63
63
  - **`with { type: 'json' }` is required.** Node's ESM JSON-import-attribute spec. Without it, the import errors.
64
64
  - **`url` is optional at construct time.** If `DATABASE_URL` is not set when `db.ts` loads, the factory still returns a client; you can call `await db.connect({ url })` later. The factory throws lazily — only when a runtime is actually needed.
65
65
 
66
- The Mongo façade has the same construction shape — `import mongo from '@prisma/orm-mongo/runtime'` — and the same `db.connect(...)` / `db.close()` lifecycle methods. **The Mongo façade does not expose `db.transaction(...)`.** See *What Prisma 8 doesn't do yet* for the workaround. **The ORM surface differs in one place: keys.** On Mongo, `db.orm` is keyed by the collection's storage name (from `@@map(...)`, or the lowercased model name if no `@@map` is set), not by the PSL model name — so `model User { … @@map("users") }` is reached at `db.orm.users`, not `db.orm.public.User`. The SQL builder lane (`db.sql.<ns>.<table>`) doesn't exist on Mongo at all (`db.sql` is `undefined`). See `references/queries.md` § *MongoDB ORM addressing* for the full rule and a rewrite recipe for SQL-target examples.
66
+ The Mongo package has the same construction shape — `import mongo from '@prisma/orm-mongo/runtime'` — and the same `db.connect(...)` / `db.close()` lifecycle methods. **The Mongo package does not expose `db.transaction(...)`.** See *What Prisma 8 doesn't do yet* for the workaround. **The ORM surface differs in one place: keys.** On Mongo, `db.orm` is keyed by the collection's storage name (from `@@map(...)`, or the lowercased model name if no `@@map` is set), not by the PSL model name — so `model User { … @@map("users") }` is reached at `db.orm.users`, not `db.orm.public.User`. The SQL builder lane (`db.sql.<ns>.<table>`) doesn't exist on Mongo at all (`db.sql` is `undefined`). See `references/queries.md` § *MongoDB ORM addressing* for the full rule and a rewrite recipe for SQL-target examples.
67
67
 
68
68
  ## Workflow — Running as a script (teardown)
69
69
 
@@ -133,7 +133,7 @@ Servers (HTTP handlers, workers in a request loop) **do not call `db.close()`**
133
133
  - **`close()` is idempotent.** Calling it twice is a no-op.
134
134
  - **`close()` is terminal.** There is no reconnect on a closed `db` — construct a new client if you need to reach the database again. After close, `db.connect(...)`, `db.query(...)`, `db.execute(...)`, `db.transaction(...)`, `db.prepare(...)` and ORM calls reject with `Error('<target> client is closed')` (e.g. `'Postgres client is closed'`, `'SQLite client is closed'`, `'Mongo client is closed'`); none of them throws at the call, so `.catch(...)` sees the error. A mistake in the call itself, such as an ORM query the database's capabilities do not allow, still throws at the call. `db.runtime()` returns a runtime, so on Postgres and SQLite it throws the same error at the call; on MongoDB it returns a promise, which rejects.
135
135
  - **`close()` waits for work already running and refuses new work.** On a Postgres client built from `{ url }`, `close()` refuses every new call at once with `DRIVER.NOT_CONNECTED` ("Postgres client is closed"), and a runtime captured with `db.runtime()` before `close()` is refused at once with "Runtime is closed"; it waits for the queries, transactions and ORM calls already in flight, then ends the pool. An ORM call that resolves to one value, such as `first()`, `create()` or a nested create with its reload, starts when it is called, so `close()` waits for it and it completes. On a serverless connection, `close()` waits until the runtime has been idle for one turn of the event loop, so a chain of queries that keeps it busy from the close onward completes, then ends the `pg.Client`; work that starts after that rejects with `DRIVER.NOT_CONNECTED` ("Runtime is closed"). A lazy result such as `db.orm...all()` or `db.query(plan)` starts when it is awaited or iterated, not when it is built; awaited after `close()`, an ORM `all()` is refused with "Postgres client is closed". A Postgres client given a caller's `pg.Pool` or `pg.Client` does not close its runtime, so work through a runtime taken before `close()` keeps running on the caller's pool. `await` outstanding work before calling `close()`.
136
- - **Ownership.** `close()` releases only what the façade constructed (`pg.Pool` from `{ url }`, `MongoClient` from `{ url }` / `{ uri, dbName }`, SQLite handle from `{ path }`). If you supplied your own `pg.Pool` / `pg.Client` (Postgres `pg:` option), `mongodb.MongoClient` (Mongo `mongoClient:` option), or a pre-built `binding`, `db.close()` does **not** touch those — you own their lifecycle.
136
+ - **Ownership.** `close()` releases only what the database package constructed (`pg.Pool` from `{ url }`, `MongoClient` from `{ url }` / `{ uri, dbName }`, SQLite handle from `{ path }`). If you supplied your own `pg.Pool` / `pg.Client` (Postgres `pg:` option), `mongodb.MongoClient` (Mongo `mongoClient:` option), or a pre-built `binding`, `db.close()` does **not** touch those — you own their lifecycle.
137
137
 
138
138
  **`db.end()` does not exist.** The universal `node-postgres` name is `pool.end()` on a `pg.Pool`; the Prisma 8 runtime client is not a `pg.Pool`. The right call is `await db.close()`.
139
139
 
@@ -215,7 +215,7 @@ A "log every query" middleware is the same shape without the threshold. The runt
215
215
 
216
216
  The concept: lints catch authoring mistakes that survive type-check (e.g. `DELETE` without a `WHERE`, `SELECT` without a `LIMIT` on a large table); budgets enforce row-count and latency ceilings at runtime. Both surface findings through the structured-error envelope so an agent can branch on the code.
217
217
 
218
- Both are exported from the façade's `family-runtime` subpath — `@prisma/orm-postgres/family-runtime` (and `@prisma/orm-sqlite/family-runtime`, `@prisma/orm-mongo/family-runtime`). `examples/prisma-8-demo/src/prisma/db.ts` shows the canonical import.
218
+ Both are exported from the database package's `family-runtime` subpath — `@prisma/orm-postgres/family-runtime` (and `@prisma/orm-sqlite/family-runtime`, `@prisma/orm-mongo/family-runtime`). `examples/prisma-8-demo/src/prisma/db.ts` shows the canonical import.
219
219
 
220
220
  ```typescript
221
221
  import postgres from '@prisma/orm-postgres/runtime';
@@ -292,7 +292,7 @@ await cache.invalidate({ keys: ['user-1'] });
292
292
 
293
293
  **Invalidate after the commit, not inside the transaction.** `invalidateAnnotation` waits for the commit on its own; a manual `invalidate` must be called after it. A read from another request can refill the cache with the old rows before the commit lands. A read that missed before the `invalidate` and finishes after it does not store its rows: the store moves the key's version on `unset`, and the read's `set` is conditional on the version it saw. This holds across processes that share a store.
294
294
 
295
- **The cache key carries no identity.** The default key is a content hash of the statement — contract hash, SQL text, and bound parameters — or, for an ORM call, of the terminal method and the statement it sends first, so two callers issuing the same read share one entry regardless of who they are. Never annotate a read whose rows depend on the caller (per-user, per-tenant, or RLS-filtered data) on the plain `postgres()` façade unless the identity is part of the key: `cacheAnnotation({ key: `user:${userId}:profile` })`, or a `where` clause that binds the identity as a parameter (the parameter is in the hash). Reads that run on a pinned connection or inside a transaction bypass the cache entirely (`ctx.scope !== 'runtime'` or `ctx.inTransaction()`), which is why a Supabase `RoleBoundDb` read — executed on a connection with the role bound via `set_config` — is never served from cache; the plain façade has no such protection.
295
+ **The cache key carries no identity.** The default key is a content hash of the statement — contract hash, SQL text, and bound parameters — or, for an ORM call, of the terminal method and the statement it sends first, so two callers issuing the same read share one entry regardless of who they are. Never annotate a read whose rows depend on the caller (per-user, per-tenant, or RLS-filtered data) on the plain `postgres()` client unless the identity is part of the key: `cacheAnnotation({ key: `user:${userId}:profile` })`, or a `where` clause that binds the identity as a parameter (the parameter is in the hash). Reads that run on a pinned connection or inside a transaction bypass the cache entirely (`ctx.scope !== 'runtime'` or `ctx.inTransaction()`), which is why a Supabase `RoleBoundDb` read — executed on a connection with the role bound via `set_config` — is never served from cache; the plain client has no such protection.
296
296
 
297
297
  ## Workflow — Compose multiple middleware
298
298
 
@@ -358,7 +358,7 @@ export const db = postgres({
358
358
 
359
359
  ## Workflow — Transactions
360
360
 
361
- The concept applies to **Postgres, SQLite, MySQL, MariaDB and Supabase**. `db.transaction(fn)` opens a transaction, passes the callback a `tx`, commits when the callback returns and rolls back when it throws. `tx` offers the client's query members with the same types: `sql`, `orm` (with the client's custom collection classes), `raw`, `prepare`, `query` (rows), `execute` (affected count) and `toSql`. Postgres and serverless-connection transactions also have `enums` and `nativeEnums`; SQLite's, MySQL's and MariaDB's have `enums`. `tx` has no `close`, `[Symbol.asyncDispose]` or `runtime()`. `tx.transaction(async (inner) => ...)` runs a nested transaction in a savepoint on every one of them, and `inner` has the same members as `tx`; see *Workflow — Transactions* in `references/queries-postgres.md`. Inside the callback, send every query through `tx`, not `db`, so it runs inside the transaction. A Supabase role-bound client (`asUser`, `asAnon`, `asServiceRole`) has `transaction(fn)` too, and its `tx` runs every statement under the bound role. The Mongo façade does not expose `db.transaction(...)`.
361
+ The concept applies to **Postgres, SQLite, MySQL, MariaDB and Supabase**. `db.transaction(fn)` opens a transaction, passes the callback a `tx`, commits when the callback returns and rolls back when it throws. `tx` offers the client's query members with the same types: `sql`, `orm` (with the client's custom collection classes), `raw`, `prepare`, `query` (rows), `execute` (affected count) and `toSql`. Postgres and serverless-connection transactions also have `enums` and `nativeEnums`; SQLite's, MySQL's and MariaDB's have `enums`. `tx` has no `close`, `[Symbol.asyncDispose]` or `runtime()`. `tx.transaction(async (inner) => ...)` runs a nested transaction in a savepoint on every one of them, and `inner` has the same members as `tx`; see *Workflow — Transactions* in `references/queries-postgres.md`. Inside the callback, send every query through `tx`, not `db`, so it runs inside the transaction. A Supabase role-bound client (`asUser`, `asAnon`, `asServiceRole`) has `transaction(fn)` too, and its `tx` runs every statement under the bound role. The Mongo package does not expose `db.transaction(...)`.
362
362
 
363
363
  ```typescript
364
364
  await db.transaction(async (tx) => {
@@ -387,7 +387,7 @@ An ORM write of more than one statement on `tx.orm` (or `inner.orm`), such as a
387
387
 
388
388
  ## Workflow — Switch between Postgres, SQLite, and Mongo
389
389
 
390
- The concept: the façade selection is baked into `db.ts` (`@prisma/orm-postgres` or `@prisma/orm-mongo`) and `prisma.config.ts` (which target's `config` subpath `ormConfig` is imported from). To switch a project's target, re-run `prisma orm init` in the same directory and pick the other target — the init flow detects the existing scaffold and prompts to reinit (non-interactive runs grant the consent with `--confirm <directory name>`). Prisma 8 re-scaffolds `prisma.config.ts` and `db.ts` for the new façade. The contract source needs to be re-authored for the new target's idioms (Mongo expresses nested documents; Postgres expresses relations).
390
+ The concept: the choice of database package is baked into `db.ts` (`@prisma/orm-postgres` or `@prisma/orm-mongo`) and `prisma.config.ts` (which target's `config` subpath `ormConfig` is imported from). To switch a project's target, re-run `prisma orm init` in the same directory and pick the other target — the init flow detects the existing scaffold and prompts to reinit (non-interactive runs grant the consent with `--confirm <directory name>`). Prisma 8 re-scaffolds `prisma.config.ts` and `db.ts` for the new database package. The contract source needs to be re-authored for the new target's idioms (Mongo expresses nested documents; Postgres expresses relations).
391
391
 
392
392
  After the switch (Mongo):
393
393
 
@@ -415,7 +415,7 @@ export const contract = contractFromJson<Contract>(contractJson);
415
415
  export const db = sqlite({ contract, path: 'app.db' });
416
416
  ```
417
417
 
418
- `path` is optional at construct time (you can call `db.connect({ path })` later); omit it and the façade still returns a client. The SQLite façade exposes the same `db.sql`, `db.orm`, `db.raw`, `db.prepare(...)`, `db.transaction(...)`, `db.close()`, and `[Symbol.asyncDispose]` surfaces as Postgres, with one addressing difference: SQLite has no schemas, so `db.sql` and `db.orm` are the unbound namespace itself (`db.orm.User`, `db.sql.user`) instead of Postgres's `db.orm.public.User` / `db.sql.public.user`. `db.orm` and `tx.orm` also offer `fragment` beside the models, unless a model is named `fragment`: `const titled = db.orm.fragment({ title: { codecId: 'sqlite/text@1', nullable: false } }, (rows) => rows.where((r) => r.title.eq('Hello')));` then `await db.orm.Post.with(titled).all();`. The Mongo façade shares `db.orm`, `db.close()`, and `[Symbol.asyncDispose]` but has no `db.sql` and no `db.transaction(...)`.
418
+ `path` is optional at construct time (you can call `db.connect({ path })` later); omit it and the database package still returns a client. The SQLite package exposes the same `db.sql`, `db.orm`, `db.raw`, `db.prepare(...)`, `db.transaction(...)`, `db.close()`, and `[Symbol.asyncDispose]` surfaces as Postgres, with one addressing difference: SQLite has no schemas, so `db.sql` and `db.orm` are the unbound namespace itself (`db.orm.User`, `db.sql.user`) instead of Postgres's `db.orm.public.User` / `db.sql.public.user`. `db.orm` and `tx.orm` also offer `fragment` beside the models, unless a model is named `fragment`: `const titled = db.orm.fragment({ title: { codecId: 'sqlite/text@1', nullable: false } }, (rows) => rows.where((r) => r.title.eq('Hello')));` then `await db.orm.Post.with(titled).all();`. The Mongo package shares `db.orm`, `db.close()`, and `[Symbol.asyncDispose]` but has no `db.sql` and no `db.transaction(...)`.
419
419
 
420
420
  The `db.sql` / `db.orm` surfaces stay the same in name; the operators each surface exposes are target-shaped (Mongo has no `JOIN`).
421
421
 
@@ -443,7 +443,7 @@ The runtime side (this skill) is the same regardless: `db.ts` reads `contract.js
443
443
 
444
444
  - **A `/middleware` subpath or a telemetry package.** Neither exists. The middleware surface is `lints`, `budgets`, and the `SqlMiddleware` type on `@prisma/orm-postgres/family-runtime`, plus the separately installed `@prisma/orm-extension-middleware-cache`. Anything else (query log, tracing spans, metrics) is a custom middleware you write on the lifecycle events. File additional gaps you hit via `references/feedback.md`.
445
445
  - **Multi-database routing / read replicas.** Prisma 8 doesn't ship a built-in primary/replica router or shard-aware client. Workaround: configure separate `db.ts` instances per data store and call the right one in your application code. If you need first-class multi-database routing, file a feature request via the `references/feedback.md` skill.
446
- - **Connection pooling as a first-class config field.** `poolOptions.connectionTimeoutMillis`, `poolOptions.idleTimeoutMillis` and `poolOptions.max` are wired through, but the rest of `pg.Pool`'s tuning surface (`allowExitOnIdle`, ssl options, …) is not exposed by name. Workaround: construct the `pg.Pool` yourself and pass it via `pg:`. If you need more pool fields surfaced on the façade, file a feature request via the `references/feedback.md` skill.
446
+ - **Connection pooling as a first-class config field.** `poolOptions.connectionTimeoutMillis`, `poolOptions.idleTimeoutMillis` and `poolOptions.max` are wired through, but the rest of `pg.Pool`'s tuning surface (`allowExitOnIdle`, ssl options, …) is not exposed by name. Workaround: construct the `pg.Pool` yourself and pass it via `pg:`. If you need more pool fields surfaced on the database package, file a feature request via the `references/feedback.md` skill.
447
447
  - **Query logger middleware as a built-in.** Prisma 8 doesn't ship a "log every query" middleware. Workaround: a custom `activityEnded` middleware (see *Workflow — Custom middleware*). If you need a built-in query log, file a feature request via the `references/feedback.md` skill.
448
448
 
449
449
  ## Reference Files
@@ -461,6 +461,6 @@ This skill is intentionally body-only; `prisma orm init --help`, the target `def
461
461
  - [ ] Per-env divergence (if any) gated by `NODE_ENV` or similar.
462
462
  - [ ] Did NOT hardcode credentials in any committed file.
463
463
  - [ ] Did NOT confabulate a `middleware` subpath on the Postgres package, a telemetry middleware package, an audit extension package, or a type argument or `contractJson` option on `postgres(...)`.
464
- - [ ] Did NOT claim `db.transaction(...)` exists on the Mongo façade — only Postgres, SQLite, MySQL, MariaDB and Supabase role-bound clients expose it.
464
+ - [ ] Did NOT claim `db.transaction(...)` exists on the Mongo package — only Postgres, SQLite, MySQL, MariaDB and Supabase role-bound clients expose it.
465
465
  - [ ] Did NOT confabulate read-replica / multi-DB / extra pool config — pointed at *What Prisma 8 doesn't do yet* and routed to `references/feedback.md`.
466
466
  - [ ] For build-system / dev-server prompts (Vite plugin, Next.js plugin, …) routed to `references/build.md`.
@@ -1,6 +1,6 @@
1
1
  # Upgrade Prisma 8 (user app)
2
2
 
3
- This reference upgrades a project that **consumes** Prisma 8 via the public package API (`@prisma/orm-postgres`, `@prisma/orm-mongo`, `@prisma/orm-sqlite`, the contract files in `prisma/`, etc.). Package names below are the published `@prisma/orm-*` names, which is what `package.json`, the lockfile, and the registry use. The other references in this skill use the same names. If the project is itself a Prisma 8 *extension*, use [`upgrade-extension.md`](upgrade-extension.md) instead — or both, if the repo contains both an app and an extension package.
3
+ This reference upgrades a project that **consumes** Prisma 8 via the public package API (a database package, `@prisma/orm-postgres`, `@prisma/orm-mongo`, `@prisma/orm-sqlite`, `@prisma/orm-mysql` or `@prisma/orm-mariadb`, the contract files in `prisma/`, etc.). Package names below are the published `@prisma/orm-*` names, which is what `package.json`, the lockfile, and the registry use. The other references in this skill use the same names. If the project is itself a Prisma 8 *extension*, use [`upgrade-extension.md`](upgrade-extension.md) instead — or both, if the repo contains both an app and an extension package.
4
4
 
5
5
  The per-transition instructions this reference reads live under [`../upgrading/app/upgrades/`](../upgrading/app/upgrades/).
6
6
 
@@ -12,18 +12,21 @@ Do the version bump first (step 1 of the per-step flow below), re-sync the skill
12
12
 
13
13
  ## Pre-flight — extension compatibility
14
14
 
15
- Before changing any code, refuse to upgrade past any installed extension's pinned Prisma 8 version. Extensions in Prisma 8 pin every `@prisma/orm-*` dependency to a single exact version (no carets, no ranges); that pin is the highest version the extension has been validated against. Upgrading the user app past that pin would silently desynchronise the extension's type identity from the app's.
15
+ Before changing any code, work out how far the chain can go. The application can take a step only when every extension published by someone else has a release that names that step's Prisma version. Extensions in Prisma 8 name every `@prisma/orm-*` package they use as a peer dependency at a single exact version (no carets, no ranges); that pin is the one release the extension has been validated against. An application on another release makes the extension's peer dependencies disagree with the app's list until the extension catches up. npm refuses the install when the packages that disagree are ones the application lists itself; pnpm, Yarn and Bun install and print a peer dependency warning, so a successful install does not prove the versions match.
16
+
17
+ This pre-flight is for extensions published by someone else. Every `@prisma/orm-*` package, such as `@prisma/orm-extension-pgvector`, `@prisma/orm-postgres-contrib` or `@prisma/orm-better-auth`, is published from the Prisma repository at every release, at that release's version, so it moves to `<to>` with the database package in the bump step below and does not limit the target.
16
18
 
17
19
  Steps:
18
20
 
19
- 1. **Read `prisma.config.ts`** (or its TS-discoverable equivalent at the project root) and enumerate the list of extension packages it imports. Each `extensions: [...]` entry corresponds to an installed npm package.
20
- 2. **For each extension**, read its installed `package.json` from `node_modules/<extension-package-name>/package.json` and find every `@prisma/orm-*` entry under `dependencies`, `peerDependencies`, or `optionalDependencies` (`@prisma/orm-framework`, `@prisma/orm-family-sql` or `@prisma/orm-family-mongo`, `@prisma/orm-toolchain`, and a `@prisma/orm-target-*` peer). By construction those entries are exact-version pins (e.g. `"8.0.0-rc.11"`), set when the extension author last ran their own upgrade.
21
- 3. **Compute the lowest pinned version across all extensions.** That is the highest Prisma 8 version reachable by this app on its current extension set.
22
- 4. **Compare to the user's target.** If the target exceeds the lowest pin, halt with a structured message naming each lagging extension and its pinned version, and offer two paths:
23
- - (a) Wait for the lagging extension to publish a compatible release, then re-run.
24
- - (b) Re-run with `--to=<highest-reachable>` (or whatever flag/option the user is using to set the target).
21
+ 1. **Read `prisma.config.ts`** (or its TS-discoverable equivalent at the project root) and enumerate the list of extension packages it imports. Each `extensions: [...]` entry corresponds to an installed npm package. Leave out every `@prisma/orm-*` package.
22
+ 2. **For each extension**, read its installed `package.json` from `node_modules/<extension-package-name>/package.json` and find every `@prisma/orm-*` entry under `dependencies`, `peerDependencies`, or `optionalDependencies` (`@prisma/orm-framework`, `@prisma/orm-family-sql` or `@prisma/orm-family-mongo`, `@prisma/orm-toolchain`, and a `@prisma/orm-target-*` package). By construction those entries are exact-version pins (e.g. `"8.0.0-rc.11"`), set when the extension author last ran their own upgrade.
23
+ 3. **Find each extension's releases.** List its published versions (`pnpm view <extension> versions --json`) and, for each, the Prisma version it names (`pnpm view <extension>@<version> peerDependencies`). For each step's `<to>` in the chain below, note the release of each extension that names exactly that version.
24
+ 4. **Find the last step every extension allows.** Walk the chain from the first step. The chain can go as far as the last step before the first one for which some extension has no release. If that is short of the user's target, tell the user before installing anything: which extension has no release for which Prisma version, how far the upgrade can go, and their options:
25
+ - (a) Wait for, or ask for, a release of the extension for that version, then re-run.
26
+ - (b) Upgrade only as far as the last step every extension allows.
27
+ - (c) Remove the extension, and upgrade without it.
25
28
 
26
- Do not auto-downgrade the target; do not skip the lagging extension; do not bump past it. If the user explicitly overrides the halt, surface the risk clearly first.
29
+ Do not skip a step, do not leave an extension at a release that names another Prisma version, and do not install past the last step every extension allows.
27
30
 
28
31
  If `prisma.config.ts` is absent or names no extensions, skip the pre-flight.
29
32
 
@@ -31,14 +34,14 @@ If `prisma.config.ts` is absent or names no extensions, skip the pre-flight.
31
34
 
32
35
  This flow applies when the project **consumes** Prisma 8:
33
36
 
34
- - `package.json` declares `@prisma/orm-postgres`, `@prisma/orm-mongo`, or `@prisma/orm-sqlite` under `dependencies` / `devDependencies`, and
35
- - the package is *not* itself an extension (no `@prisma/orm-framework` or other SPI package under `dependencies`/`peerDependencies`; name does not match `^@.*/extension-`; not referenced from a sibling app's `prisma.config.ts`).
37
+ - `package.json` declares a database package, `@prisma/orm-postgres`, `@prisma/orm-mongo`, `@prisma/orm-sqlite`, `@prisma/orm-mysql` or `@prisma/orm-mariadb`, under `dependencies` / `devDependencies`, and
38
+ - it names no `@prisma/orm-framework` or other platform package under `peerDependencies`: an application lists them under `dependencies` beside its database package. A package that names one as a peer, such as an extension, a library integration or a database package built outside this repository, takes [`upgrade-extension.md`](upgrade-extension.md#role-detection) instead, even when it also lists a database package.
36
39
 
37
- If the project also matches the extension-author role, run **this** flow first and then [`upgrade-extension.md`](upgrade-extension.md) in the same session. If detection is ambiguous, ask the user.
40
+ If the repository also holds an extension, in a `package.json` of its own, run **this** flow for the application first and then [`upgrade-extension.md`](upgrade-extension.md) for the extension, in the same session. If detection is ambiguous, ask the user.
38
41
 
39
42
  ## Version detection
40
43
 
41
- - **From-version.** Read the currently-installed Prisma 8 version from `pnpm-lock.yaml` (or `package-lock.json` / `yarn.lock`) by inspecting the resolved version of the app's Prisma packages: `@prisma/orm-postgres`, `@prisma/orm-mongo`, or `@prisma/orm-sqlite`. Do not read it from a `@prisma/orm-extension-*` package; extensions carry their own version and are handled by the pre-flight above. Compare full semver strings, prerelease identifier included: `8.0.0-rc.10` and `8.0.0-rc.11` are different versions and different steps in the chain below. If the lockfile shows the app's Prisma packages at different versions (already broken), the **lowest** is the from-version.
44
+ - **From-version.** Read the currently-installed Prisma 8 version from `pnpm-lock.yaml` (or `package-lock.json` / `yarn.lock`) by inspecting the resolved version of the app's database package: `@prisma/orm-postgres`, `@prisma/orm-mongo`, `@prisma/orm-sqlite`, `@prisma/orm-mysql` or `@prisma/orm-mariadb`. Do not read it from an extension published by someone else; such an extension carries its own version and is handled by the pre-flight above. Compare full semver strings, prerelease identifier included: `8.0.0-rc.10` and `8.0.0-rc.11` are different versions and different steps in the chain below. If the lockfile shows the app's Prisma packages at different versions (already broken), the **lowest** is the from-version.
42
45
  - **To-version.** Either the version the user specified, or whatever `npm view @prisma/orm-postgres dist-tags.latest` reports. Do not assume that is a stable version: while Prisma 8 is a release candidate, `latest` tracks the newest release, `8.0.0-rc.N` included. If the user wants a stable version specifically, they must name it.
43
46
 
44
47
  Report both back to the user before continuing.
@@ -55,13 +58,13 @@ The [`../upgrading/app/upgrades/`](../upgrading/app/upgrades/) directories name
55
58
 
56
59
  Apply each step in order, fully: bump, install, run instructions, validate, commit — before moving to the next. Halt the chain on the first failed step; do not skip ahead.
57
60
 
58
- The chain order does not depend on which extensions are installed; the pre-flight has already established the target is reachable.
61
+ The chain order does not depend on which extensions are installed; the pre-flight has already worked out how far it can go.
59
62
 
60
63
  ## Per-step flow
61
64
 
62
65
  For each `(from, to)` step in the chain:
63
66
 
64
- 1. **Bump the app's Prisma packages.** Rewrite every `@prisma/orm-postgres`, `@prisma/orm-mongo`, and `@prisma/orm-sqlite` entry in the project's `package.json` to the exact `<to>` version (no caret, no tilde). All entries advance to the same version. Cover `dependencies` and `devDependencies`. Leave `@prisma/orm-extension-*` entries unchanged: each extension pins its own Prisma version, and the pre-flight has already confirmed every installed extension supports `<to>`. The skill itself ships inside the Prisma packages, so bumping them is what updates it; there is no separate skill package to bump.
67
+ 1. **Bump the app's Prisma packages.** Rewrite every `@prisma/orm-*` entry in the project's `package.json` to the exact `<to>` version (no caret, no tilde): the database package, such as `@prisma/orm-postgres`, the platform packages it names as peer dependencies, and every extension or library integration published from the Prisma repository (`@prisma/orm-extension-*`, `@prisma/orm-postgres-contrib`, `@prisma/orm-better-auth`). Each of those is published at every release and names the other Prisma packages at that release's exact version, so one left behind disagrees with the rest. All entries advance to the same version. Cover `dependencies` and `devDependencies`. If the database package at `<to>` names a `@prisma/orm-*` peer dependency the project does not list, add it at `<to>`: the application lists every one, so it holds one copy of each. A monorepo whose applications are on different Prisma versions can still get two copies under npm workspaces and Bun's hoisted linker; keep such applications on one version, or use pnpm, Yarn or Bun's isolated linker. Set each extension published by someone else to its release that names `<to>`, found in the pre-flight. If one has no such release, halt before this step's install: the project stays at the last step that worked, and the user gets the pre-flight's message for that extension and step. The skill itself ships inside the Prisma packages, so bumping them is what updates it; there is no separate skill package to bump.
65
68
 
66
69
  2. **Install.** Run `pnpm install` (or the project's lockfile-managing command). The project's code is now broken against the new types — the upgrade instructions for `<from> → <to>` exist to fix it.
67
70
 
@@ -99,4 +102,4 @@ Report back to the user: the number of steps applied, the SHAs of the commits yo
99
102
 
100
103
  When a step fails: surface a structured error with code `PN-UPGRADE-NNNN`, the failing change's `id`, the file paths touched (or the lockfile, or the validation command), and the inferred remediation. Do not retry automatically; do not auto-roll-back. The user can revert if they want a clean slate.
101
104
 
102
- If a pre-flight halt fires, do not bump anything; the project is left unchanged.
105
+ If the pre-flight finds that the first step is already blocked, do not bump anything; the project is left unchanged. A halt at a later step leaves the project at the last step that worked.
@@ -1,8 +1,8 @@
1
1
  # Upgrade Prisma 8 (extension)
2
2
 
3
- This reference upgrades a project that **is** a Prisma 8 extension — a package that consumes the framework SPI (`@prisma/orm-framework`, `@prisma/orm-family-sql` or `@prisma/orm-family-mongo`, `@prisma/orm-toolchain`, with a `@prisma/orm-target-*` peer) and exposes contract / middleware / codec / migration surfaces that downstream apps install via `prisma.config.ts`.
3
+ This reference upgrades a project that **is** a Prisma 8 extension — a package that consumes the framework SPI (`@prisma/orm-framework`, `@prisma/orm-family-sql` or `@prisma/orm-family-mongo`, `@prisma/orm-toolchain`, `@prisma/orm-target-*`, each a peer dependency) and exposes contract / middleware / codec / migration surfaces that downstream apps install via `prisma.config.ts`.
4
4
 
5
- If the project you are upgrading is a consumer **app** (it depends on `@prisma/orm-postgres`, `@prisma/orm-mongo`, or `@prisma/orm-sqlite` from its application code), use [`upgrade-app.md`](upgrade-app.md) instead — or both, if the repo contains both a consumer app and an extension package, in which case run the app flow first then this one in the same session.
5
+ If the project you are upgrading is a consumer **app** (it depends on a database package, `@prisma/orm-postgres`, `@prisma/orm-mongo`, `@prisma/orm-sqlite`, `@prisma/orm-mysql` or `@prisma/orm-mariadb`, from its application code), use [`upgrade-app.md`](upgrade-app.md) instead — or both, if the repo contains both a consumer app and an extension package, in which case run the app flow first then this one in the same session.
6
6
 
7
7
  The per-transition instructions this reference reads live under [`../upgrading/extension/upgrades/`](../upgrading/extension/upgrades/).
8
8
 
@@ -14,19 +14,20 @@ Do the version bump first (step 1 of the per-step flow below), re-sync the skill
14
14
 
15
15
  ## Role detection
16
16
 
17
- This flow applies when the project **is** a Prisma 8 extension. Heuristics:
17
+ This flow applies when the project **is** a Prisma 8 extension, a library integration such as `@prisma/orm-better-auth`, or a database package built outside this repository ([`build-a-target-package.md`](build-a-target-package.md)). It is one when either holds:
18
18
 
19
- - `package.json` declares `@prisma/orm-framework` (or another `@prisma/orm-*` SPI package) under `dependencies` or `peerDependencies`, and
20
- - the package's `name` matches `^@.*/extension-` (the convention used by `@prisma/orm-extension-pgvector`, etc.), or
21
- - the package is referenced as an `extensions` entry from a sibling app's `prisma.config.ts` in the same monorepo.
19
+ - `package.json` declares `@prisma/orm-framework` or another `@prisma/orm-*` platform package under `peerDependencies`, whatever else it declares (`@prisma/orm-extension-supabase` also names `@prisma/orm-postgres` as a peer, and is an extension); or
20
+ - it declares a platform package under `dependencies` with no database package (`@prisma/orm-postgres`, `@prisma/orm-mongo`, …) beside it, as an extension written for an earlier release does, and its `name` matches `^@.*/extension-` (the convention used by `@prisma/orm-extension-pgvector`, etc.), its `keywords` include `prisma-orm-extension`, or a sibling app's `prisma.config.ts` in the same monorepo lists it as an `extensions` entry.
22
21
 
23
- If the project additionally consumes Prisma 8 from its own app code, run [`upgrade-app.md`](upgrade-app.md) first, then this flow in the same session.
22
+ An application never names a platform package as a peer, so a package that does is never an application.
23
+
24
+ If the repository also holds an application, in a `package.json` of its own, run [`upgrade-app.md`](upgrade-app.md) for it first, then this flow for the extension, in the same session.
24
25
 
25
26
  If detection is ambiguous, ask the user which role to operate under.
26
27
 
27
28
  ## Version detection
28
29
 
29
- - **From-version.** Read the currently-installed Prisma 8 version from `pnpm-lock.yaml` (or `package-lock.json` / `yarn.lock`) by inspecting the resolved version of any `@prisma/orm-*` SPI package (`@prisma/orm-framework`, `@prisma/orm-family-*`, `@prisma/orm-target-*`, `@prisma/orm-toolchain`). Do not read it from a `@prisma/orm-extension-*` dependency; another extension carries its own version. Compare full semver strings, prerelease identifier included: `8.0.0-rc.10` and `8.0.0-rc.11` are different versions and different steps in the chain below. If the lockfile shows the SPI packages at different versions, the lowest is the from-version.
30
+ - **From-version.** Read the currently-installed Prisma 8 version from `pnpm-lock.yaml` (or `package-lock.json` / `yarn.lock`) by inspecting the resolved version of any `@prisma/orm-*` platform package (`@prisma/orm-framework`, `@prisma/orm-family-*`, `@prisma/orm-target-*`, `@prisma/orm-toolchain`). Do not read it from an extension published by someone else; it carries its own version. Compare full semver strings, prerelease identifier included: `8.0.0-rc.10` and `8.0.0-rc.11` are different versions and different steps in the chain below. If the lockfile shows the platform packages at different versions, the lowest is the from-version.
30
31
  - **To-version.** Either the version the user specified, or whatever `npm view @prisma/orm-framework dist-tags.latest` reports. Do not assume that is a stable version: while Prisma 8 is a release candidate, `latest` tracks the newest release, `8.0.0-rc.N` included. If the user wants a stable version specifically, they must name it.
31
32
 
32
33
  Report both back to the user before continuing.
@@ -49,14 +50,14 @@ This flow assumes you are an **external extension author** — your extension li
49
50
 
50
51
  For each `(from, to)` step in the chain:
51
52
 
52
- 1. **Bump `@prisma/orm-*` deps.** Rewrite every `@prisma/orm-*` entry other than `@prisma/orm-extension-*` in the extension's `package.json` to the exact `<to>` version (e.g. `"8.0.0-rc.11"` — no caret, no tilde, no range, no `workspace:` specifier; the exact-pin rule below details why). All entries advance to the same version. Cover whichever dep field(s) the extension uses today — `dependencies` and/or `peerDependencies` — and any `optionalDependencies`. The skill itself ships inside the Prisma packages, so bumping them is what updates it; there is no separate skill package to bump.
53
+ 1. **Bump `@prisma/orm-*` deps.** Rewrite every `@prisma/orm-*` entry in the extension's `package.json` to the exact `<to>` version, another extension published from the Prisma repository such as `@prisma/orm-extension-pgvector` included: every `@prisma/orm-*` package is published at every release and names the others at that release's version (e.g. `"8.0.0-rc.11"` — no caret, no tilde, no range, no `workspace:` specifier; the exact-pin rule below details why). All entries advance to the same version. Every such package the extension's shipped code imports belongs under `peerDependencies` and again under `devDependencies`, at the same version. One that only the extension's tests use, such as a database package the tests run against, belongs under `devDependencies` alone, at the same version. Move any entry still under `dependencies` or `optionalDependencies` there: an extension written for an earlier release held the framework, the family and the toolchain as ordinary dependencies. The skill itself ships inside the Prisma packages, so bumping them is what updates it; there is no separate skill package to bump.
53
54
 
54
55
  2. **Install.** Run `pnpm install` (or the project's lockfile-managing command). The extension's source is now broken against the new SPI — the upgrade instructions for `<from> → <to>` exist to fix it.
55
56
 
56
- 3. **Check pins.** Every `@prisma/orm-*` entry other than `@prisma/orm-extension-*` across `dependencies`, `peerDependencies`, and `optionalDependencies` must now be the single exact string `<to>`. This prints any entry that is not, and exits 1:
57
+ 3. **Check pins.** Every `@prisma/orm-*` entry under `peerDependencies` or `devDependencies` must now be the single exact string `<to>`, every such peer must also be under `devDependencies`, and none may be under `dependencies` or `optionalDependencies`. A development dependency with no peer entry is one only the tests use, and passes. This prints any entry that breaks the rule, and exits 1:
57
58
 
58
59
  ```bash
59
- node -e 'const p=require("./package.json");const to=process.argv[1];const bad=[];for(const f of ["dependencies","peerDependencies","optionalDependencies"])for(const [n,v] of Object.entries(p[f]??{}))if(n.startsWith("@prisma/orm-")&&!n.startsWith("@prisma/orm-extension-")&&v!==to)bad.push(f+": "+n+"@"+v);if(bad.length){console.error(bad.join("\n"));process.exit(1)}' <to>
60
+ node -e 'const p=require("./package.json");const to=process.argv[1];const ours=(n)=>n.startsWith("@prisma/orm-");const bad=[];for(const f of ["dependencies","optionalDependencies"])for(const n of Object.keys(p[f]??{}))if(ours(n))bad.push(f+": "+n+" belongs in peerDependencies, or in devDependencies alone if only tests use it");for(const f of ["peerDependencies","devDependencies"])for(const [n,v] of Object.entries(p[f]??{}))if(ours(n)&&v!==to)bad.push(f+": "+n+"@"+v);for(const n of Object.keys(p.peerDependencies??{}))if(ours(n)&&!(n in (p.devDependencies??{})))bad.push("devDependencies: "+n+" is missing");if(bad.length){console.error(bad.join("\n"));process.exit(1)}' <to>
60
61
  ```
61
62
 
62
63
  If it fails, the bump step did not rewrite every spec — fix the offending entries and re-run before proceeding.
@@ -89,9 +90,9 @@ Move on to the next step. Repeat.
89
90
 
90
91
  ## Exact-pin rule
91
92
 
92
- Prisma 8 extensions pin every `@prisma/orm-*` SPI dependency (everything except `@prisma/orm-extension-*`) to a single **exact** version (no `^`, no `~`, no range, no wildcard, no `workspace:` specifier in the published `package.json`). All of those entries share the same version. The pin advances after each successful upgrade step, release-candidate steps included.
93
+ A Prisma 8 extension names every `@prisma/orm-*` package its shipped code uses, another extension published from the Prisma repository included, as a **peer dependency** at a single **exact** version (no `^`, no `~`, no range, no wildcard, no `workspace:` specifier in the published `package.json`), and lists the same packages under `devDependencies` at that version, so its own build and tests install them. A package of ours that only its tests use is a development dependency alone, at that version. None of them is an ordinary dependency. All of those entries share the same version. The pin advances after each successful upgrade step, release-candidate steps included.
93
94
 
94
- The version is the one the application's database package (`@prisma/orm-postgres`, `@prisma/orm-mongo`, …) uses. Values and registries made by one copy of Prisma ORM are not recognised by another, so they must never cross between copies. A host may load two copies on purpose, as Prisma Composer's boot wrapper does beside the application bundle, but the application, its extensions and the `prisma` CLI must share one. When an extension pins a different version, the package manager installs a second copy beside the application's, and the extension's values then cross between copies. The target package (such as `@prisma/orm-target-postgres`) is therefore a **peer dependency**, so npm refuses a mismatched install instead of adding a copy. The framework and family packages are ordinary dependencies at the same version. pnpm and bun only warn about a mismatched peer, so a second copy can still be installed. `npm ls @prisma/orm-framework`, `pnpm why @prisma/orm-framework` or `bun why @prisma/orm-framework` lists every copy and the package that brought it.
95
+ The version is the one the application's database package (`@prisma/orm-postgres`, `@prisma/orm-mongo`, …) uses. The platform packages recognise a data-type value by which copy made it, so one made by one copy of Prisma ORM is refused by another, and values must never cross between copies. A host may load two copies on purpose, as Prisma Composer's boot wrapper does beside the application bundle, but the application, its extensions and the `prisma` CLI must share one. A package manager gives a package its own copy of an ordinary dependency whenever the version differs from the one already installed, but it never gives a package its own copy of a peer dependency: it uses the copy the application lists. So when every Prisma package an extension uses is a peer, the application's list is the only place a copy can come from, and a version that does not match is reported at install instead of becoming a second copy. When the packages that disagree are ones the application lists itself, npm refuses the install, and pnpm, Yarn and Bun install and print a peer dependency warning. A successful install does not prove the versions match, so read the peer warnings it prints. That holds within one application. A monorepo whose applications are on different Prisma versions can still get two copies under npm workspaces and Bun's hoisted linker; keep such applications on one version, or use pnpm, Yarn or Bun's isolated linker. The application lists the platform packages beside its database package for the same reason. The decision record explains this in full: [ADR 329](https://github.com/prisma/orm/blob/main/docs/architecture%20docs/adrs/ADR%20329%20-%20An%20application%20lists%20the%20platform%20packages%20and%20our%20packages%20name%20each%20other%20as%20peers.md). `npm ls @prisma/orm-framework`, `pnpm why @prisma/orm-framework` or `bun why @prisma/orm-framework` lists every copy and the package that brought it.
95
96
 
96
97
  The one-line check in step 3 of the per-step flow enforces the rule; the `prisma-8-check-pins` guard the monorepo uses for its own extensions is not published. Wire the check into the extension's CI alongside the build/test step so an accidental range pin fails the PR before it lands.
97
98
 
@@ -504,7 +504,7 @@ const config: PrismaConfig<'sql', 'postgres'> = defineConfig({ /* ... */ });
504
504
  ```
505
505
 
506
506
 
507
- ## Generated files import from the module the target package names
507
+ ## Generated files import from the module the facade names
508
508
 
509
509
  The target package an application's `prisma.config.ts` imports, such as `@prisma/orm-postgres`, now tells Prisma which modules generated files import from. The CLI no longer reads the application's `package.json` to work that out.
510
510
 
@@ -118,7 +118,7 @@ changes:
118
118
  - '(?<![\s\S])(?=[\s\S]*@(?:prisma/orm-family-sql|internal/sql-contract-ts)/(?:contract-ts/)?config-types)[\s\S]*\btypescriptContractFromPath\b'
119
119
  - id: target-package-exports-an-init-contribution
120
120
  summary: |
121
- `prisma orm init` takes everything about a target from the target package: a package that wants `init` to set up a project on it exports an init contribution, typed `InitContribution` from `@prisma/orm-toolchain/cli/init-contribution`, as the default export of its `init` entrypoint. `@prisma/orm-postgres`, `@prisma/orm-mongo`, `@prisma/orm-sqlite` and `@prisma/orm-mysql` export one. A package without it is not affected; `init` cannot set up a project on it, and the application writes `prisma.config.ts` by hand.
121
+ `prisma orm init` takes everything about a database from its facade: a package that wants `init` to set up a project on it exports an init contribution, typed `InitContribution` from `@prisma/orm-toolchain/cli/init-contribution`, as the default export of its `init` entrypoint. `@prisma/orm-postgres`, `@prisma/orm-mongo`, `@prisma/orm-sqlite` and `@prisma/orm-mysql` export one. A package without it is not affected; `init` cannot set up a project on it, and the application writes `prisma.config.ts` by hand.
122
122
  - id: init-reaches-a-target-package-by-name
123
123
  summary: |
124
124
  `prisma orm init --target <package name>` sets up a project on any target package that exports an init contribution from its `init` entrypoint. The package needs no entry in any list of Prisma's, and must list the `prisma-orm-extension` keyword. A package without an `init` entrypoint is not affected.
@@ -1 +0,0 @@
1
- {"version":3,"file":"mongo-static-DU3UYNCF-BrYN5Wtc.mjs","names":[],"sources":["../../../../3-targets/mongo/9-facade/dist/mongo-static-DU3UYNCF.mjs"],"sourcesContent":["import mongoRuntimeAdapter from \"@internal/adapter-mongo/runtime\";\nimport { mongoRaw } from \"@internal/mongo-orm\";\nimport { createMongoExecutionContext, createMongoExecutionStack, enumMemberCodecFor } from \"@internal/mongo-runtime\";\nimport mongoRuntimeTarget from \"@internal/target-mongo/runtime\";\nimport { validateContractOnce } from \"@internal/contract/validate-once\";\nimport { MongoContractSerializer } from \"@internal/family-mongo/ir\";\nimport { buildNamespacedEnums } from \"@internal/contract/enum-accessor\";\nimport { UNBOUND_NAMESPACE_ID } from \"@internal/framework-components/ir\";\nimport { mongoQuery } from \"@internal/mongo-query-builder\";\nimport { assertDefined } from \"@internal/utils/assertions\";\n//#region package.json\nvar version = \"8.0.0-rc.25-dev.9\";\n//#endregion\n//#region src/static/contract-from-json.ts\nconst serializer = new MongoContractSerializer();\nconst validator = `${mongoRuntimeTarget.targetId}@${version}`;\n/**\n* Validates an emitted Mongo `contract.json` and returns it as the contract type the application\n* names, ready to pass to `mongo({ contract })` and `mongoStatic({ contract })`. Clients built from\n* the result do not validate it again.\n*\n* The returned value's top level is frozen; its nested objects are not. Do not change `json` or the\n* returned value after the call: clients built from the value later do not validate it again.\n*\n* @example\n* ```ts\n* import type { Contract } from './contract.d';\n* import contractJson from './contract.json' with { type: 'json' };\n*\n* export const contract = contractFromJson<Contract>(contractJson);\n* ```\n*/\nfunction contractFromJson(json) {\n\treturn validateContractOnce(json, validator, (input) => serializer.deserializeContract(input));\n}\nfunction validateMongoContract(contract) {\n\treturn contractFromJson(contract);\n}\n//#endregion\n//#region src/static/mongo-static.ts\nfunction buildMongoStaticContext(contract, stack) {\n\tconst context = createMongoExecutionContext({\n\t\tcontract,\n\t\tstack\n\t});\n\tconst enums = Object.freeze(buildNamespacedEnums(context.contract.domain, enumMemberCodecFor(context.codecs)))[UNBOUND_NAMESPACE_ID];\n\tassertDefined(enums, \"the unbound namespace always exists on a mongo builder output\");\n\treturn {\n\t\tcontext,\n\t\tcontract,\n\t\tenums,\n\t\tquery: mongoQuery({ context }),\n\t\traw: mongoRaw({ context })\n\t};\n}\n/**\n* The query surfaces of a Mongo client without a driver: `query`, `raw` and `enums`. Use it where\n* loading `mongodb` is not wanted.\n*\n* @example\n* ```ts\n* const { enums } = mongoStatic({ contract: contractFromJson<Contract>(contractJson) });\n* ```\n*/\nfunction mongoStatic(options) {\n\tconst stack = createMongoExecutionStack({\n\t\ttarget: mongoRuntimeTarget,\n\t\tadapter: mongoRuntimeAdapter,\n\t\textensions: options.extensions ?? []\n\t});\n\treturn buildMongoStaticContext(validateMongoContract(options.contract), stack);\n}\n//#endregion\nexport { validateMongoContract as i, mongoStatic as n, contractFromJson as r, buildMongoStaticContext as t };\n\n//# sourceMappingURL=mongo-static-DU3UYNCF.mjs.map"],"mappings":";;;;;;;;;;;AAWA,IAAI,UAAU;AAGd,MAAM,aAAa,IAAI,wBAAwB;AAC/C,MAAM,YAAY,GAAG,mBAAmB,SAAS,GAAG;;;;;;;;;;;;;;;;;AAiBpD,SAAS,iBAAiB,MAAM;CAC/B,OAAO,qBAAqB,MAAM,YAAY,UAAU,WAAW,oBAAoB,KAAK,CAAC;AAC9F;AACA,SAAS,sBAAsB,UAAU;CACxC,OAAO,iBAAiB,QAAQ;AACjC;AAGA,SAAS,wBAAwB,UAAU,OAAO;CACjD,MAAM,UAAU,4BAA4B;EAC3C;EACA;CACD,CAAC;CACD,MAAM,QAAQ,OAAO,OAAO,qBAAqB,QAAQ,SAAS,QAAQ,mBAAmB,QAAQ,MAAM,CAAC,CAAC,CAAC,CAAC;CAC/G,cAAc,OAAO,+DAA+D;CACpF,OAAO;EACN;EACA;EACA;EACA,OAAO,WAAW,EAAE,QAAQ,CAAC;EAC7B,KAAK,SAAS,EAAE,QAAQ,CAAC;CAC1B;AACD;;;;;;;;;;AAUA,SAAS,YAAY,SAAS;CAC7B,MAAM,QAAQ,0BAA0B;EACvC,QAAQ;EACR,SAAS;EACT,YAAY,QAAQ,cAAc,CAAC;CACpC,CAAC;CACD,OAAO,wBAAwB,sBAAsB,QAAQ,QAAQ,GAAG,KAAK;AAC9E"}