@prisma/orm-mongo 8.0.1-dev.22 → 8.0.1-dev.24
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/dist/{mongo-static-CVBuNpha-Ar3Aibi1.mjs → mongo-static-DtMqhSMp-BCVaL9FE.mjs} +3 -3
- package/dist/{mongo-static-CVBuNpha-Ar3Aibi1.mjs.map → mongo-static-DtMqhSMp-BCVaL9FE.mjs.map} +1 -1
- package/dist/runtime.mjs +1 -1
- package/dist/runtime.mjs.map +1 -1
- package/dist/static.mjs +1 -1
- package/package.json +12 -12
- package/skills/prisma-8/SKILL.md +5 -5
- package/skills/prisma-8/references/debug.md +10 -10
- package/skills/prisma-8/references/migration-model.md +12 -12
- package/skills/prisma-8/references/migration-review.md +20 -20
- package/skills/prisma-8/references/migrations.md +39 -39
- package/skills/prisma-8/references/quickstart.md +11 -11
- package/skills/prisma-8/references/runtime.md +2 -2
|
@@ -9,8 +9,8 @@ import { buildNamespacedEnums } from "@prisma/orm-framework/contract/enum-access
|
|
|
9
9
|
import { UNBOUND_NAMESPACE_ID } from "@prisma/orm-framework/components/ir";
|
|
10
10
|
import { mongoQuery } from "@prisma/orm-family-mongo/query-builder";
|
|
11
11
|
import { assertDefined } from "@prisma/orm-framework/utils/assertions";
|
|
12
|
-
//#region ../../../3-targets/mongo/9-facade/dist/mongo-static-
|
|
13
|
-
var version = "8.0.1-dev.
|
|
12
|
+
//#region ../../../3-targets/mongo/9-facade/dist/mongo-static-DtMqhSMp.mjs
|
|
13
|
+
var version = "8.0.1-dev.24";
|
|
14
14
|
const serializer = new MongoContractSerializer();
|
|
15
15
|
const validator = `${mongoRuntimeTarget.targetId}@${version}`;
|
|
16
16
|
/**
|
|
@@ -71,4 +71,4 @@ function mongoStatic(options) {
|
|
|
71
71
|
//#endregion
|
|
72
72
|
export { validateMongoContract as i, contractFromJson as n, mongoStatic as r, buildMongoStaticContext as t };
|
|
73
73
|
|
|
74
|
-
//# sourceMappingURL=mongo-static-
|
|
74
|
+
//# sourceMappingURL=mongo-static-DtMqhSMp-BCVaL9FE.mjs.map
|
package/dist/{mongo-static-CVBuNpha-Ar3Aibi1.mjs.map → mongo-static-DtMqhSMp-BCVaL9FE.mjs.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mongo-static-
|
|
1
|
+
{"version":3,"file":"mongo-static-DtMqhSMp-BCVaL9FE.mjs","names":[],"sources":["../../../../3-targets/mongo/9-facade/dist/mongo-static-DtMqhSMp.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 { isContractBuiltInMemory } from \"@internal/contract/stored-format\";\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.1-dev.24\";\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}\n/** Validates a contract value for a Mongo client, once per value. */\nfunction validateMongoContract(contract) {\n\treturn validateContractOnce(contract, validator, () => serializer.deserializeContract(isContractBuiltInMemory(contract) ? serializer.serializeContract(contract) : 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-DtMqhSMp.mjs.map"],"mappings":";;;;;;;;;;;;AAYA,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;;AAEA,SAAS,sBAAsB,UAAU;CACxC,OAAO,qBAAqB,UAAU,iBAAiB,WAAW,oBAAoB,wBAAwB,QAAQ,IAAI,WAAW,kBAAkB,QAAQ,IAAI,QAAQ,CAAC;AAC7K;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-
|
|
1
|
+
import { i as validateMongoContract, t as buildMongoStaticContext } from "./mongo-static-DtMqhSMp-BCVaL9FE.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";
|
package/dist/runtime.mjs.map
CHANGED
|
@@ -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-CVBuNpha.mjs\";\nimport { ifDefined } from \"@internal/utils/defined\";\nimport { isStructuredError, structuredError } from \"@internal/utils/structured-error\";\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 { InvariantError } from \"@internal/utils/invariant-error\";\nimport { ConnectionString } from \"mongodb-connection-string-url\";\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 InvariantError(\"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 InvariantError(\"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\t...ifDefined(\"log\", options.log)\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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;IACR,OAAO;IACP,SAAS;GACV;EACD,CAAC;EACD;EACA;EACA;EACA;EACA;EACA,MAAM,QAAQ,cAAc;GAC3B,IAAI,QAAQ,MAAM,YAAY;GAC9B,IAAI,mBAAmB,KAAK,GAAG;IAC9B,IAAI,iBAAiB,KAAK,GAAG,MAAM,WAAW,4BAA4B,iCAAiC;KAC1G,KAAK;KACL,KAAK;IACN,CAAC;IACD,MAAM,UAAU,MAAM;IACtB,IAAI,QAAQ,MAAM,YAAY;IAC9B,OAAO;GACR;GACA,IAAI,iBAAiB,KAAK,GAAG,UAAU,oBAAoB,YAAY;GACvE,IAAI,YAAY,KAAK,GAAG,MAAM,WAAW,2BAA2B,yHAAyH;GAC7L,MAAM,UAAU,MAAM,WAAW;GACjC,IAAI,QAAQ,MAAM,YAAY;GAC9B,OAAO;EACR;EACA,UAAU;GACT,OAAO,WAAW;EACnB;EACA,MAAM,QAAQ,aAAa,UAAU;GACpC,IAAI,QAAQ,MAAM,YAAY;GAC9B,OAAO,kBAAkB,cAAc,CAAC,CAAC,SAAS,aAAa,QAAQ;EACxE;EACA,MAAM,QAAQ;GACb,IAAI,QAAQ;GACZ,SAAS;GACT,MAAM,gBAAgB,YAAY,KAAK,CAAC;GACxC,MAAM,iBAAiB,QAAQ,MAAM;EACtC;EACA,CAAC,OAAO,gBAAgB;GACvB,OAAO,KAAK,MAAM;EACnB;CACD;AACD"}
|
|
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-DtMqhSMp.mjs\";\nimport { ifDefined } from \"@internal/utils/defined\";\nimport { isStructuredError, structuredError } from \"@internal/utils/structured-error\";\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 { InvariantError } from \"@internal/utils/invariant-error\";\nimport { ConnectionString } from \"mongodb-connection-string-url\";\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 InvariantError(\"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 InvariantError(\"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\t...ifDefined(\"log\", options.log)\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, isStructuredError };\n\n//# sourceMappingURL=runtime.mjs.map"],"mappings":";;;;;;;;;;;;;AAaA,SAAS,WAAW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GAC9B,IAAI,mBAAmB,KAAK,GAAG;IAC9B,IAAI,iBAAiB,KAAK,GAAG,MAAM,WAAW,4BAA4B,iCAAiC;KAC1G,KAAK;KACL,KAAK;IACN,CAAC;IACD,MAAM,UAAU,MAAM;IACtB,IAAI,QAAQ,MAAM,YAAY;IAC9B,OAAO;GACR;GACA,IAAI,iBAAiB,KAAK,GAAG,UAAU,oBAAoB,YAAY;GACvE,IAAI,YAAY,KAAK,GAAG,MAAM,WAAW,2BAA2B,yHAAyH;GAC7L,MAAM,UAAU,MAAM,WAAW;GACjC,IAAI,QAAQ,MAAM,YAAY;GAC9B,OAAO;EACR;EACA,UAAU;GACT,OAAO,WAAW;EACnB;EACA,MAAM,QAAQ,aAAa,UAAU;GACpC,IAAI,QAAQ,MAAM,YAAY;GAC9B,OAAO,kBAAkB,cAAc,CAAC,CAAC,SAAS,aAAa,QAAQ;EACxE;EACA,MAAM,QAAQ;GACb,IAAI,QAAQ;GACZ,SAAS;GACT,MAAM,gBAAgB,YAAY,KAAK,CAAC;GACxC,MAAM,iBAAiB,QAAQ,MAAM;EACtC;EACA,CAAC,OAAO,gBAAgB;GACvB,OAAO,KAAK,MAAM;EACnB;CACD;AACD"}
|
package/dist/static.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as contractFromJson, r as mongoStatic } from "./mongo-static-
|
|
1
|
+
import { n as contractFromJson, r as mongoStatic } from "./mongo-static-DtMqhSMp-BCVaL9FE.mjs";
|
|
2
2
|
export { contractFromJson, mongoStatic as default };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prisma/orm-mongo",
|
|
3
|
-
"version": "8.0.1-dev.
|
|
3
|
+
"version": "8.0.1-dev.24",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -19,21 +19,21 @@
|
|
|
19
19
|
"temporal-spec": "1.0.1"
|
|
20
20
|
},
|
|
21
21
|
"devDependencies": {
|
|
22
|
-
"@internal/mongo": "8.0.1-dev.
|
|
23
|
-
"@prisma/orm-family-mongo": "8.0.1-dev.
|
|
24
|
-
"@prisma/orm-framework": "8.0.1-dev.
|
|
25
|
-
"@prisma/orm-target-mongo": "8.0.1-dev.
|
|
26
|
-
"@prisma/orm-toolchain": "8.0.1-dev.
|
|
27
|
-
"@repo/tsconfig": "8.0.1-dev.
|
|
28
|
-
"@repo/tsdown": "8.0.1-dev.
|
|
22
|
+
"@internal/mongo": "8.0.1-dev.24",
|
|
23
|
+
"@prisma/orm-family-mongo": "8.0.1-dev.24",
|
|
24
|
+
"@prisma/orm-framework": "8.0.1-dev.24",
|
|
25
|
+
"@prisma/orm-target-mongo": "8.0.1-dev.24",
|
|
26
|
+
"@prisma/orm-toolchain": "8.0.1-dev.24",
|
|
27
|
+
"@repo/tsconfig": "8.0.1-dev.24",
|
|
28
|
+
"@repo/tsdown": "8.0.1-dev.24",
|
|
29
29
|
"tsdown": "0.22.14",
|
|
30
30
|
"typescript": "5.9.3"
|
|
31
31
|
},
|
|
32
32
|
"peerDependencies": {
|
|
33
|
-
"@prisma/orm-family-mongo": "8.0.1-dev.
|
|
34
|
-
"@prisma/orm-framework": "8.0.1-dev.
|
|
35
|
-
"@prisma/orm-target-mongo": "8.0.1-dev.
|
|
36
|
-
"@prisma/orm-toolchain": "8.0.1-dev.
|
|
33
|
+
"@prisma/orm-family-mongo": "8.0.1-dev.24",
|
|
34
|
+
"@prisma/orm-framework": "8.0.1-dev.24",
|
|
35
|
+
"@prisma/orm-target-mongo": "8.0.1-dev.24",
|
|
36
|
+
"@prisma/orm-toolchain": "8.0.1-dev.24",
|
|
37
37
|
"mongodb": "^7.0.0",
|
|
38
38
|
"temporal-polyfill": "^1.0.8",
|
|
39
39
|
"typescript": ">=5.9"
|
package/skills/prisma-8/SKILL.md
CHANGED
|
@@ -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.1-dev.
|
|
18
|
+
library_version: '8.0.1-dev.24'
|
|
19
19
|
version: '2026-09-12'
|
|
20
20
|
---
|
|
21
21
|
|
|
@@ -37,7 +37,7 @@ Check these before acting on anything below. Halt on the first one that fails an
|
|
|
37
37
|
|
|
38
38
|
## Never reset or drop a database
|
|
39
39
|
|
|
40
|
-
Never reset or drop a database to fix a migration,
|
|
40
|
+
Never reset or drop a database to fix a migration, contract signature or contract problem, and never propose it. A database can always be moved to the contract you want. When its migration history does not need to be kept (a local, development, staging or preview database), reconcile it with `prisma db update`. When it changes only through migrations, as production should, author the migrations that bring it there. The database's change policy, recorded in its signature, says which it is, and `db update` refuses one that permits only migrations; never edit a ref's `policies` or pass `--permit-policy-change` to get past that. A deploy that says there is no migration path, or `MIGRATION.SIGNATURE_NOT_IN_GRAPH`, is covered in [`references/migrations.md`](references/migrations.md) § *A database whose signature is not in the migration graph*.
|
|
41
41
|
|
|
42
42
|
Prisma 8 is a contract-first data layer. This skill routes every Prisma 8 task to the right reference file — open the reference before writing code; do not answer from this file alone.
|
|
43
43
|
|
|
@@ -63,14 +63,14 @@ Open the reference whose triggers match the task. If more than one matches, open
|
|
|
63
63
|
| --- | --- | --- |
|
|
64
64
|
| Adopt / set up / first steps | [`references/quickstart.md`](references/quickstart.md) | new project, existing database, "what can I do with Prisma 8", "where do I start", "just ran createprisma", `npx create-prisma`, first steps, first query, `prisma orm init` greenfield setup, `contract infer` + `db sign` brownfield adoption, connect-write-read first arc, day-to-day commands (`contract emit`, `db init`, `db update`, `migration plan`, `db migrate`, `db schema`, `db verify`), flags `--target` / `--authoring` / `--schema-path` / `--probe-db` / `--output` |
|
|
65
65
|
| Edit the data contract | [`references/contract.md`](references/contract.md) | schema, models, fields, attributes, relations, indexes, enums, value objects (composite types), type aliases, namespaces (Postgres schemas), cross-contract foreign keys (cross-space FK), polymorphic types (`@@discriminator` / `@@base`), extension namespaces (`pgvector.Vector(...)`, `postgis.Geometry(...)`), `prisma.config.ts` / `definePrismaConfig` / `ormConfig`, `prisma contract emit`, PSL, `contract.prisma`, `contract.ts`, `contract.json`, `contract.d.ts`, `@prisma/orm-postgres/config`, `@prisma/orm-postgres/contract-builder`, `@prisma/orm-mongo/config`, `extensions:`, pgvector, postgis, Temporal / `temporal-polyfill` / `RUNTIME.TEMPORAL_UNAVAILABLE`, `@@control`, control policy (managed / tolerated / external / observed), soft delete, validations, callbacks |
|
|
66
|
-
| Author migrations | [`references/migrations.md`](references/migrations.md) | "no migration path", "migration path not found", "no authored path", `MIGRATION.
|
|
66
|
+
| Author migrations | [`references/migrations.md`](references/migrations.md) | "no migration path", "migration path not found", "no authored path", `MIGRATION.SIGNATURE_NOT_IN_GRAPH`, `MIGRATION.CHANGE_POLICY_FORBIDS`, `MIGRATION.DATA_PROTECTION_FORBIDS`, `MIGRATION.POLICY_MISMATCH`, change policy, data protection policy, `migration ref policy show` / `set` / `delete`, declaring a ref's policies, `--permit-policy-change`, "reset the database", "drop the database", `db update` vs `migration plan`, `db migrate`, `migration new`, `migration show`, `db update --dry-run`, `db verify`, `db sign`, data migration, `dataTransform`, placeholder sentinels in framework-rendered `migration.ts`, `MIGRATION.HASH_MISMATCH`, `MIGRATION.UNFILLED_PLACEHOLDER`, data-loss questions (`--delete`, `--rename`, `--allow`, `CLI.CONSENT_REQUIRED`), schema drift |
|
|
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
|
-
| 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.
|
|
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.SIGNATURE_NOT_IN_GRAPH`, `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
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
|
-
| 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.
|
|
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.SIGNATURE_MISSING`, `CONFIG.*` / `CLI.*` / `CONTRACT.*` / `MIGRATION.*` / `ORM.*` / `RUNTIME.*` codes, legacy `PN-*` codes, exit code 4 findings, drift, capability missing, planner conflict, EXPLAIN, query log, script won't exit / close connection |
|
|
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), exact-pin rule, which `prisma` CLI version an extension's tests use, per-transition instructions in [`upgrading/extension/upgrades/`](upgrading/extension/upgrades/) |
|
|
76
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` |
|
|
@@ -84,18 +84,18 @@ The single source of truth: read the envelope, find the row by `code`, follow th
|
|
|
84
84
|
| `CONTRACT.VALIDATION_FAILED` | `contract emit`, `db *` | Re-run `pnpm prisma contract emit` after fixing the contract source named in `where.path`; `meta.errors` lists the issues. See `references/contract.md`. |
|
|
85
85
|
| `CONFIG.DB_CONNECTION_REQUIRED` | `db *`, `db migrate`, `migration status` | Pass `--db <url>` or set `db.connection` in `prisma.config.ts`. |
|
|
86
86
|
| `CONFIG.MISSING_EXTENSION_PACKS` | `contract emit` (e.g. contract uses `pgvector.Vector(...)` but config does not list the pgvector descriptor) | Add the descriptors named in `meta.missingExtensionPacks` to `extensions` in `prisma.config.ts`. See `references/contract.md`. |
|
|
87
|
-
| `MIGRATION.PLANNING_FAILED` | `db init`, `db update`, `migration plan` | Inspect `meta.conflicts`. Recovery is per-conflict — chain to `references/migrations.md`. When `migration plan` raises it for a first migration whose contract describes nothing to create (conflict kind `nothingToCreate`), the conflict's `why` gives the next step: `migration new`, with the operations written by hand. A plan from an earlier contract with no operations is not refused: it is written, and `db migrate` moves the
|
|
87
|
+
| `MIGRATION.PLANNING_FAILED` | `db init`, `db update`, `migration plan` | Inspect `meta.conflicts`. Recovery is per-conflict — chain to `references/migrations.md`. When `migration plan` raises it for a first migration whose contract describes nothing to create (conflict kind `nothingToCreate`), the conflict's `why` gives the next step: `migration new`, with the operations written by hand. A plan from an earlier contract with no operations is not refused: it is written, and `db migrate` moves the contract signature. |
|
|
88
88
|
| `CLI.INIT_MISSING_FLAGS` / `CLI.INIT_INVALID_FLAG_VALUE` / `CLI.INIT_REINIT_NEEDS_FORCE` / `CLI.INIT_*` | `prisma orm init` | Re-run with the flags listed in `meta.missingFlags` or `meta.allowed`; a re-init needs `--confirm <directory name>`. `CLI.INIT_INSTALL_FAILED` (exit 4) and `CLI.INIT_EMIT_FAILED` (exit 5) are findings on a completed scaffold — the files are on disk; fix and re-run the named step. |
|
|
89
89
|
| `MIGRATION.UNFILLED_PLACEHOLDER` | `node <package dir>/migration.ts` (self-emit) or `db migrate` | Edit `migration.ts`, replace the `placeholder("<slot>")` named by `meta.slot` with a real query closure, self-emit. See `references/migrations.md`. |
|
|
90
90
|
| `MIGRATION.FILE_MISSING` | Reading a migration package | Restore from version control or scaffold a fresh package with `migration plan` / `migration new`. |
|
|
91
91
|
| `MIGRATION.INVALID_DEFAULT_EXPORT` | Loading `migration.ts` | Use `export default class extends Migration<Start, End> { ... }` (or a factory returning `{ operations, targetId, destination }`). See `references/migrations.md`. |
|
|
92
92
|
| `MIGRATION.DATA_TRANSFORM_CONTRACT_MISMATCH` | Building a data-transform query plan | Pass the `contract` that `postgres({ contract: contractFromJson<End>(endContract) })` returns to `this.dataTransform(contract, …)`, and build the queries with that client's `sql`. |
|
|
93
93
|
| `MIGRATION.HASH_MISMATCH` | Any read of a migration package (`plan`, `list`, `db migrate`) | `ops.json` / `migration.json` were edited without self-emitting. Run `node <package dir>/migration.ts` to re-emit. |
|
|
94
|
-
| `CONTRACT.
|
|
95
|
-
| `CONTRACT.
|
|
94
|
+
| `CONTRACT.SIGNATURE_MISSING` | `db verify` (`error` diagnostic, exit 4), runtime startup (warning) | DB has no signature yet. Run `prisma db init --db <url>` (baseline empty DB), `db update --db <url>` (apply contract directly), or `db sign --db <url>` if the schema already matches the contract. |
|
|
95
|
+
| `CONTRACT.SIGNATURE_MISMATCH` | `db verify` (exit 4), runtime startup (warning) | Signature disagrees with contract hash (`meta.expected` / `meta.actual`). Either migrate forward (`db migrate` / `db update`), or — if the DB is correct after a manual fix-up — `db sign`. See `references/migrations.md`. |
|
|
96
96
|
| `CONTRACT.TARGET_MISMATCH` | `db verify`, runtime startup | Contract target ≠ config target; align them (see `meta.expected` / `meta.actual`). |
|
|
97
97
|
| `CONTRACT.SCHEMA_VERIFICATION_FAILED` | `db verify`, `db sign` (both exit 4 with the finding) | Live schema does not satisfy the contract; `meta.schemaIssues` lists the schema diff issues per `meta.space`, in the same shape as `MIGRATION.SCHEMA_VERIFY_FAILED`. Run `db update` to reconcile, or adjust the contract. |
|
|
98
|
-
| `MIGRATION.SCHEMA_VERIFY_FAILED` | `db migrate`, `db update`, `db init` | The schema after apply does not satisfy the contract; the
|
|
98
|
+
| `MIGRATION.SCHEMA_VERIFY_FAILED` | `db migrate`, `db update`, `db init` | The schema after apply does not satisfy the contract; the signature stays at its origin, and on SQL targets the apply rolled back (on MongoDB the operations that ran stay applied). `meta.schemaIssues` lists the issues and `why` names them. Change the contract source to resolve them, re-emit, and re-run; `db migrate` also says how to plan the failed migration again. |
|
|
99
99
|
| `MIGRATION.PRECHECK_FAILED` | `db migrate`, `db update`, `db init` | An operation's check before it ran did not hold (`meta.failedCheck`); the apply rolled back on SQL targets. `meta.rowsWithoutValue` is set when a field becoming required has rows with no value. Follow `nextActions`. |
|
|
100
100
|
| `CLI.CONSENT_REQUIRED` | `migration plan` / `db update` when a plan would lose data (or, on `db update`, widen access) and nobody can answer (`--no-interactive`, CI, `--yes`) | `meta.unanswered[]` and `nextActions` list each question with its flags. Re-run with `--delete <subject>`, `--rename <subject>:<new name>` or `--allow <Model>` as each subject means. `--confirm` and `--yes` answer none of them. `db migrate` does not ask. |
|
|
101
101
|
| `CLI.CONSENT_UNUSED` | `migration plan` / `db update` | Every question was answered, and a `--delete` or `--allow` was left over: a typo, a subject the plan does not touch, or a `--confirm` (which consents to nothing). Fix or drop the flag. A typo next to a question nobody answered is reported as `CLI.CONSENT_REQUIRED` instead, which names the flag that matched nothing. On `db update --dry-run` the same mistake is `MIGRATION.STATEMENT_ANSWERS_NO_QUESTION`. |
|
|
@@ -103,14 +103,14 @@ The single source of truth: read the envelope, find the row by `code`, follow th
|
|
|
103
103
|
| `MIGRATION.NO_INVARIANT_PATH` / `MIGRATION.UNKNOWN_INVARIANT` | `db migrate` | Concurrent-migration and invariant flows — `references/migration-review.md`. |
|
|
104
104
|
| `DRIVER.NOT_CONNECTED` with message `Runtime is closed` | A query, prepared statement or `db.runtime().connection()` that starts after `db.close()` and after the runtime was idle for one turn of the event loop, or after the `await using` scope that held a serverless connection ended | The work started after the runtime closed. Almost always it is a lazy read (`db.orm...all()`, `db.query(...)`) returned without `await`, which starts only when the caller awaits it, or work that waited on something other than the database first. Write `return await ...`, or move the call before `close()`. See `references/runtime.md` § *Workflow — Serverless and per-request runtimes*. |
|
|
105
105
|
| `await db.close()` or the end of an `await using` scope never settles in a test | A test that installed fake timers (`vi.useFakeTimers()`, Jest's modern fake timers) before the Prisma runtime module was imported | `close()` waits one turn of the event loop through a `setTimeout(0)` that the runtime module takes when it loads. Install fake timers after the imports, or advance the fake clock (`await vi.runAllTimersAsync()`) before awaiting the close. |
|
|
106
|
-
| `MIGRATION.
|
|
106
|
+
| `MIGRATION.SIGNATURE_NOT_IN_GRAPH` | `db migrate`, `db migrate --show`, a Composer deploy | The database's signature is not in the migration graph, usually because a migration it applied was planned again or deleted. `why` names the last graph contract it applied and the missing migrations. `nextActions` gives the one recovery the database's change policy permits. Follow `references/migrations.md` § *A database whose signature is not in the migration graph*. Never reset or drop the database. |
|
|
107
107
|
| `MIGRATION.CHANGE_POLICY_FORBIDS` | `db update`, `db sign`, `db migrate` | The database's change policy does not include what the command does. When `db update` or `db sign` is refused, follow its advice: apply the migrations on disk that already lead to the target with `db migrate`, or author one (with `migration plan`, or with `migration new` when the database is already at the target and lacks only invariants) and apply it with `db migrate`. See `references/migrations.md` § *Policies*. |
|
|
108
108
|
| `MIGRATION.DATA_PROTECTION_FORBIDS` | `db update`, `db migrate`, `migration plan --to <ref>`, a Composer deploy | The database's data protection policy (or the ref's, for `migration plan --to <ref>` and a run given `--permit-policy-change`) forbids an operation that loses data or changes who can read or write rows. `meta.operations` lists them. The operation cannot run on that database. For `db update` and `migration plan`, a refused data loss: state a `--rename` if it was only a rename, plan a type change with `migration plan --convert`, or keep the model or field. A refused access change: keep the contract's access rules as they are. For `db migrate`, first find out whether another database has applied the refused migration; if one has, keep it as it is and tell the user that this database cannot run it. If none has, delete it and every later migration no database has applied, and plan once from where the first one started, with `--rename`, `--convert`, or after putting back in the contract what it removes; never only take the operation out of the migration. The full steps (saving hand-written operations, `--from`, `contract emit`, moving refs) are in `references/migrations.md` § *Policies*. For `db migrate` and `db update`, an operation in an extension's contract space belongs to the extension: do not edit or delete its migration; ask the extension's author for a version without the operation, and tell the user. `--delete` and `--allow` do not help. Never change a database's or a ref's policy to make a deploy pass, and never suggest that anyone does. See `references/migrations.md` § *Policies*. |
|
|
109
109
|
| `MIGRATION.POLICY_MISMATCH` | `db migrate --to <ref>`, `db update --to <ref>`, a Composer deploy | The ref declares a policy that differs from the database's, and nothing runs while they differ. The error says to report the difference to whoever owns the database: tell the user. Never change the ref's or the database's policies to make them match, and never suggest that anyone does. See `references/migrations.md` § *Policies*. |
|
|
110
|
-
| `MIGRATION.PATH_UNREACHABLE` | `db migrate`, a Composer deploy | The
|
|
110
|
+
| `MIGRATION.PATH_UNREACHABLE` | `db migrate`, a Composer deploy | The signature is in the graph but no migration reaches the target from it. Run the two commands the error prints: a `migration plan --from <contract>`, with `--to <target>` unless the target is the emitted contract (a contract change emitted but not planned), then the `db migrate` that was run, with its flags. To the emitted contract, `--from` is where the history that continues from the signature ends, so the new migration extends the history instead of forking it; to any other target it is the signature. On an empty database, `--from` is where the migration history ends. When the history has more than one end, the error names each end for you to choose from. A database with no signature in a project with no migrations gets the plan from `@empty` as a choice: run it only on an empty database, and adopt one that already has tables with `db sign` first. When the path ends at the empty contract (`--to @empty`), or the project has migrations and the path starts at a contract none of them records, no plan can author it, and the error prints only `migration list`. In a project with no migrations yet, the plan starts from the ref that names the database's contract, and with no such ref the error prints no plan and says why. When an extension space has no path, the error says to install a version of the extension whose migrations start where the database is. `migration list` audits the graph. |
|
|
111
111
|
| `MIGRATION.PLAN_ORIGIN_UNKNOWN` / `MIGRATION.HASH_NOT_IN_GRAPH` / `MIGRATION.SNAPSHOT_MISSING` | `migration plan`, `migration new` | Origin resolution — `references/migration-model.md` § *The trap* and `references/migrations.md` § *Dev → ship transition*. |
|
|
112
|
-
| `MIGRATION.MISSING_INVARIANTS` | `migration status` `warn` diagnostic (exit 0) | The live
|
|
113
|
-
| `MIGRATION.
|
|
112
|
+
| `MIGRATION.MISSING_INVARIANTS` | `migration status` `warn` diagnostic (exit 0) | The live signature reached the destination hash structurally but doesn't carry all invariants the target ref requires. Run `db migrate --to <name> --db $URL` to take a path that covers the missing invariants. See `references/migration-review.md`. |
|
|
113
|
+
| `MIGRATION.SIGNATURE_NOT_IN_GRAPH` / `CONTRACT.UNREADABLE` | `migration status` `warn` diagnostics (exit 0) | Read `severity` *and* `code`. Up-to-date / pending / no-signature states are not codes — read `spaces[].currentContract` and `migrations[].status` in the `--json` document. `references/migration-review.md` covers the signature-out-of-history flow. |
|
|
114
114
|
| `BUDGET.ROWS_EXCEEDED` / `BUDGET.TIME_EXCEEDED` | Runtime, when the `budgets` middleware is active | Tune `budgets({ maxRows, maxLatencyMs, ... })` or rewrite the query. See `references/runtime.md`. |
|
|
115
115
|
| `LINT.SELECT_STAR` / `LINT.NO_LIMIT` / `LINT.DELETE_WITHOUT_WHERE` / `LINT.UPDATE_WITHOUT_WHERE` / `LINT.READ_ONLY_MUTATION` | Runtime, when the `lints` middleware is active | Fix the query (add a `WHERE` / `LIMIT` / explicit columns), or relax the lint config. See `references/runtime.md`. |
|
|
116
116
|
| `PLAN.HASH_MISMATCH` | Runtime, executing a precompiled plan | The contract the plan was built against does not match the runtime contract. Re-emit, rebuild, redeploy. |
|
|
@@ -130,8 +130,8 @@ If the envelope's `code` is not in this table, follow the envelope's `fix` field
|
|
|
130
130
|
1. **Reading only `summary`, not the rest of the envelope.** `code`, `severity`, `why`, `fix`, `meta`/`details`, and (for CLI errors) `where` all carry information the recovery depends on. The agent routes on `code`; the user sees `summary`.
|
|
131
131
|
2. **Ignoring `severity`.** `migration status` emits warn-level diagnostics and **exits 0**. An agent that only checks exit code misses every concurrent-migration warning.
|
|
132
132
|
3. **Matching `MIGRATION.RUNNER_FAILED`.** That code no longer exists: an apply failure carries the runner's own code, and its facts are in typed `meta` keys.
|
|
133
|
-
4. **Treating drift as something to silence with `db sign`.** `db sign` writes the
|
|
134
|
-
5. **Re-running `db migrate` after a partial failure without inspecting state.** `db schema --db <url>` shows the live shape; `migration status --db <url> --json` shows where the
|
|
133
|
+
4. **Treating drift as something to silence with `db sign`.** `db sign` writes the contract signature from the current contract hash and, by default, advances the `db` ref to it (`--no-advance-ref` skips the ref), but it requires schema verification to pass first. Run `db verify` before reaching for `db sign`.
|
|
134
|
+
5. **Re-running `db migrate` after a partial failure without inspecting state.** `db schema --db <url>` shows the live shape; `migration status --db <url> --json` shows where the signature actually is.
|
|
135
135
|
|
|
136
136
|
## What Prisma 8 doesn't do yet
|
|
137
137
|
|
|
@@ -28,12 +28,12 @@ The on-disk migrations under `migrations/<space>/` form a directed graph. **Each
|
|
|
28
28
|
Consequences worth internalising:
|
|
29
29
|
|
|
30
30
|
- **No node is privileged.** There is no "current" node, no HEAD, no special tip the planner chains from. Multiple branch tips are legal (two migrations planned off the same node). Cycles are legal (a rollback edge back to an earlier hash creates one).
|
|
31
|
-
- **The graph does not know where your database is.** "Where is my database" is answered by the database's **
|
|
31
|
+
- **The graph does not know where your database is.** "Where is my database" is answered by the database's **contract signature** (a live-DB record of "this database is at hash X") and, offline, by **refs**. Never by the graph.
|
|
32
32
|
- **The graph does not know where your next migration should start.** The planner has to be told an origin. That is the entire job of refs and `--from`.
|
|
33
33
|
|
|
34
34
|
### What a migration may contain
|
|
35
35
|
|
|
36
|
-
Because a migration is an edge, `db migrate` can run it on any database whose
|
|
36
|
+
Because a migration is an edge, `db migrate` can run it on any database whose contract signature is at its `from` hash, however that database got there: created by `db init`, adopted with `db sign`, restored from a backup, or brought along a different path through the graph. Those databases share a schema but not their rows, so every operation must be correct on any of them. A schema change tests the live schema before and after it runs. Most operation factories do this for you, but not all: on Postgres, `createNativeEnumType` and `dropNativeEnumType` emit no checks. A `rawSql` DDL step you write must carry its own precheck and postcheck. A data change is a data transform; on Postgres and Mongo its `check` decides on each database whether there is work to do. `references/migrations.md` § *Data changes go in a data transform* gives the rule, the reason, and what each target checks.
|
|
37
37
|
|
|
38
38
|
### Refs — version-controlled pointers
|
|
39
39
|
|
|
@@ -64,17 +64,17 @@ A ref's `policies` are read and written with `migration ref policy show`, `set`
|
|
|
64
64
|
| `db sign` | Advances `db` after a successful signature (override the name with `--advance-ref <name>`; `--no-advance-ref` skips it, writing no ref and no snapshot); an existing ref is overwritten and the previous hash is reported in the human output (the JSON `advancedRefs` lists `{ space, name, hash }` for each contract space it advanced). `--db` does **not** suppress it, unlike init/update: sign never mutates the schema, and adoption is normally done via `--db` |
|
|
65
65
|
| `db migrate` | Advances `db` after a successful apply when the connection comes from `prisma.config.ts` and the CLI does not detect CI. Never with `--db`, and never in CI (unless the `CI` environment variable is `false`, which turns detection off whatever else is set, the CLI detects CI when `CI` is set or when a variable that CI services set is present, such as `BUILD_NUMBER`, `BUILD_ID` or `GITHUB_ACTIONS`; the run then reports `MIGRATION.REF_NOT_ADVANCED_IN_CI`), so deploys and pipelines write no ref. `--advance-ref <name>` advances that ref instead, in every case; `--no-advance-ref` advances none. A run that ends at the empty contract, which a ref cannot name, leaves `db` unchanged and, when `db` exists and the run passes neither `--db` nor `--no-advance-ref`, warns (`MIGRATION.REF_NOT_ADVANCED_TO_EMPTY`; when that database is your development database, remove the stale ref with `migration ref delete db`), and refuses an explicit `--advance-ref` before applying. A ref that cannot be written is a warning (`MIGRATION.REF_NOT_WRITTEN`), not a failure: the migrations have already applied |
|
|
66
66
|
| `migration plan` | Never advances anything — chaining discipline is yours |
|
|
67
|
-
| deploys (Composer / CD) | Write the database's
|
|
67
|
+
| deploys (Composer / CD) | Write the database's contract signature; structurally cannot and do not touch repo refs |
|
|
68
68
|
|
|
69
69
|
### How `migration plan` picks its origin
|
|
70
70
|
|
|
71
71
|
`migration plan` resolves its origin in exactly this order:
|
|
72
72
|
|
|
73
|
-
1. Explicit `--from <ref-name | hash | hash-prefix | migration-dir | migration-dir^ | @empty>` — `@empty` names the empty database deliberately. The reserved forms `@db` and `@contract` exist in the shared ref grammar but do not resolve here: `migration plan` is offline, so `@db` (the live
|
|
73
|
+
1. Explicit `--from <ref-name | hash | hash-prefix | migration-dir | migration-dir^ | @empty>` — `@empty` names the empty database deliberately. The reserved forms `@db` and `@contract` exist in the shared ref grammar but do not resolve here: `migration plan` is offline, so `@db` (the live contract signature) has nothing to read, and `@contract` needs a contract hash the plan resolver does not pass. Use them with `db migrate --show` / `migration status`, not with `plan`.
|
|
74
74
|
2. No `--from` → the `db` ref (`migrations/app/refs/db.json`).
|
|
75
75
|
3. No `db` ref → **greenfield: the plan starts from the empty database.** On an empty graph the human output adds a muted notice beneath the summary — `No db ref set — planning from an empty database. Run db init, db update, or db sign if a database already exists.` — and the JSON document carries `fromDefaulted: true`, so this case is distinguishable from an explicit `--from @empty`.
|
|
76
76
|
|
|
77
|
-
It is **offline** — it never consults a database, never reads a
|
|
77
|
+
It is **offline** — it never consults a database, never reads a signature (which is why `--from @db` is not an option here). Whatever the refs on disk say is what it believes. The destination defaults to the emitted `contract.json` (`--to` overrides).
|
|
78
78
|
|
|
79
79
|
When the origin came from the `db` ref by default and that node **already has an outgoing migration**, the plan still succeeds but warns: planning from there forks the graph. Pass `--from` to name the origin deliberately if that is what you want.
|
|
80
80
|
|
|
@@ -86,7 +86,7 @@ The human output names the resolved origin on its `from:` line. **`from: (baseli
|
|
|
86
86
|
|
|
87
87
|
## The trap — a greenfield plan over existing migrations
|
|
88
88
|
|
|
89
|
-
**A plan whose origin is the empty contract while migrations already exist on disk is almost always a mistake.** A full-create migration cannot do what you meant: a database that has the prior migrations applied refuses it (`MIGRATION.PATH_UNREACHABLE` — no path from its
|
|
89
|
+
**A plan whose origin is the empty contract while migrations already exist on disk is almost always a mistake.** A full-create migration cannot do what you meant: a database that has the prior migrations applied refuses it (`MIGRATION.PATH_UNREACHABLE` — no path from its contract signature to the new plan's destination), and running its create statements against any populated schema fails outright. The CLI refuses this at plan time: when origin resolution falls all the way through (no `--from`, no `db` ref) and migrations exist, `migration plan` stops with `MIGRATION.PLAN_ORIGIN_UNKNOWN` instead of writing the package — the error's suggestions are the three exits below; do not reflexively take the `--from @empty` one, pick by intent.
|
|
90
90
|
|
|
91
91
|
How the fall-through happens: a project whose only commands run in CI or deploys (the deploy-first path below) never acquires a `db` ref, so *every* default plan resolves to the empty origin. Running the dev loop with an explicit `--db` has the same effect: `db init`, `db update` and `db migrate` with that flag never advance the ref, whatever URL it carries (`db sign` is the exception — it advances the ref with or without `--db`). The first time that is correct (it is the baseline; an empty migration graph plans with only the muted notice); every later time it is the trap the refusal catches.
|
|
92
92
|
|
|
@@ -117,7 +117,7 @@ Full mechanics, refusals, and recovery: `references/migrations.md` § *Dev → s
|
|
|
117
117
|
|
|
118
118
|
## Workflow — the deploy-first loop (Composer / CD-managed databases)
|
|
119
119
|
|
|
120
|
-
The concept: the deploy pipeline owns the databases, so `db init` / `db update` never run, `db migrate` runs only in CI or with `--db`, and nothing ever advances a `db` ref for you. Deploys replay each database from its
|
|
120
|
+
The concept: the deploy pipeline owns the databases, so `db init` / `db update` never run, `db migrate` runs only in CI or with `--db`, and nothing ever advances a `db` ref for you. Deploys replay each database from its contract signature to the contract emitted at build time; they never write to `migrations/app/refs/`. Two disciplines keep this loop safe:
|
|
121
121
|
|
|
122
122
|
**Author the baseline before the first deploy.** Before anything is deployed:
|
|
123
123
|
|
|
@@ -127,7 +127,7 @@ pnpm prisma migration plan --name init # from: (baseline) — intended, thi
|
|
|
127
127
|
git add migrations/ && git commit
|
|
128
128
|
```
|
|
129
129
|
|
|
130
|
-
This is the one intended greenfield plan. With the baseline committed, the deployed database's
|
|
130
|
+
This is the one intended greenfield plan. With the baseline committed, the deployed database's signature always corresponds to a graph node, and every later state is reachable by planned migrations.
|
|
131
131
|
|
|
132
132
|
**Chain every later plan from the last shipped contract.** Nothing advances refs in this loop, so either keep the `db` ref current yourself — after each plan, `migration ref set db <new-migration-to-hash>` (the hash is a graph node as soon as the plan is written; `migration list` shows it) — or pass `--from <last-migration-dir>` on every plan. Committing the ref together with the migration keeps teammates' default plans chaining correctly too.
|
|
133
133
|
|
|
@@ -135,7 +135,7 @@ If you skip the chaining, the next default plan resolves to greenfield: the trap
|
|
|
135
135
|
|
|
136
136
|
## Workflow — adopt a pre-existing database
|
|
137
137
|
|
|
138
|
-
The concept: a database that predates Prisma 8 enters the system by describing it, not migrating it — `contract infer` derives the contract from the live schema, and after review + `contract emit`, `db sign` records the
|
|
138
|
+
The concept: a database that predates Prisma 8 enters the system by describing it, not migrating it — `contract infer` derives the contract from the live schema, and after review + `contract emit`, `db sign` records the contract signature. Full recipe: `references/quickstart.md` § *Brownfield-DB*.
|
|
139
139
|
|
|
140
140
|
```bash
|
|
141
141
|
pnpm prisma contract infer --db "$DATABASE_URL" --output src/prisma/contract.prisma
|
|
@@ -148,7 +148,7 @@ By default `db sign` sets the `db` ref to the signed contract's hash and stores
|
|
|
148
148
|
|
|
149
149
|
## Workflow — retrofit a database that has no on-disk migrations
|
|
150
150
|
|
|
151
|
-
The concept: the database exists and its
|
|
151
|
+
The concept: the database exists and its contract signature is accurate (hash **M**) — it was built by `db update` or signed with `db sign` in another checkout, or built by a deploy pipeline — but the migration graph doesn't reach M. (A database adopted with `db sign` in *this* checkout already has its ref set; retrofit is for the case where the ref was never set here.) The goal is to **make the graph reach the signature's hash**: once a baseline `null → M` exists, applying against the marked database is clean by construction — the runner starts at the signature, so the baseline never executes; only real deltas past M run.
|
|
152
152
|
|
|
153
153
|
- **It's your dev database.** Run `db update` (default URL; no-op on the DB when the contract already matches) — it advances the `db` ref and stores the contract snapshot. The next `migration plan` auto-emits the baseline plus your delta. This is just the dev loop's dev → ship transition.
|
|
154
154
|
- **It's a deployed database you must not touch.** Build the baseline offline, at the deployed contract state:
|
|
@@ -163,7 +163,7 @@ The concept: the database exists and its marker is accurate (hash **M**) — it
|
|
|
163
163
|
|
|
164
164
|
1. **Assuming `migration plan` or `migration new` chains from the newest migration on disk.** Neither does. The origin is `--from`, else the `db` ref. With neither, only an empty graph plans from scratch (with the muted `No db ref set` notice); once migrations exist, both commands refuse with `MIGRATION.PLAN_ORIGIN_UNKNOWN`.
|
|
165
165
|
2. **Expecting `migration plan`, or `db migrate` with `--db` or in CI, to keep the `db` ref current.** None of them touches refs. `db init`, `db update` and `db migrate` advance `db` only when the connection comes from `prisma.config.ts` (and, for `db migrate`, outside CI); `db sign` advances it even with `--db`. Elsewhere, pass `--advance-ref db`.
|
|
166
|
-
3. **Expecting a deploy to update refs.** Deploys write the database's
|
|
166
|
+
3. **Expecting a deploy to update refs.** Deploys write the database's contract signature; the files under `migrations/app/refs/` only change when you change them.
|
|
167
167
|
4. **Reading `from: (baseline)` as informational.** Over a non-empty migrations directory it is the trap announcing itself. Stop and pick an exit before applying or committing.
|
|
168
168
|
5. **`migration ref set` with a hash no on-disk migration produces.** A ref target must be the `to` hash of an on-disk migration bundle. A hash outside the graph is refused (`MIGRATION.HASH_NOT_IN_GRAPH`); a from-only graph node is refused with `MIGRATION.REF_SET_BUNDLE_NOT_FOUND`, whose fix text points at fixtures and is unhelpful here. Either way: plan the edge whose `to` is the hash first (baseline or delta), then set the ref.
|
|
169
169
|
6. **Treating `db` as reserved.** It's a naming default. Setting it yourself is fine and sometimes exactly right (deploy-first chaining, retrofit); just expect dev commands on the config's database (`db init`, `db update`, and `db migrate` outside CI) to overwrite it.
|
|
@@ -179,6 +179,6 @@ The concept: the database exists and its marker is accurate (hash **M**) — it
|
|
|
179
179
|
- [ ] Read the plan output's `from:` line and confirmed it names that origin — not `(baseline)` over an existing graph.
|
|
180
180
|
- [ ] In a deploy-first project: baseline authored and committed before the first deploy; every later plan chained via the `db` ref or `--from`.
|
|
181
181
|
- [ ] After each plan in a loop where nothing advances refs: advanced the `db` ref (`migration ref set db <to-hash>`) or resolved to pass `--from` next time.
|
|
182
|
-
- [ ] For a marked database with no on-disk migrations: made the graph reach the
|
|
182
|
+
- [ ] For a marked database with no on-disk migrations: made the graph reach the contract signature's hash (auto-baseline via `db update` or `db sign`, or an offline baseline plan) before planning deltas.
|
|
183
183
|
- [ ] Expected plain `db migrate` to advance `db` only when its connection comes from `prisma.config.ts`, the CLI does not detect CI and neither `--advance-ref` nor `--no-advance-ref` is passed; did NOT expect `migration plan`, `db migrate --db`, or a deploy in CI to advance any ref.
|
|
184
184
|
- [ ] Did NOT apply or commit a `from: (baseline)` plan without confirming the empty origin was the intent.
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
|
|
6
6
|
This skill is about *reviewing* migrations, not authoring them. It covers the questions that come up at deploy time and when multiple developers are landing migrations concurrently.
|
|
7
7
|
|
|
8
|
-
The skill teaches *the system's mental model* — what a ref is, what a
|
|
8
|
+
The skill teaches *the system's mental model* — what a ref is, what a contract signature is, what the migration graph is — and shows how to ask the system for its state. It does **not** prescribe rigid step-by-step procedures: most "review" questions are answered by understanding the model and querying the right thing. Rigid procedures are reserved for the rare case where there's literally one safe path.
|
|
9
9
|
|
|
10
10
|
## When to Use
|
|
11
11
|
|
|
@@ -27,9 +27,9 @@ The skill teaches *the system's mental model* — what a ref is, what a marker i
|
|
|
27
27
|
|
|
28
28
|
### Origin
|
|
29
29
|
|
|
30
|
-
The **origin** is the database's *current contract hash*. The database carries a row in Prisma 8's
|
|
30
|
+
The **origin** is the database's *current contract hash*. The database carries a row in Prisma 8's contract signature table that records *"this database is at hash X"*. When the CLI runs online (a `--db <url>` is provided, or `db.connection` is set in `prisma.config.ts`), Prisma 8 reads the signature and that hash is the origin. Offline (no DB connection), the origin is unknown — many commands degrade to listing the on-disk migrations and skip the per-edge applied/pending status.
|
|
31
31
|
|
|
32
|
-
A live DB is therefore the authoritative source of origin. The "recorded
|
|
32
|
+
A live DB is therefore the authoritative source of origin. The "recorded signature" in any other artifact (refs, local cache, your assumptions) is a working copy that can drift; the live DB never does.
|
|
33
33
|
|
|
34
34
|
### Destination
|
|
35
35
|
|
|
@@ -42,9 +42,9 @@ The **destination** is the contract hash you want the database to be at. Two way
|
|
|
42
42
|
|
|
43
43
|
### The migration graph
|
|
44
44
|
|
|
45
|
-
The on-disk migrations form a directed graph: **nodes are contract hashes; edges are migrations.** Each migration declares a `from` hash and a `to` hash. A migration applies only when the database's current
|
|
45
|
+
The on-disk migrations form a directed graph: **nodes are contract hashes; edges are migrations.** Each migration declares a `from` hash and a `to` hash. A migration applies only when the database's current contract signature matches its `from` hash; running it advances the signature to its `to` hash.
|
|
46
46
|
|
|
47
|
-
The graph is a static, committed artifact. Several branch tips may coexist, rollback edges may form cycles, and no node is privileged — "where is my database" is answered by the
|
|
47
|
+
The graph is a static, committed artifact. Several branch tips may coexist, rollback edges may form cycles, and no node is privileged — "where is my database" is answered by the signature and refs, never by the graph itself. `references/migration-model.md` carries the full model, including how `migration plan` chooses its origin.
|
|
48
48
|
|
|
49
49
|
`migration status` queries the graph for the path from origin to destination and reports per-edge status:
|
|
50
50
|
|
|
@@ -54,12 +54,12 @@ The graph is a static, committed artifact. Several branch tips may coexist, roll
|
|
|
54
54
|
|
|
55
55
|
### Diagnostic codes
|
|
56
56
|
|
|
57
|
-
`migration status` answers with a document (`--json`): `spaces[]`, each with `currentContract` (the
|
|
57
|
+
`migration status` answers with a document (`--json`): `spaces[]`, each with `currentContract` (the contract hash in the contract signature, or `null` when the database has no signature for that space), `targetContract`, and `migrations[]` carrying the `applied` / `pending` / `null` status above; a `summary` line; and `diagnostics[]`. The ordinary states — up to date, N pending, no signature yet, signature on another branch, no path to the target — are read from `spaces[]` and the summary, not from diagnostic codes. The three diagnostics it can attach are all `warn`, and each carries a `message` and `hints` — the same hints the CLI prints under the summary line:
|
|
58
58
|
|
|
59
59
|
| Code | Meaning in the navigation model | Next move |
|
|
60
60
|
|---|---|---|
|
|
61
|
-
| `MIGRATION.
|
|
62
|
-
| `MIGRATION.MISSING_INVARIANTS` |
|
|
61
|
+
| `MIGRATION.SIGNATURE_NOT_IN_GRAPH` | Online; signed contract hash is not a node in the graph. The database was changed outside the migration system. | Follow the finding's advice, which depends on the database's change policy. When the policy includes `reconcile`, decide which side is truth: `db sign` (accept DB as truth), `db update` (push contract to DB), `contract infer` (re-derive contract from DB), or `db verify` (inspect first). When it is `migrate` alone, `db sign` and `db update` are refused: author migrations that bring the database back onto the graph. When the policies cannot be read, have them corrected first: on Postgres the `policies` column of `prisma.config`, elsewhere `meta.policies` in the application space's signature. **Not** the same as `MIGRATION.SIGNATURE_NOT_IN_GRAPH`, which `db migrate` (before any DDL) and `db migrate --show` raise as an error when the signed contract hash is not a graph node. |
|
|
62
|
+
| `MIGRATION.MISSING_INVARIANTS` | Signature reached the destination structurally but lacks invariants the target ref declares. | `db migrate --to <name> --db $URL` to take a path that covers them. |
|
|
63
63
|
| `CONTRACT.UNREADABLE` | `contract.json` couldn't be read. | `contract emit` to regenerate it. |
|
|
64
64
|
|
|
65
65
|
Conditions that make the run *refuse* instead (exit `2`) arrive as ordinary errors: `MIGRATION.NO_INVARIANT_PATH` (no path covers the missing invariants), `MIGRATION.UNKNOWN_INVARIANT` (the ref names an invariant no edge provides), and the ref-resolution errors for a bad `--to` / `--from`.
|
|
@@ -81,14 +81,14 @@ These codes surface on `migration plan`, `migration ref set`, and `db migrate`
|
|
|
81
81
|
|---|---|---|---|
|
|
82
82
|
| `MIGRATION.HASH_NOT_IN_GRAPH` | `migration plan` (non-empty graph) or `migration ref set` | Resolved hash is not a node in the on-disk migration graph — typical when the default `db` ref points past the graph tip after `db update` cycles. | `migration plan --from <reachable-ref>` (e.g. `--from production`); or realign the ref with `migration ref set db <graph-node-hash>`. |
|
|
83
83
|
| `MIGRATION.SNAPSHOT_MISSING` | `migration plan` | A named ref has no pointer file (`<name>.json`), and the hash being resolved isn't a node in the migration graph either. | `migration ref set <name> <hash>` to create the ref, `db update --advance-ref <name>` to advance it, or pass a hash that is a graph node. |
|
|
84
|
-
| `MIGRATION.
|
|
85
|
-
| `MIGRATION.PATH_UNREACHABLE` | `db migrate` (path resolution) | No migration path from the current
|
|
84
|
+
| `MIGRATION.SIGNATURE_NOT_IN_GRAPH` | `db migrate` (pre-DDL, before the runner), `db migrate --show` | Live contract hash the database is signed with is not a graph node. Usually a migration the database applied was planned again or deleted. | Follow the error's next actions, and `references/migrations.md` § *A database whose contract signature is not in the migration graph*. Never reset the database. |
|
|
85
|
+
| `MIGRATION.PATH_UNREACHABLE` | `db migrate` (path resolution) | No migration path from the current signature to the resolved target in the on-disk graph. | Read the improved `fix` payload — it names `fromHash` / `targetHash` and prints the `migration plan` and `db migrate` commands to run, with `--to <target>` unless the target is the emitted contract. On an empty database the plan starts from where the migration history ends. When the space named is an extension's, it prints no plan command: install a version of the extension whose migrations start from the contract the database is at; run `migration list` to inspect the graph. |
|
|
86
86
|
|
|
87
87
|
## Workflow — *"What's about to run on deploy?"*
|
|
88
88
|
|
|
89
89
|
The user asks: *"I'm about to merge this PR. What migrations are going to run when I deploy to staging?"*
|
|
90
90
|
|
|
91
|
-
This is the navigation question: **origin** = staging's live
|
|
91
|
+
This is the navigation question: **origin** = staging's live contract signature; **destination** = the ref `staging` (or the contract head if you haven't set one). Ask the system:
|
|
92
92
|
|
|
93
93
|
```bash
|
|
94
94
|
pnpm prisma migration status --to staging --db "$STAGING_DATABASE_URL"
|
|
@@ -96,12 +96,12 @@ pnpm prisma migration status --to staging --db "$STAGING_DATABASE_URL"
|
|
|
96
96
|
|
|
97
97
|
The command:
|
|
98
98
|
|
|
99
|
-
1. Reads the staging DB's
|
|
99
|
+
1. Reads the staging DB's signature (the origin).
|
|
100
100
|
2. Resolves `staging` to a contract hash (the destination).
|
|
101
101
|
3. Renders the path between them as an ordered list of migrations, with per-edge `applied` / `pending` / `null` status, and an explicit summary line of the form *"N migration(s) behind ref 'staging'"*.
|
|
102
102
|
4. Prints a header that names the config, migrations directory, the active ref, and the database connection (masked) — so the framing is visible in the output.
|
|
103
103
|
|
|
104
|
-
If you omit `--db`, the command runs offline: it lists the migrations on disk but cannot tell you what's applied, because it has no origin. That's fine for *"what's on this branch?"*; it's not fine for *"what's about to run on staging?"* — for that you need staging's live
|
|
104
|
+
If you omit `--db`, the command runs offline: it lists the migrations on disk but cannot tell you what's applied, because it has no origin. That's fine for *"what's on this branch?"*; it's not fine for *"what's about to run on staging?"* — for that you need staging's live signature.
|
|
105
105
|
|
|
106
106
|
If you omit `--to`, the destination defaults to the contract head — which answers *"is this branch's contract reachable from the database, and how?"*, not *"what runs on deploy"*. Pass the ref explicitly when the question is about a specific environment.
|
|
107
107
|
|
|
@@ -109,7 +109,7 @@ If you omit `--to`, the destination defaults to the contract head — which answ
|
|
|
109
109
|
|
|
110
110
|
## Workflow — *"What state is each environment at?"*
|
|
111
111
|
|
|
112
|
-
Just `migration status --db $URL` for each environment's DB. The
|
|
112
|
+
Just `migration status --db $URL` for each environment's DB. The contract signature (origin) comes back from the DB itself; the summary line tells you whether the environment is at the contract head, at a named ref, ahead of head, or on a divergent branch.
|
|
113
113
|
|
|
114
114
|
## Concept — concurrent migrations on the same branch point
|
|
115
115
|
|
|
@@ -148,7 +148,7 @@ Two ref roles, one mechanism: environment refs like `production` are the contrac
|
|
|
148
148
|
pnpm prisma db migrate --to production --db "$PRODUCTION_DATABASE_URL"
|
|
149
149
|
```
|
|
150
150
|
|
|
151
|
-
The destination is the ref's hash; the origin is the production DB's live
|
|
151
|
+
The destination is the ref's hash; the origin is the production DB's live contract signature. The command computes the path between them and applies each pending migration in order, advancing the signature.
|
|
152
152
|
|
|
153
153
|
`--db` is the environment selection knob. `--to` is the destination-hash knob. They're independent.
|
|
154
154
|
|
|
@@ -158,8 +158,8 @@ CI reports: *"the recorded ref `production` is at hash X; the live DB is at hash
|
|
|
158
158
|
|
|
159
159
|
The mismatch is a fact about *two pieces of state that disagree*. The investigation is the same regardless of which piece is wrong:
|
|
160
160
|
|
|
161
|
-
- **DB ahead of the ref.** Someone applied a migration outside CI without updating the ref in git. Re-record the ref with `prisma migration ref set <ref-name> <db-
|
|
162
|
-
- **DB behind the ref.** A previous deploy was rolled back, or the DB was restored from an older backup. Either re-apply forward with `prisma db migrate --to <ref-name> --db $URL`, or re-route the ref backward to match what's actually deployed with `prisma migration ref set <ref-name> <db-
|
|
161
|
+
- **DB ahead of the ref.** Someone applied a migration outside CI without updating the ref in git. Re-record the ref with `prisma migration ref set <ref-name> <db-signature-hash>` (commit + push); then audit how the out-of-band apply happened.
|
|
162
|
+
- **DB behind the ref.** A previous deploy was rolled back, or the DB was restored from an older backup. Either re-apply forward with `prisma db migrate --to <ref-name> --db $URL`, or re-route the ref backward to match what's actually deployed with `prisma migration ref set <ref-name> <db-signature-hash>`. The choice is the user's — name both options.
|
|
163
163
|
- **DB on a different branch.** An out-of-band schema change (manual SQL, ad-hoc migration) wrote something the migration graph doesn't model. Run `prisma db verify` to inspect the drift, then either `prisma contract infer` to re-derive the contract from the database, or edit the contract and run `prisma migration plan` so the database is the eventual destination.
|
|
164
164
|
|
|
165
165
|
`migration ref set` to silently align the ref with whatever the DB happens to be at is almost never the right move. It papers over drift that you'll pay for later.
|
|
@@ -173,9 +173,9 @@ The whole job is one command:
|
|
|
173
173
|
run: pnpm prisma db migrate --to staging --db "$STAGING_DATABASE_URL"
|
|
174
174
|
```
|
|
175
175
|
|
|
176
|
-
`db migrate` is safe to run unattended, by design. Before any operation runs it reads the live
|
|
176
|
+
`db migrate` is safe to run unattended, by design. Before any operation runs it reads the live contract signature and refuses with `MIGRATION.SIGNATURE_NOT_IN_GRAPH` if that hash is not a node in the on-disk graph, which is what a database changed outside the migration system looks like. Each operation then evaluates its own `precheck[]` and stops if the database is not in the state the operation expects. A successful run writes the destination hash as the new signature. Nothing runs before `db migrate` in the job.
|
|
177
177
|
|
|
178
|
-
`migration status --to staging --db $URL` is what a human or agent runs to answer *"what will run on deploy?"* before merging: it reports the path from the live
|
|
178
|
+
`migration status --to staging --db $URL` is what a human or agent runs to answer *"what will run on deploy?"* before merging: it reports the path from the live signature to the ref without changing anything. `db migrate --show --db $URL` gives the same path as an ordered preview; `migration log --db $URL` gives the applied history after a deploy.
|
|
179
179
|
|
|
180
180
|
`db migrate` is interactive-free and asks nothing — the questions about data loss are asked by `migration plan` when it writes the package, and by `db update` (see the `references/migrations.md` skill). Whatever the planner put in the migration graph is what `db migrate` runs; review happens at `migration plan` and at `migration status` time, before the apply step.
|
|
181
181
|
|
|
@@ -198,7 +198,7 @@ This skill is intentionally body-only; the underlying CLI reference (`prisma mig
|
|
|
198
198
|
|
|
199
199
|
## Checklist
|
|
200
200
|
|
|
201
|
-
- [ ] Named both the **origin** (live
|
|
201
|
+
- [ ] Named both the **origin** (live contract signature) and the **destination** (ref or contract head) for the question the user asked.
|
|
202
202
|
- [ ] Passed `--db $URL` whenever the question involves a specific environment.
|
|
203
203
|
- [ ] Passed `--to <name>` whenever the question is about deploying *to* a named environment, not just *from* the current branch's head.
|
|
204
204
|
- [ ] Read the `migration status` header (it names config, ref, database) and the summary line (it names the origin/destination distance) before reading the per-edge list.
|
|
@@ -11,7 +11,7 @@ The three-step user model:
|
|
|
11
11
|
|
|
12
12
|
Once the contract changes, you choose how the change reaches the database. This skill covers the two paths (`db update` and `migration plan` + `db migrate`), the migration-package contract, the `migration.ts` authoring API, and the failure modes you recover from without leaving the loop.
|
|
13
13
|
|
|
14
|
-
**Targets.** This reference covers migration authoring for **Postgres** and **Mongo**. The CLI reads the target from `prisma.config.ts` (set during `prisma orm init --target …`). Migration commands do not accept a `--target` flag — use a config scoped to the target you need.
|
|
14
|
+
**Targets.** This reference covers migration authoring for **Postgres** and **Mongo**. The CLI reads the target from `prisma.config.ts` (set during `prisma orm init --target …`). Migration commands do not accept a `--target` flag — use a config scoped to the target you need. Where the targets differ, the examples below say so: in imports, factories, transaction behavior, and where each target keeps its contract signatures.
|
|
15
15
|
|
|
16
16
|
## When to Use
|
|
17
17
|
|
|
@@ -20,7 +20,7 @@ Once the contract changes, you choose how the change reaches the database. This
|
|
|
20
20
|
- User wants to run pending migrations against a local DB.
|
|
21
21
|
- User hit `MIGRATION.HASH_MISMATCH`, `MIGRATION.UNFILLED_PLACEHOLDER`, or a partially-applied migration.
|
|
22
22
|
- User mentions: *migrate, migration, db push, db update, `prisma migrate dev`, `prisma migrate deploy`, drift, hash mismatch, data backfill*.
|
|
23
|
-
- A deploy or `db migrate` fails with `MIGRATION.
|
|
23
|
+
- A deploy or `db migrate` fails with `MIGRATION.SIGNATURE_NOT_IN_GRAPH` (older Composer releases: "no authored path"), or someone proposes resetting a database → *A database whose contract signature is not in the migration graph* below. For `MIGRATION.PATH_UNREACHABLE`, where the signature is in the graph but no migration reaches the target, plan from the signature to the target instead (`references/debug.md`).
|
|
24
24
|
|
|
25
25
|
## When Not to Use
|
|
26
26
|
|
|
@@ -45,10 +45,10 @@ Once the contract changes, you choose how the change reaches the database. This
|
|
|
45
45
|
- **`this.dataTransform(contract, name, { check, run })`.** The Postgres data-transform factory. `check` is a rowset query whose presence-of-any-row signals "work remains"; `run` is one or more mutation queries that perform the backfill. Both are lazy closures returning query plans built with the SQL query builder over the end contract. `contract` is the `contract` that `postgres({ contract: contractFromJson<End>(endContract) })` returns, not the imported `endContract` JSON the planner renders (see *Fill a placeholder*). The runner wraps `check` as `EXISTS(...)` for precheck and `NOT EXISTS(...)` for postcheck, so the same closure asserts both "there is work" and "the work is done".
|
|
46
46
|
- **`pendingPlaceholders`.** A boolean field on the JSON result of `migration plan`. `true` means the package was written but contains unfilled placeholders — `db migrate` will throw `MIGRATION.UNFILLED_PLACEHOLDER` until you edit `migration.ts` and self-emit.
|
|
47
47
|
- **`migrationHash`.** Content-addressed identity of a migration package. `MIGRATION.HASH_MISMATCH` fires when the stored hash in `migration.json` disagrees with the hash recomputed from the on-disk files (almost always: someone edited `migration.ts` without self-emitting).
|
|
48
|
-
- **
|
|
49
|
-
- **Apply atomicity.** **Postgres:** one `db migrate` run is one transaction — the runner issues a single `BEGIN`, applies every pending migration for every contract space, then one `COMMIT`; any failure issues `ROLLBACK` for the whole run, so the
|
|
48
|
+
- **Contract signature.** Records "this database is at contract hash X for space Y". **Postgres:** a row in `prisma.signatures`. **Mongo:** a document in the `_prisma_migrations` collection (keyed by space). Each successful migration advances the signature once schema verification passes for that space. `db sign` writes the signature from the current contract hash, but only after a schema-verification pass succeeds (it will not sign a database whose live schema disagrees with the contract).
|
|
49
|
+
- **Apply atomicity.** **Postgres:** one `db migrate` run is one transaction — the runner issues a single `BEGIN`, applies every pending migration for every contract space, then one `COMMIT`; any failure issues `ROLLBACK` for the whole run, so the signature stays where it was before the command. **Mongo:** DDL ops (`createCollection`, `createIndex`, `collMod`, `setValidation`, …) are not wrapped in a multi-document transaction; the runner applies ops, verifies the live schema against the destination contract, and advances the signature only on verify-pass (resumable across spaces — see the MongoDB family doc). Ordinary DDL + `dataTransform` flows stay consistent; partial state from failed mid-migration runs is diagnosed with `db verify` / `db schema`, not assumed away.
|
|
50
50
|
- **Changed foreign key actions and primary keys (Postgres).** A changed `onDelete`/`onUpdate` plans a drop and an add of the foreign key. A moved or removed primary key plans a drop (and an add), and the foreign keys that reference the old key are dropped first and added back after it. These ask no data-loss question.
|
|
51
|
-
- **Policies.** A database records how it may be changed (**Postgres:** in the one row of `prisma.config`; **Mongo** and the other SQL targets: in the application space's
|
|
51
|
+
- **Policies.** A database records how it may be changed (**Postgres:** in the one row of `prisma.config`; **Mongo** and the other SQL targets: in the application space's signature, under `meta.policies`): its *change policy* (`migrate`, `reconcile` or both; `reconcile` is what `db update` and `db sign` do) and its *data protection policy* (`dataLoss` and `accessWidening`, each `forbidden`, `with-consent` or `permitted`). Every command that changes a database obeys both. A ref declares the policies its database should have in a `policies` field. See *Policies: what a database says about how it may change* below.
|
|
52
52
|
- **Operation classes.** Every operation declares an `operationClass`: `additive`, `widening`, `data`, or `destructive`. `additive` adds structure and leaves existing structure and data as they are. `widening` changes existing structure without losing data; an operation that cannot keep every value fails instead, so a tightened constraint such as `SET NOT NULL` is widening. `destructive` can lose rows or values: dropping a table or column, or a type change that can change values. `data` reads and writes rows as its author wrote them, such as a backfill or a type conversion; a `dataTransform` is always `data`. Each operation factory sets its own class (`this.alterColumnType` is `data` with `using` and `destructive` without it, unless you pass `operationClass`). A `rawSql` step you write takes the class of the factory that would express it, or the class the definitions above give. The CLI surfaces these in the plan preview and in JSON output. There is no `long-running` class and the framework does not emit `CREATE INDEX CONCURRENTLY` — operations stay transactional.
|
|
53
53
|
|
|
54
54
|
## `migration.ts` is framework-rendered, not hand-authored
|
|
@@ -77,10 +77,10 @@ Treat the rendered import lines as framework-managed on both targets:
|
|
|
77
77
|
| `CLI.CONSENT_REQUIRED` | `migration plan` / `db update` run with nobody to answer (`--no-interactive`, CI, `--yes`) | The plan would lose data or (on `db update`) widen access. `meta.unanswered` and `nextActions` list each question with the flags that answer it: `--delete <subject>`, `--rename <subject>:<new name>`, `--allow <Model>`. Re-run with the ones you mean. `--confirm` and `--yes` answer none of them. |
|
|
78
78
|
| `CLI.CONSENT_UNUSED` | `migration plan` / `db update` | Every question was answered, and a `--delete` or `--allow` was left over: a typo, a subject the plan does not touch, or a `--confirm` (which consents to nothing). Fix or drop the flag. A typo next to a question nobody answered is reported as `CLI.CONSENT_REQUIRED` instead, which names the flag that matched nothing. On `db update --dry-run` the same mistake is `MIGRATION.STATEMENT_ANSWERS_NO_QUESTION`. |
|
|
79
79
|
| `MIGRATION.STATEMENT_DID_NOT_RESOLVE_LOSS` | A rename typed at the data-loss prompt | The plan was made again with the rename and still loses the subject's data. Answer with `delete`, or give a rename whose old name is the subject. |
|
|
80
|
-
| `CONTRACT.
|
|
80
|
+
| `CONTRACT.SIGNATURE_MISMATCH` | `db verify` (finding, exit 4) | The contract signature disagrees with the contract hash (**Postgres:** `prisma.signatures`; **Mongo:** `_prisma_migrations`). The DB is at a different contract version than the code thinks. Either run a migration forward, or — if the DB is correct and the signature is stale after a manual fix-up — run `db sign`. |
|
|
81
81
|
| `CONTRACT.PRISMA_SPACE_BEHIND` | `db verify`, `migration status`, `migration log`, dry runs; the client's first query (a warning, only when the client is given a `log`) | The records Prisma keeps for itself in the database are not up to date with the installed release, for example a database a release candidate set up, whose tables are in `prisma_contract`. Run the command the project already uses to change its database: `prisma db migrate` with migrations, `prisma db update` with `db update`, or `prisma db sign` if it only signs. Each brings the records up to date before its usual work. Then run the read again. |
|
|
82
82
|
| `MIGRATION.INSTALLED_SPACE_UNREACHABLE` | `db init`, `db update`, `db migrate`, `db sign`, `db verify` | The records Prisma keeps for itself were changed by a release this one cannot follow: `meta.reason` is `laterMajor` when a later major version of Prisma changed them, `unknownContract` otherwise. Use the release that last changed the database, or a newer one. Do not edit them by hand. |
|
|
83
|
-
| `CONTRACT.
|
|
83
|
+
| `CONTRACT.SIGNATURE_MISSING` | `db verify` (finding, exit 4), runtime startup (warning) | The DB has no signature yet. Run `prisma db init --db <url>` to baseline an empty database, `db update --db <url>` to apply the current contract directly, or `db sign --db <url>` if the schema already matches the contract. |
|
|
84
84
|
| `MIGRATION.STATEMENT_INVALID` | `migration plan` / `db update` with `--rename` | The statement is malformed, mixes a model and a field, renames something to itself, swaps two names, or repeats a name. The error's next step is the statement to type instead; use it. |
|
|
85
85
|
| `MIGRATION.STATEMENT_UNRESOLVED` | `migration plan` / `db update` with `--rename` | A name is not where a rename needs it. The error lists the names it found and says what to type: the statement the right way round, the order that works, or to leave out a rename that has already happened. |
|
|
86
86
|
| `MIGRATION.CHANGE_POLICY_FORBIDS` | `db update`, `db sign`, `db migrate` | The database's change policy does not include what the command does (`meta.change` lists what it permits). When `db update` or `db sign` is refused, the database changes only through migrations: follow its advice, which says to apply the migrations on disk that already lead to the target with `db migrate`, or to author one (with `migration plan`, or with `migration new` when the database is already at the target and lacks only invariants) and apply it with `db migrate`. Do not look for a way round the policy. |
|
|
@@ -94,7 +94,7 @@ Treat the rendered import lines as framework-managed on both targets:
|
|
|
94
94
|
| Moving a database whose history does not need to be kept (local, development, staging, preview) to the contract | `db update` | Fast, no migration files. Works whether or not the database is shared. |
|
|
95
95
|
| A change other developers or environments will receive | `migration plan` + `db migrate` | Replayable, reviewable, content-hashed. |
|
|
96
96
|
| A database that changes only through migrations, such as production | `migration plan` + `db migrate` | It must run a reviewed, hashed migration. |
|
|
97
|
-
| A deploy says there is no migration path, or `MIGRATION.
|
|
97
|
+
| A deploy says there is no migration path, or `MIGRATION.SIGNATURE_NOT_IN_GRAPH` | See *A database whose contract signature is not in the migration graph* | Never reset the database. |
|
|
98
98
|
| Adding a column that needs a backfill | `migration plan --backfill Model.field` (writes `placeholder`), edit `migration.ts`, self-emit, then `db migrate` | `db update` does not author data transforms; the formal path does. Without `--backfill`, existing rows get a temporary value. |
|
|
99
99
|
| Changing a field's type so values may not survive | `migration plan --convert Model.field`, fill `using`, self-emit, `db migrate` | Or `--delete Model.field` to let the database cast; the cast may cut or round values (Postgres cuts a longer text to a shorter `varchar`), and a value it cannot cast fails the apply. |
|
|
100
100
|
| Recovering from drift (DB diverged from contract) | `db sign` after manual fix, *or* `migration plan` if Prisma 8 can plan the fix | Depends on which side is right. See *Recover from drift* below. |
|
|
@@ -146,13 +146,13 @@ pnpm prisma migration plan --name my_change
|
|
|
146
146
|
|
|
147
147
|
If the `db` ref's pointer is itself missing and the hash isn't a graph node either (`MIGRATION.SNAPSHOT_MISSING`), create it with `migration ref set db <hash>` or advance it with `db update --advance-ref db`.
|
|
148
148
|
|
|
149
|
-
**After `db migrate` with `--db`, with `--no-advance-ref` or in CI.** The live
|
|
149
|
+
**After `db migrate` with `--db`, with `--no-advance-ref` or in CI.** The live contract signature advances and the `db` ref does not. The `db` ref records where development plans start, so move it only for your development database, never for a deployment database. On the development database, run the same `db migrate` again with `--advance-ref db`, without `--no-advance-ref`: it applies nothing and moves the ref to the contract the database is at. If that run ended at the empty contract (`--to @empty`, or a rollback of the first migration with `--to <first-migration-dir>^`), no ref can name it and `--advance-ref db` is refused with `MIGRATION.REF_TARGET_EMPTY`; remove the stale ref with `migration ref delete db` instead.
|
|
150
150
|
|
|
151
151
|
**When to switch paths.** Use `db update` while the schema is in flux, on a database whose migration history does not need to be kept (a local, development, staging or preview database). Switch to `migration plan` + `db migrate` when the change needs a reviewable, replayable migration — typically before opening a PR, and always for a database that changes only through migrations, such as production. The `db` ref bridges the two: it captures dev iteration state on disk so the first formal plan knows where you left off.
|
|
152
152
|
|
|
153
153
|
**Graph-node rule (plan time).** Any hash used as a `from` end — explicit `--from`, default `db` ref, or ref name — must already be a node in the on-disk migration graph once the graph is non-empty. The auto-baseline two-bundle emission is the one exception: it applies only on an **empty** graph with a non-null ref-resolved `from` and an available store entry. If the ref's pointer is missing and the hash isn't a graph node either, plan refuses with `MIGRATION.SNAPSHOT_MISSING` instead.
|
|
154
154
|
|
|
155
|
-
**Apply-time complement.** `db migrate` reads the live
|
|
155
|
+
**Apply-time complement.** `db migrate` reads the live signature before DDL. If the signed contract hash is not a graph node, the command refuses with `MIGRATION.SIGNATURE_NOT_IN_GRAPH` — catching drift the offline planner cannot see. This is separate from `MIGRATION.SIGNATURE_NOT_IN_GRAPH`, a warning `migration status` gives when the database's contract signature names no contract in the migration graph. See `references/migration-review.md` for the full diagnostic catalog.
|
|
156
156
|
|
|
157
157
|
`db` is a **default ref name**, not a reserved one. The framework overwrites it on the next dev cycle; you may `migration ref set db <hash>` explicitly and accept that a subsequent `db update` replaces it when run against the default URL.
|
|
158
158
|
|
|
@@ -172,7 +172,7 @@ pnpm prisma db update --db $DATABASE_URL --dry-run
|
|
|
172
172
|
pnpm prisma db update --db $DATABASE_URL
|
|
173
173
|
```
|
|
174
174
|
|
|
175
|
-
`db update` already verifies schema and advances the
|
|
175
|
+
`db update` already verifies schema and advances the contract signature on success — a follow-up `db verify` is redundant on the happy path. Use `db verify` only when you need a standalone diagnostic (see *Verify contract vs DB*).
|
|
176
176
|
|
|
177
177
|
Inspect the JSON output to drive the next move:
|
|
178
178
|
|
|
@@ -180,11 +180,11 @@ Inspect the JSON output to drive the next move:
|
|
|
180
180
|
pnpm prisma db update --db $DATABASE_URL --json
|
|
181
181
|
```
|
|
182
182
|
|
|
183
|
-
The JSON contains `plan.operations[]` with each `operationClass`, plus (in apply mode) `execution.operationsExecuted` and the post-apply `
|
|
183
|
+
The JSON contains `plan.operations[]` with each `operationClass`, plus (in apply mode) `execution.operationsExecuted` and the post-apply `signature.storageHash`. If the command was refused because nobody answered its questions, the error is `CLI.CONSENT_REQUIRED`, and its `meta.unanswered[]` lists each subject with the flags that answer it.
|
|
184
184
|
|
|
185
185
|
## Workflow — `migration plan` + `db migrate` (formal path)
|
|
186
186
|
|
|
187
|
-
The concept: `migration plan` writes a new migration package on disk. If the planner needed any data transforms, the package is *pending* — `migration.ts` holds `placeholder(...)` calls until you fill them in. `db migrate` runs every pending package in graph order — on Postgres inside one transaction for the whole run; on Mongo op by op with verify-gated
|
|
187
|
+
The concept: `migration plan` writes a new migration package on disk. If the planner needed any data transforms, the package is *pending* — `migration.ts` holds `placeholder(...)` calls until you fill them in. `db migrate` runs every pending package in graph order — on Postgres inside one transaction for the whole run; on Mongo op by op with verify-gated contract signature advancement (see *Apply atomicity* above).
|
|
188
188
|
|
|
189
189
|
Plan a change:
|
|
190
190
|
|
|
@@ -210,7 +210,7 @@ pnpm prisma migration show migrations/app/20260515T1200_add_user_email
|
|
|
210
210
|
`migration show` displays a single migration package. To see the ordered list of migrations that would run — across all contract spaces — use `db migrate --show`:
|
|
211
211
|
|
|
212
212
|
```bash
|
|
213
|
-
# Online: reads the
|
|
213
|
+
# Online: reads the database's contract signature as the origin.
|
|
214
214
|
pnpm prisma db migrate --show --db $DATABASE_URL
|
|
215
215
|
|
|
216
216
|
# Offline: hypothetical path from any ref or hash.
|
|
@@ -391,7 +391,7 @@ Self-emit the same way: `node <package dir>/migration.ts`.
|
|
|
391
391
|
|
|
392
392
|
**The rule.** A statement that inserts, updates or deletes rows, or selects rows to decide what to write, goes in a data transform (`dataTransform`), never in a `rawSql` step. `rawSql` is for DDL that no operation factory expresses. DDL includes statements that convert stored values as part of a schema change, such as `ALTER COLUMN … TYPE … USING` and SQLite's table recreation: use the operation factory (`this.alterColumnType`, `this.recreateTable`). A `rawSql` step you write carries a precheck and a postcheck that test the live schema, and the class *Operation classes* under *Key Concepts* describes.
|
|
393
393
|
|
|
394
|
-
**Why.** Migrations form a graph (`references/migration-model.md`), and a migration is an edge. `db migrate` can run a migration on any database whose
|
|
394
|
+
**Why.** Migrations form a graph (`references/migration-model.md`), and a migration is an edge. `db migrate` can run a migration on any database whose contract signature is at its `from` hash, however that database got there. Those databases share a schema but not their rows: on one the work is already done, on another it was never needed. A data transform stays correct on all of them for two reasons:
|
|
395
395
|
|
|
396
396
|
- **`check` is the guard.** The runner skips the transform when `check` finds no rows (the work is done or was never needed), runs `run` otherwise, and fails the migration if `check` still finds rows afterwards. `check` is optional in the type, but a transform without it runs `run` on every database and can never refuse, so always write it.
|
|
397
397
|
- **On Postgres, the queries are checked against a contract.** Self-emit checks each query plan against the contract passed to `this.dataTransform` and refuses a mismatch with `MIGRATION.DATA_TRANSFORM_CONTRACT_MISMATCH`.
|
|
@@ -415,7 +415,7 @@ For any other gap, offer to report it through `references/feedback.md`. Then let
|
|
|
415
415
|
|
|
416
416
|
### How a transform refuses bad data
|
|
417
417
|
|
|
418
|
-
Write `check` to find the rows the transform must fix. If `run` leaves any of them behind, for example rows whose values have no valid mapping, the postcheck fails and the migration stops with `MIGRATION.POSTCHECK_FAILED`. On Postgres `meta.failedCheck.operationId` names the transform. On Mongo `meta.operationId` and `meta.name` do. On Postgres the whole run rolls back. On Mongo nothing is undone: the documents `run` already changed stay changed, and operations that ran earlier stay applied; only the
|
|
418
|
+
Write `check` to find the rows the transform must fix. If `run` leaves any of them behind, for example rows whose values have no valid mapping, the postcheck fails and the migration stops with `MIGRATION.POSTCHECK_FAILED`. On Postgres `meta.failedCheck.operationId` names the transform. On Mongo `meta.operationId` and `meta.name` do. On Postgres the whole run rolls back. On Mongo nothing is undone: the documents `run` already changed stay changed, and operations that ran earlier stay applied; only the contract signature does not advance. So on Mongo, write `run` so it is safe to run again, for example by filtering on the documents that still need the change. A SQLite transform has no `check`, so it cannot refuse this way. Do not add a raw step that raises an error. If the user wants the offending rows named, run a read-only query that selects them before migrating.
|
|
419
419
|
|
|
420
420
|
## Type changes and new required fields
|
|
421
421
|
|
|
@@ -473,29 +473,29 @@ There is no built-in filter flag — pipe the JSON through `jq` (or your favouri
|
|
|
473
473
|
|
|
474
474
|
## Workflow — Verify contract vs DB (diagnostic)
|
|
475
475
|
|
|
476
|
-
The concept: `db verify` is a **standalone diagnostic** — not a routine step after `db update` or `db migrate` on the happy path (those commands already verify and advance the
|
|
476
|
+
The concept: `db verify` is a **standalone diagnostic** — not a routine step after `db update` or `db migrate` on the happy path (those commands already verify and advance the contract signature when they succeed). Reach for `db verify` when you suspect drift or need to prove the DB matches the contract:
|
|
477
477
|
|
|
478
478
|
- Following manual SQL or ad-hoc edits outside Prisma 8.
|
|
479
479
|
- When restoring a database from backup.
|
|
480
480
|
- If a `db migrate` fails or partially applies (especially on Mongo, where DDL is resumable rather than transaction-wrapped).
|
|
481
|
-
- When `CONTRACT.
|
|
481
|
+
- When `CONTRACT.SIGNATURE_MISMATCH` / `CONTRACT.SIGNATURE_MISSING` surfaces at runtime or from another command.
|
|
482
482
|
|
|
483
483
|
Modes:
|
|
484
484
|
|
|
485
|
-
- Default — full verification (schema +
|
|
486
|
-
- `--
|
|
487
|
-
- `--schema-only` — skip
|
|
485
|
+
- Default — full verification (schema + signature).
|
|
486
|
+
- `--signature-only` — skip schema verification, only check the signature.
|
|
487
|
+
- `--schema-only` — skip signature verification, only check schema satisfies contract.
|
|
488
488
|
- `--strict` adds: schema elements not present in the contract are an error (default is "DB may have extras").
|
|
489
489
|
|
|
490
490
|
```bash
|
|
491
491
|
pnpm prisma db verify --db $DATABASE_URL
|
|
492
492
|
```
|
|
493
493
|
|
|
494
|
-
`db verify` exits `0` when everything matches, `4` when it ran and found something, and `2` only when it could not run. Findings ride the completed envelope as `error` diagnostics: `CONTRACT.
|
|
494
|
+
`db verify` exits `0` when everything matches, `4` when it ran and found something, and `2` only when it could not run. Findings ride the completed envelope as `error` diagnostics: `CONTRACT.SIGNATURE_MISMATCH`, `CONTRACT.SIGNATURE_MISSING`, `CONTRACT.TARGET_MISMATCH`, `CONTRACT.SCHEMA_VERIFICATION_FAILED` (with `meta.schemaIssues` listing the schema diff issues).
|
|
495
495
|
|
|
496
496
|
## Policies: what a database says about how it may change
|
|
497
497
|
|
|
498
|
-
Every database records two policies, and every command obeys them. On Postgres they are in `prisma.config`; on the other targets they are in the application space's
|
|
498
|
+
Every database records two policies, and every command obeys them. On Postgres they are in `prisma.config`; on the other targets they are in the application space's contract signature. Read them from the error that refuses you, or with `prisma migration status --to <ref> --db <url>`, which reports where the ref's declared policies differ from the database's.
|
|
499
499
|
|
|
500
500
|
**Change policy.** The strategies the database may be changed by:
|
|
501
501
|
|
|
@@ -504,7 +504,7 @@ Every database records two policies, and every command obeys them. On Postgres t
|
|
|
504
504
|
| `migrate` | Walk the migration graph, running recorded migrations | `db migrate`, a Composer deploy |
|
|
505
505
|
| `reconcile` | Plan and apply the difference to a contract, then sign | `db update`, `db sign` |
|
|
506
506
|
|
|
507
|
-
A database that records nothing permits both. Production records `["migrate"]`, so `db update` and `db sign` refuse it with `MIGRATION.CHANGE_POLICY_FORBIDS`. The off-graph error (`MIGRATION.
|
|
507
|
+
A database that records nothing permits both. Production records `["migrate"]`, so `db update` and `db sign` refuse it with `MIGRATION.CHANGE_POLICY_FORBIDS`. The off-graph error (`MIGRATION.SIGNATURE_NOT_IN_GRAPH`) reads the policy and gives only the recovery it permits.
|
|
508
508
|
|
|
509
509
|
**Data protection policy.** `dataLoss` and `accessWidening`, each `data-loss-forbidden` / `data-loss-with-consent` / `data-loss-permitted` (and the `access-widening-` forms). `with-consent` is the default and is today's behaviour: `db update` asks, and a migration carries the consent given when it was planned. Every command enforces them before it runs anything:
|
|
510
510
|
|
|
@@ -554,21 +554,21 @@ Write the field by hand, or with the `migration ref policy` commands, which chan
|
|
|
554
554
|
|
|
555
555
|
No other command changes a ref's policies. Commands that rewrite a ref (`migration ref set`, `db update`, `db sign`, `db migrate`, and the `migration ref policy` commands) keep the `hash`, `invariants` and `policies` they do not change, and write `formatVersion` themselves. A ref file with any other field is refused with `MIGRATION.INVALID_REF_FILE`, and the file is left as it was: remove the field by hand.
|
|
556
556
|
|
|
557
|
-
**Applying a declared policy.** `db migrate --to <ref>` and `db update --to <ref>` compare the ref's declarations with the database before running anything. If they differ, the command fails with `MIGRATION.POLICY_MISMATCH` and nothing runs. The database's policy changes only when the deploy is told it may: `prisma db migrate --to production --permit-policy-change --db <url>`. The run is checked against the ref's policies, runs, and records them in the database (on Postgres in `prisma.config`, elsewhere in the
|
|
557
|
+
**Applying a declared policy.** `db migrate --to <ref>` and `db update --to <ref>` compare the ref's declarations with the database before running anything. If they differ, the command fails with `MIGRATION.POLICY_MISMATCH` and nothing runs. The database's policy changes only when the deploy is told it may: `prisma db migrate --to production --permit-policy-change --db <url>`. The run is checked against the ref's policies, runs, and records them in the database (on Postgres in `prisma.config`, elsewhere in the signature) when it succeeds, so a failed run leaves the old policy. With nothing pending, the run writes only the policies. A pipeline that should apply reviewed policy changes passes the flag on every deploy; a cautious team leaves it out and applies policy changes by hand. The flag needs `--to <ref>`: with a hash, `@db`, `@empty` or no `--to`, the command fails with `CLI.INVALID_ARGUMENTS` before it connects. A ref that declares no policies is accepted and changes nothing, so a pipeline can pass the flag on every deploy.
|
|
558
558
|
|
|
559
559
|
The flag is consent, like `--delete`. It is for the person who owns the database and reviewed the ref change. Never add it to make your own deploy pass, and never change a database's or a ref's policies, by hand or with `migration ref policy set` or `delete`, to get a deploy, a plan or `db update` past a refusal or a mismatch: the policy is there to stop exactly that.
|
|
560
560
|
|
|
561
|
-
## Workflow —
|
|
561
|
+
## Workflow — Sign the database again
|
|
562
562
|
|
|
563
|
-
The concept: `db sign` rewrites the
|
|
563
|
+
The concept: `db sign` rewrites the signature to the current contract hash and moves the `db` ref to it (`--advance-ref <name>` overrides the ref name; `--db` does not suppress the ref write; `--no-advance-ref` skips it). Use after a manual repair where the DB is the source of truth and the signature is stale. `db sign` performs a schema-verify first and refuses to sign a DB whose schema disagrees with the contract — so a successful sign always means the schema matches and the signature is now correct.
|
|
564
564
|
|
|
565
565
|
```bash
|
|
566
566
|
pnpm prisma db sign --db $DATABASE_URL
|
|
567
567
|
```
|
|
568
568
|
|
|
569
|
-
## Workflow — A database whose
|
|
569
|
+
## Workflow — A database whose contract signature is not in the migration graph
|
|
570
570
|
|
|
571
|
-
**The symptom.** `db migrate` or a deploy fails with `MIGRATION.
|
|
571
|
+
**The symptom.** `db migrate` or a deploy fails with `MIGRATION.SIGNATURE_NOT_IN_GRAPH`: the database's signature names a contract that no migration in `migrations/` starts or ends at. (Composer releases older than this skill print it as `MIGRATION_PATH_NOT_FOUND`, "no authored path from the database's current schema".)
|
|
572
572
|
|
|
573
573
|
**The usual cause.** The database applied a migration that was later planned again or deleted. The common case is a branch deployed to a shared environment, then rebased: each new plan of its migration has a new target hash, and the version the database applied is gone. The error's `why` names the last contract in the graph the database applied (`meta.lastGraphHash`) and the applied migrations that are no longer on disk (`meta.missingMigrations`).
|
|
574
574
|
|
|
@@ -591,25 +591,25 @@ Reconcile it to the target with `db update`:
|
|
|
591
591
|
|
|
592
592
|
### When the database changes only through migrations (production)
|
|
593
593
|
|
|
594
|
-
Author migrations that bring it back onto the graph, and deploy them. The
|
|
594
|
+
Author migrations that bring it back onto the graph, and deploy them. The contract signature's contract is `<signed contract hash>`; the last graph contract is `meta.lastGraphHash`. When the error has no `lastGraphHash`, the ledger shows no contract the database applied that is still in the graph, or could not be read: check with `prisma migration log`, and if no applied contract is in the graph, stop and ask a person.
|
|
595
595
|
|
|
596
596
|
`migration plan --to` accepts only contracts already in the graph, so the database's contract goes through the contract source:
|
|
597
597
|
|
|
598
|
-
1. Commit or copy aside any uncommitted edits to the contract source; step 4 restores it from `HEAD`. Then put the contract the database is at into the contract source. Prefer the contract source as it was when the deleted migration was planned: find the commit with `git log --all --oneline -- migrations/snapshots/<
|
|
599
|
-
2. `prisma contract emit`, and check that the emitted storage hash is `<
|
|
598
|
+
1. Commit or copy aside any uncommitted edits to the contract source; step 4 restores it from `HEAD`. Then put the contract the database is at into the contract source. Prefer the contract source as it was when the deleted migration was planned: find the commit with `git log --all --oneline -- migrations/snapshots/<signed contract hash>` and check out the contract source file from it. If git no longer has it, infer it from the database into a separate file, `prisma contract infer --db $DATABASE_URL --output ./inferred.prisma` (without `--output` it overwrites the contract source), then copy that file over the contract source.
|
|
599
|
+
2. `prisma contract emit`, and check that the emitted storage hash is `<signed contract hash>`. If it is not, stop and ask a person.
|
|
600
600
|
3. Plan a migration from the last graph contract to the database's contract: `prisma migration plan --from <lastGraphHash> --name rejoin_<database>`. Nothing will run it against this database; it only puts the database's contract in the graph. A fresh database could still run it, so copy the data transforms of every migration in `meta.missingMigrations` into it, in ledger order (`prisma migration log`), from the git commits that held them, and review them.
|
|
601
|
-
4. Restore the contract source (`git checkout HEAD -- <contract source>`; without `HEAD` git restores the version step 1 staged), run `prisma contract emit`, then plan from the database's contract to the target: `prisma migration plan --from <
|
|
601
|
+
4. Restore the contract source (`git checkout HEAD -- <contract source>`; without `HEAD` git restores the version step 1 staged), run `prisma contract emit`, then plan from the database's contract to the target: `prisma migration plan --from <signed contract hash> --name <slug>`. A plan that loses data needs `--delete` or `--rename` (see *Answer the data-loss questions*). Review it like any migration, and add data transforms for any data the deleted migration's replacement would have moved.
|
|
602
602
|
5. Check how a fresh database reaches the target: `prisma migration status --from @empty --to <target>` lists the migrations it would run. Path finding takes the shortest route, so if these two migrations make a shorter route from the last graph contract to the target than the main line, a new database would take it. When they do, ask a person how to proceed.
|
|
603
603
|
6. Commit both migrations and deploy.
|
|
604
604
|
|
|
605
|
-
Do not `db sign` the database to a contract you inferred: that rewrites its
|
|
605
|
+
Do not `db sign` the database to a contract you inferred: that rewrites its signature without a migration, and a database whose change policy permits only migrations refuses it.
|
|
606
606
|
|
|
607
607
|
## Workflow — Recover from drift
|
|
608
608
|
|
|
609
|
-
The concept: drift means `db verify` reports the live DB schema doesn't match what the
|
|
609
|
+
The concept: drift means `db verify` reports the live DB schema doesn't match what the contract signature says it should be. Two valid moves, picked by which side is correct:
|
|
610
610
|
|
|
611
611
|
- **The contract is right; the DB is wrong** → run a migration. Either `db update`, on a database whose migration history does not need to be kept (a local, development, staging or preview database), or `migration plan` + `db migrate`, which every database accepts and a database that changes only through migrations, such as production requires.
|
|
612
|
-
- **The DB is right; the contract or
|
|
612
|
+
- **The DB is right; the contract or signature is wrong** → edit the contract to match the DB (see `references/contract.md`), emit, then `db sign` to refresh the signature. The sign also moves the `db` ref to the signed hash; when the migration graph is non-empty and that hash is not a graph node, the next default `migration plan` refuses with `MIGRATION.HASH_NOT_IN_GRAPH` (see *The forgot-the-flag pitfall* above for the recovery).
|
|
613
613
|
|
|
614
614
|
The diagnostic that reveals which side is right:
|
|
615
615
|
|
|
@@ -622,7 +622,7 @@ Use `db verify` to confirm which side is wrong, then re-run it after either bran
|
|
|
622
622
|
|
|
623
623
|
## Workflow — Recover from a partially-applied migration
|
|
624
624
|
|
|
625
|
-
The concept: on **Postgres**, the whole `db migrate` run is one transaction — a failure anywhere rolls back every migration the run had applied, and the
|
|
625
|
+
The concept: on **Postgres**, the whole `db migrate` run is one transaction — a failure anywhere rolls back every migration the run had applied, and the contract signature stays where it was before the command. On **Mongo**, DDL is resumable with verify-gated signature advancement; diagnose with `db verify` / `db schema`, fix the failed package's `migration.ts`, self-emit, and re-run `db migrate`.
|
|
626
626
|
|
|
627
627
|
Failures that *can* leak partial state: Mongo DDL that partially applied before verify failed, and external side-effects (calls out to other systems from a `run` closure). On Postgres nothing runs outside the transaction — `rawSql(...)` steps are ordinary steps inside it and roll back with the rest.
|
|
628
628
|
|
|
@@ -704,8 +704,8 @@ In a terminal the command asks each question in turn; type `delete`, `allow`, or
|
|
|
704
704
|
8. **Renaming a model or field without a statement.** The planner cannot tell a rename from a drop and a create, so without a statement it plans a destructive drop+add. State the rename on the command line: `migration plan --name <slug> --rename User:Person --rename Person.email:Person.emailAddress`, or the same `--rename` flags on `db update`. A field is named through its model as the new contract names it. The planner then renames the table or column and the constraints and indexes named after it; on MongoDB it renames the collection, and the field in every document that holds it (only in that variant's documents for a variant's field). On MongoDB a field is named by its name in the contract, as on SQL: `id @map("_id")` is `User.id`. A statement that keeps the stored name, such as `--rename User.name:User.title` where both are stored as `display_name`, plans nothing; one that changes it renames the field in the documents. A model or field whose name stays and whose `@@map` or `@map` changes needs no statement, on MongoDB as on SQL (see pitfall 16).
|
|
705
705
|
9. **Planning with no `db` ref and no `--from` in a project that already has migrations.** The origin falls through to the empty database, which would make the plan a full-create migration; `migration plan` refuses with `MIGRATION.PLAN_ORIGIN_UNKNOWN` rather than writing it. Pick the exit that matches your intent — the error lists them, and `references/migration-model.md` § *The trap* explains which to choose.
|
|
706
706
|
10. **Hand-authoring `migration.ts` from a blank file, or rewriting the rendered import line.** Migration files are framework-rendered — let `prisma migration plan` (or `migration new`) render the package, then edit only the holes the framework leaves for you, and, until [prisma/orm#30504](https://github.com/prisma/orm/issues/30504) is fixed, the first argument of `this.dataTransform` (see pitfall 7). On Postgres leave the rendered `@prisma/orm-postgres/migration` (or `@prisma/orm-sqlite/migration`) import path alone; on Mongo leave `@prisma/orm-mongo/target/migration` as rendered. Add symbols to the existing import line rather than introducing new import paths.
|
|
707
|
-
12. **Replaying migrations onto a database that is already ahead.** `db migrate` on a database with no
|
|
708
|
-
13. **Running Prisma 7 `migrate` commands against Prisma 8.** Each one answers `CLI.V7_COMMAND` with its Prisma 8 command: `migrate dev` is `contract emit`, `migration status` (which prints the `migration plan` that takes the database to the new contract), running that `migration plan`, then `db migrate`; when migrations on disk already lead to the new contract, `migration status` prints no plan, so skip that step and run `db migrate`; `migrate deploy` is `db migrate`; `migrate reset` has no equivalent, because Prisma 8 has no reset: `db update` brings the database to the contract instead, asking before it loses data, but it keeps existing rows and runs no seed steps or data transforms (a database that changes only through migrations is moved with `db migrate`); `migrate status` is `migration status`; `migrate diff` is `db update --dry-run`, or `migration plan` to write a migration package; `migrate resolve` is `db sign <migration>`, which moves the database
|
|
707
|
+
12. **Replaying migrations onto a database that is already ahead.** `db migrate` on a database with no contract signature runs every migration, skipping operations already applied. When the database is already past a migration (it has `x int8` where the migration adds `x int4`), the run stops at that migration's precheck with `MIGRATION.PRECHECK_FAILED`. Adopt such a database with `prisma db sign` (after `contract infer` if needed), not by replaying history.
|
|
708
|
+
13. **Running Prisma 7 `migrate` commands against Prisma 8.** Each one answers `CLI.V7_COMMAND` with its Prisma 8 command: `migrate dev` is `contract emit`, `migration status` (which prints the `migration plan` that takes the database to the new contract), running that `migration plan`, then `db migrate`; when migrations on disk already lead to the new contract, `migration status` prints no plan, so skip that step and run `db migrate`; `migrate deploy` is `db migrate`; `migrate reset` has no equivalent, because Prisma 8 has no reset: `db update` brings the database to the contract instead, asking before it loses data, but it keeps existing rows and runs no seed steps or data transforms (a database that changes only through migrations is moved with `db migrate`); `migrate status` is `migration status`; `migrate diff` is `db update --dry-run`, or `migration plan` to write a migration package; `migrate resolve` is `db sign <migration>`, which moves the database's contract signature to that migration after checking its schema, but leaves `migration status` without an applied mark. While Prisma 7 still owns the migrations, install Prisma 7's CLI with `npm install --save-dev @prisma/prisma7@7` and run every one of them except `migrate diff`, whose replacement only reads, as `prisma7 migrate <command>` instead; `migrate resolve` runs as `prisma7 migrate resolve --applied <migration>`.
|
|
709
709
|
14. **Changing rows outside a data transform.** A `rawSql` step that inserts, updates or deletes rows, or a Postgres transform whose query comes from `db.raw.sql` or contains `fns.raw`. Write it in a `dataTransform` (with a `check` on Postgres and Mongo); on Postgres, build its queries with the SQL query builder. *Data changes go in a data transform* explains why. If the builder cannot express it, stop (see *When the SQL query builder cannot express the transform*).
|
|
710
710
|
15. **A data transform without `check` (Postgres, Mongo).** It runs `run` on every database, including those where the work is already done, and can never refuse bad data. Always write `check`.
|
|
711
711
|
16. **Passing a statement for a changed `@@map` or `@map`.** A model or field that keeps its name is the same model or field, so when only `@@map` or `@map` changes, `migration plan` and `db update` rename the table or column, and its constraints and indexes, with no question and no statement. This needs a snapshot of the contract the database is at, and a table whose control policy is `managed` in both contracts. Without a snapshot, the change is planned as a drop and a create and asked about, as before, except a table name whose only change is a capital first letter (`users` to `Users`): that is refused with `MIGRATION.TABLE_NAME_CASE_CHANGED`, whose message gives the steps to rename the table; for a table that is not `managed`, nothing is renamed, and the plan is what that control policy allows. `--rename User:User` is refused with `MIGRATION.STATEMENT_INVALID`, and a `--delete User` left in a script from earlier releases fails with `CLI.CONSENT_UNUSED`. To get an empty table under the new name instead, remove the model in one change and add it back in a second. A rename the planner cannot order is refused with `MIGRATION.PLANNING_FAILED`: two models or fields that swap tables or columns, a chain where one moves to a name another frees, a model that takes the table of a removed one, and a rename statement that moves something into the old name. The message gives two plans through a name nothing uses (`prisma_swap_<name>`), or, for a takeover, a first plan that removes the model or field holding the name; follow it. One swap is not refused by `migration plan`: when two tables or columns of the same shape swap names and nothing else changes, the storage does not change, so `migration plan` reports no change and writes nothing, and the rows are then read as the other model's; `db update` refuses it. Make such a swap through a name nothing uses in the same way. The table is renamed only when everything stored in it moves, so a variant that gains or loses a table of its own is still asked about, as a data migration. MySQL plans no renames, so there a changed `@@map` is still a drop and a create. MongoDB does the same with collections, document keys (in every place an embedded model is stored) and enum stored values. Its operations run one at a time with no transaction, so it also refuses enum values that shift along a chain, and `--rename` of a model whose collection another model shares; each message gives its route.
|
|
@@ -7,7 +7,7 @@ This skill takes the user from zero (or near-zero) to a first working query agai
|
|
|
7
7
|
|
|
8
8
|
- **First-touch orientation** — the user has arrived at a Prisma 8 project for the first time (a scaffold tool like `npx createprisma` dropped them in, they cloned a teammate's repo, or they ran `prisma orm init` themselves and now want to make their first move) and they're asking *"what can I do with Prisma 8?"*, *"where do I start?"*, or *"what's next?"*. The goal is to anchor them on the contract, get them connected to a database, round-trip one row, and let further commands surface organically.
|
|
9
9
|
- **Greenfield** — new project, fresh database. User runs `prisma orm init` themselves. `init` seeds a starter contract with a sample model, so the path joins the first-touch orientation arc as soon as the database is initialised.
|
|
10
|
-
- **Brownfield-DB** — existing database, no contract yet. Infer the contract from the database with `contract infer`, sign the
|
|
10
|
+
- **Brownfield-DB** — existing database, no contract yet. Infer the contract from the database with `contract infer`, sign the database with `db sign`, then write queries against one of the existing tables.
|
|
11
11
|
|
|
12
12
|
This skill does **not** cover migrating from another ORM (Drizzle, Prisma 6/7, Sequelize, TypeORM, Kysely, Knex, raw drivers). Those are separately-installable skills.
|
|
13
13
|
|
|
@@ -37,7 +37,7 @@ This skill does **not** cover migrating from another ORM (Drizzle, Prisma 6/7, S
|
|
|
37
37
|
- **Why the application lists them.** The application must have exactly one copy of each. Prisma does not accept a value that another copy of its own code created, and a package manager takes a peer dependency only from the application's own list. A monorepo whose applications are on different Prisma releases can still get two copies under npm workspaces and under Bun's hoisted linker; keep such applications on one release, or use pnpm, Yarn or Bun's isolated linker.
|
|
38
38
|
- **Yarn Plug'n'Play.** `prisma orm init` does not support it. With Yarn, set `nodeLinker: node-modules` in `.yarnrc.yml` first.
|
|
39
39
|
- **`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.
|
|
40
|
-
- **
|
|
40
|
+
- **Contract signature**: a row in the `prisma.signatures` 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).
|
|
41
41
|
|
|
42
42
|
### Canonical on-disk layout
|
|
43
43
|
|
|
@@ -109,7 +109,7 @@ If that prints `[{ id: 1, email: 'alice@example.com' }]`, the project is wired e
|
|
|
109
109
|
- The contract source exists at `src/prisma/contract.{prisma,ts}` (a starter model from `init`, or the inferred contract from `contract infer`, or whatever the bootstrap tool generated).
|
|
110
110
|
- `src/prisma/db.ts` exists and instantiates the runtime with the emitted contract.
|
|
111
111
|
- `DATABASE_URL` is set in `.env` (or wherever the runtime's config tells it to look).
|
|
112
|
-
- The database has been initialised (`db init`) or
|
|
112
|
+
- The database has been initialised (`db init`) or signed (`db sign`), so its contract signature exists and the schema matches the contract.
|
|
113
113
|
|
|
114
114
|
The three workflows below each describe how their path gets the user to that state. After that, the arc above is the same.
|
|
115
115
|
|
|
@@ -135,7 +135,7 @@ Before saying anything specific to the user, read:
|
|
|
135
135
|
- The contract source the config declares (canonically `src/prisma/contract.prisma` or `src/prisma/contract.ts`; a project scaffolded by an older init may have it at `prisma/contract.{prisma,ts}` instead — check the `contract` field of the config) — what starter models, if any, exist.
|
|
136
136
|
- `src/prisma/db.ts` (next to the contract) — the runtime entry point.
|
|
137
137
|
- `.env` / `.env.example` — is `DATABASE_URL` set, or only the example?
|
|
138
|
-
- Optionally `pnpm prisma db verify` — does the live DB match the contract? (Exit `4` with findings means drift or no
|
|
138
|
+
- Optionally `pnpm prisma db verify` — does the live DB match the contract? (Exit `4` with findings means drift or no contract signature; `2` means it could not run.)
|
|
139
139
|
|
|
140
140
|
Then **say the contract path back to the user, with its role attached**. Something like: *"Your contract is at `src/prisma/contract.prisma`, and it currently declares a `User` model. The contract describes your app — every query type, migration, and runtime type the framework gives you flows from this file. Let's get your app connected to a database next."* The exact wording is up to the agent; what matters is that the user leaves the first response knowing *where the contract is* and *that it is the source of truth*.
|
|
141
141
|
|
|
@@ -144,8 +144,8 @@ Then **say the contract path back to the user, with its role attached**. Somethi
|
|
|
144
144
|
The motivation is *"so your app can actually run against your database"*, not *"so the prerequisite checklist passes"*. The mechanics depend on what's already in place from Step 1:
|
|
145
145
|
|
|
146
146
|
- **Everything already wired.** Go straight to writing and reading a row (see *Your first arc — connect, write, read* above). Adapt the snippet to whatever model the contract declares.
|
|
147
|
-
- **`DATABASE_URL` not set.** Have the user set it in `.env` (not in `prisma.config.ts` — see Pitfall 5). Then `pnpm prisma db init` to apply the current contract to that database and write the
|
|
148
|
-
- **Database is connectable but not yet aware of the contract** (
|
|
147
|
+
- **`DATABASE_URL` not set.** Have the user set it in `.env` (not in `prisma.config.ts` — see Pitfall 5). Then `pnpm prisma db init` to apply the current contract to that database and write the contract signature row. Now the app can connect.
|
|
148
|
+
- **Database is connectable but not yet aware of the contract** (signature row missing; `db verify` reports drift). Run `pnpm prisma db init`. (`db update` is the alternative for quick dev cycles — it's looser, doesn't write a migration history, and is what users reach for when they want to iterate on the schema fast. Mention it if the user asks how to make schema changes flow to the DB; don't pre-explain it.)
|
|
149
149
|
- **Contract is empty** (bootstrap left the source blank). Add **one** model with **two** fields (e.g. `User { id, email }`), `pnpm prisma contract emit`, then `pnpm prisma db init`. Minimal — get the round-trip working, *then* extend.
|
|
150
150
|
|
|
151
151
|
The user encounters `db init` (and optionally `db update`, `contract emit`) here because they're the commands their current move *requires*. They learn what those commands are by using them.
|
|
@@ -214,7 +214,7 @@ The flags `init` accepts (run `prisma orm init --help` for the source of truth):
|
|
|
214
214
|
After init succeeds, the path converges on *Your first arc — connect, write, read* above. `init` has already seeded a starter contract with `User` and `Post` models (with a relation between them) and run `contract emit` once; the only remaining prerequisites are setting `DATABASE_URL` and initialising the database. Two commands:
|
|
215
215
|
|
|
216
216
|
1. Set `DATABASE_URL` in `.env` (copy from `.env.example`).
|
|
217
|
-
2. Initialise the database: `pnpm prisma db init`. Creates tables, indexes, constraints, and writes the
|
|
217
|
+
2. Initialise the database: `pnpm prisma db init`. Creates tables, indexes, constraints, and writes the contract signature row — using the starter contract `init` generated.
|
|
218
218
|
|
|
219
219
|
Then run the snippet from *Your first arc* above against the `User` model. When the user is ready to extend the contract — add more models, change fields, add relations — chain to `references/contract.md`. For more queries, chain to `references/queries.md`.
|
|
220
220
|
|
|
@@ -222,7 +222,7 @@ Then run the snippet from *Your first arc* above against the `User` model. When
|
|
|
222
222
|
|
|
223
223
|
## Workflow — Brownfield-DB (existing database, no contract)
|
|
224
224
|
|
|
225
|
-
The concept: against an existing database with no Prisma 8 contract, `contract infer` walks the live schema (tables, columns, indexes — including expression and partial ones — constraints, and RLS enablement + policies) and writes a PSL contract that describes it. Where authoring would generate a CHECK constraint the database does not carry (the element-non-null check on a list column), infer writes the list with nullable elements (`String?[]`), which derives no such check, so the contract declares exactly what the database enforces. The reverse gap is closed too: a hand-written CHECK constraint the database enforces that authoring would never have generated comes back as `@@check(expression: <reprint>, map: "<name>")`, so it is a declared object from the first pull instead of an invisible extra a later destructive plan could drop. That inferred check warns (`PN_EXACT_NAME_BODY_COMPARISON`) the next time you run `contract emit` — expected, not a defect: the warning fires on any `map:` body regardless of who wrote it, and the comparison stays sound because both sides are Postgres's own reprint. Columns come back as the convenience types with their defaults, and only the arguments that differ: `int2` as `Int(storage: int2)`, `numeric(10,2)` as `Decimal(precision: 10, scale: 2)`, `varchar(12)` as `String(storage: varchar, length: 12)`, `json` as `Json`, `jsonb` as `Json(storage: jsonb)`, `timestamptz(3)` as `DateTime` (a JavaScript `Date`), a `timestamptz` with no declared precision as `DateTime(precision: 6)`, `timestamp(3)` as `DateTime(storage: timestamp)`, `date` as `Date`, `time` as `Time` and `interval` as `Duration` (ISO strings). A `Date` holds milliseconds, so a timestamp column whose values use microseconds reads with them dropped: change such a field to `DateTime(as: temporal)` or `DateTime(as: string)` to keep them. The result is a *starting point*, not the final contract — review and clean it up, then `db sign` to record the current contract hash as the
|
|
225
|
+
The concept: against an existing database with no Prisma 8 contract, `contract infer` walks the live schema (tables, columns, indexes — including expression and partial ones — constraints, and RLS enablement + policies) and writes a PSL contract that describes it. Where authoring would generate a CHECK constraint the database does not carry (the element-non-null check on a list column), infer writes the list with nullable elements (`String?[]`), which derives no such check, so the contract declares exactly what the database enforces. The reverse gap is closed too: a hand-written CHECK constraint the database enforces that authoring would never have generated comes back as `@@check(expression: <reprint>, map: "<name>")`, so it is a declared object from the first pull instead of an invisible extra a later destructive plan could drop. That inferred check warns (`PN_EXACT_NAME_BODY_COMPARISON`) the next time you run `contract emit` — expected, not a defect: the warning fires on any `map:` body regardless of who wrote it, and the comparison stays sound because both sides are Postgres's own reprint. Columns come back as the convenience types with their defaults, and only the arguments that differ: `int2` as `Int(storage: int2)`, `numeric(10,2)` as `Decimal(precision: 10, scale: 2)`, `varchar(12)` as `String(storage: varchar, length: 12)`, `json` as `Json`, `jsonb` as `Json(storage: jsonb)`, `timestamptz(3)` as `DateTime` (a JavaScript `Date`), a `timestamptz` with no declared precision as `DateTime(precision: 6)`, `timestamp(3)` as `DateTime(storage: timestamp)`, `date` as `Date`, `time` as `Time` and `interval` as `Duration` (ISO strings). A `Date` holds milliseconds, so a timestamp column whose values use microseconds reads with them dropped: change such a field to `DateTime(as: temporal)` or `DateTime(as: string)` to keep them. The result is a *starting point*, not the final contract — review and clean it up, then `db sign` to record the current contract hash as the contract signature (instead of letting `db init` try to recreate the schema from scratch). By default `db sign` also sets the `db` ref and stores the contract snapshot, so the next `migration plan` chains from the adopted schema — even when the database is named with `--db`. `--advance-ref <name>` writes another ref instead and `--no-advance-ref` writes none; in either case the next plan needs `--from` or a `db` ref you set yourself.
|
|
226
226
|
|
|
227
227
|
```bash
|
|
228
228
|
mkdir my-app && cd my-app
|
|
@@ -250,7 +250,7 @@ Then re-emit and sign:
|
|
|
250
250
|
|
|
251
251
|
```bash
|
|
252
252
|
pnpm prisma contract emit
|
|
253
|
-
pnpm prisma db sign # writes the
|
|
253
|
+
pnpm prisma db sign # writes the contract signature and sets the db ref
|
|
254
254
|
pnpm prisma db verify # exit 0 immediately after a pull; exit 4 with findings if the DB drifts later
|
|
255
255
|
```
|
|
256
256
|
|
|
@@ -304,7 +304,7 @@ This skill is intentionally body-only; `prisma orm init --help`, `contract infer
|
|
|
304
304
|
|
|
305
305
|
- [ ] Confirmed which path applies (first-touch orientation / greenfield / brownfield) before proposing commands.
|
|
306
306
|
- [ ] **First-touch orientation:** named the contract path back to the user and framed its role (*source of truth from which query types, migrations, and runtime types flow*) before proposing any commands.
|
|
307
|
-
- [ ] **All paths:** brought the project to the *Your first arc* prerequisites (config, contract source, `db.ts`, `DATABASE_URL`,
|
|
307
|
+
- [ ] **All paths:** brought the project to the *Your first arc* prerequisites (config, contract source, `db.ts`, `DATABASE_URL`, contract signature row) *before* writing application code.
|
|
308
308
|
- [ ] **All paths:** ran the first arc — one `create` + one `select` against the starter (or inferred) model — and got the round-trip working green.
|
|
309
309
|
- [ ] **All paths:** did *not* edit the contract source as part of the first arc. Schema extension is the *next* move, not the first.
|
|
310
310
|
- [ ] **All paths:** did *not* lead with a feature tour, capability inventory, or recital of CLI commands. Commands surfaced as the user's current move required them.
|
|
@@ -314,7 +314,7 @@ This skill is intentionally body-only; `prisma orm init --help`, `contract infer
|
|
|
314
314
|
- [ ] **All paths (application projects):** the project ended up in the canonical `src/prisma/contract.{prisma,ts}` + `src/prisma/db.ts` + `migrations/app/` layout (what `init` scaffolds by default). An extension or aggregate-root package keeps its own `src/contract.{prisma,ts}` + `migrations/<timestamp>_<slug>/` layout — do not relocate it.
|
|
315
315
|
- [ ] **Brownfield path:** ran `contract infer --db "$DATABASE_URL" --output src/prisma/contract.prisma`, reviewed the result, then `contract emit` + `db sign` (which by default also sets the `db` ref, so the next `migration plan` chains from the adopted schema; not with `--no-advance-ref` or `--advance-ref <name>`).
|
|
316
316
|
- [ ] Set `DATABASE_URL` in `.env` and confirmed the value is reachable.
|
|
317
|
-
- [ ] Initialised the DB (`db init` greenfield / first-touch orientation) or signed the
|
|
317
|
+
- [ ] Initialised the DB (`db init` greenfield / first-touch orientation) or signed the database (`db sign` brownfield — by default sets the `db` ref too, with or without `--db`).
|
|
318
318
|
- [ ] Did NOT hand-edit `contract.json` or `contract.d.ts`.
|
|
319
319
|
- [ ] Did NOT set `DATABASE_URL` in `prisma.config.ts`.
|
|
320
320
|
- [ ] Confirmed the user understands what the *next* skill is for their workflow (typically `references/queries.md` for more queries, then `references/contract.md` when they're ready to extend the schema).
|
|
@@ -309,7 +309,7 @@ Order matters: `beforeEncode` runs in registration order for every middleware be
|
|
|
309
309
|
|
|
310
310
|
## Workflow — Configure the connection
|
|
311
311
|
|
|
312
|
-
The concept: the runtime takes one of three binding shapes — `url`, `pg` (a pre-constructed `pg.Pool` or `pg.Client`), or `binding` (an explicit kind tag). They're mutually exclusive. The `pg` form is for projects that already manage their own pool (e.g. a Lambda layer); `url` is the default. Pool tuning is `poolOptions.connectionTimeoutMillis` / `poolOptions.idleTimeoutMillis` / `poolOptions.max` (pool size, 10 by default) — *not* `driverOptions`. Behind a server-side connection pooler, `poolOptions: { max: 1 }` keeps one connection; queries then take turns on it, so a query waits while a transaction is open. Inside `db.transaction(async (tx) => …)` send every query through `tx`: with one connection, a query through `db` waits for the connection its own transaction holds and fails after `connectionTimeoutMillis`. Reads are buffered by default; setting `cursor` (`{ batchSize: 100 }`; `{}` or `{ batchSize: undefined }` for batches of 100; a `batchSize` that is not a positive integer fails the factory call) makes them stream through a server-side cursor, and there is no flag that turns cursors off (see `references/queries.md` § *Streaming*). `postgresServerless()` takes the same `cursor` option. Pass `log` (an object with `info`, `warn`, `error` and an optional `debug`; `console` works, and the type is `Log` from `@prisma/orm-postgres/family-runtime`) to receive what the runtime logs: the
|
|
312
|
+
The concept: the runtime takes one of three binding shapes — `url`, `pg` (a pre-constructed `pg.Pool` or `pg.Client`), or `binding` (an explicit kind tag). They're mutually exclusive. The `pg` form is for projects that already manage their own pool (e.g. a Lambda layer); `url` is the default. Pool tuning is `poolOptions.connectionTimeoutMillis` / `poolOptions.idleTimeoutMillis` / `poolOptions.max` (pool size, 10 by default) — *not* `driverOptions`. Behind a server-side connection pooler, `poolOptions: { max: 1 }` keeps one connection; queries then take turns on it, so a query waits while a transaction is open. Inside `db.transaction(async (tx) => …)` send every query through `tx`: with one connection, a query through `db` waits for the connection its own transaction holds and fails after `connectionTimeoutMillis`. Reads are buffered by default; setting `cursor` (`{ batchSize: 100 }`; `{}` or `{ batchSize: undefined }` for batches of 100; a `batchSize` that is not a positive integer fails the factory call) makes them stream through a server-side cursor, and there is no flag that turns cursors off (see `references/queries.md` § *Streaming*). `postgresServerless()` takes the same `cursor` option. Pass `log` (an object with `info`, `warn`, `error` and an optional `debug`; `console` works, and the type is `Log` from `@prisma/orm-postgres/family-runtime`) to receive what the runtime logs: the contract-signature-verification warnings `CONTRACT.SIGNATURE_MISSING` and `CONTRACT.SIGNATURE_MISMATCH` from the client's first use of the database (its first query, connection or transaction), the warnings `lints()` emits for rules whose severity is `warn`, and the errors a middleware's `activityEnded` or `activityFinalized` hook throws, which the runtime logs and swallows. If `log` has a `debug` method, it also receives debug events, for example when a middleware intercepts a statement. `budgets()` violations reach `log` only in `mode: 'permissive'` (see *Lints and budgets middleware*). Without `log`, the runtime logs to the console: errors to `console.error` and warnings to `console.warn`, which in Node write to standard error, info events to `console.info`, and debug events nowhere. To silence it, pass a logger that does nothing: `log: { info() {}, warn() {}, error() {} }`. `postgresServerless()`, `sqlite()` and `supabase()` take the same option.
|
|
313
313
|
|
|
314
314
|
```typescript
|
|
315
315
|
// Default — URL string, factory constructs the pool.
|
|
@@ -322,7 +322,7 @@ postgres({
|
|
|
322
322
|
// max: 10, // optional: the most connections the pool opens
|
|
323
323
|
},
|
|
324
324
|
// cursor: { batchSize: 100 }, // optional — stream reads in batches instead of buffering
|
|
325
|
-
// log: logger, // optional — where
|
|
325
|
+
// log: logger, // optional — where contract signature and lints() warnings go; the console by default
|
|
326
326
|
});
|
|
327
327
|
|
|
328
328
|
// BYO pool — pass a pg.Pool you already created.
|