Repository navigation
Releases
v8.0.0-rc.25
v8.0.0-rc.25
A database can now record how it may change and what data it protects, and the CLI refuses a migration or update that breaks those rules. MariaDB gets a client of its own, and MySQL gains the ORM's aggregates. Int, BigInt, Float, Decimal, String, Boolean, Bytes and Json are convenience types on every database. SQL clients run nested transactions with tx.transaction(callback), and an ORM write inside a transaction is atomic. On PostgreSQL and SQLite, a changed @@map, @map or enum stored value is planned as a rename. Nested writes gain onConflict, variants of a polymorphic model, a disconnect that applies its criteria, and update and delete of one related row. prisma orm init --target takes any target package by name.
The upgrade recipes for this hop: the app recipe and the extension recipe. Each breaking change below names the change ids to look for in them. The examples write the ORM client as db.orm.public.<Model>, the PostgreSQL form; on SQLite, MySQL and MariaDB it is db.orm.<Model>. After upgrading, run prisma contract emit once: the generated contract.d.ts now imports from one module of the target package, SQL contracts record two new capabilities, and MySQL and MariaDB contracts gain aggregate types.
Breaking changes
-
pgand@types/pgare peer dependencies.@prisma/orm-postgres,@prisma/orm-target-postgresand@prisma/orm-extension-supabaseno longer install their own copy ofpgand@types/pg. Add"pg": "^8.22.0"to your dependencies and"@types/pg": "^8.20.0"to your dev dependencies before you install the upgrade. This fixes aPoolfrom your ownpgnot being accepted by the client when the two@types/pgversions differed. Seepg-is-a-peer-dependencyin the app recipe and the extension recipe, andextension-importing-pg-peers-itin the extension recipe. (#31060) -
temporal-polyfillmust be 1.0.8 or later. Every database package that requirestemporal-polyfillas a peer dependency now requires^1.0.8, where it required^1.0.4. A project or extension package that pins an older 1.0.x version updates it. Seetemporal-polyfill-peer-range-moves-to-1-0-8in the app recipe and the extension recipe. (#31045) -
PostgreSQL connections no longer set
lc_monetary=C. This lets a pooled Prisma Postgres URL connect. If you usemoneycolumns, runSHOW lc_monetaryas the application's role, outside Prisma. If it is notC,POSIXoren_US, runALTER ROLE <role> SET lc_monetary = 'C'before you deploy the upgrade; otherwise amoneyread fails withRUNTIME.LC_MONETARY_NOT_C. Under a locale with no or three fraction digits, writes made before the change are stored wrong, so make the change first. Seepostgres-lc-monetary-not-setin the app recipe. (#31081) -
The config type is
PrismaConfig. The typedefineConfigreturns is renamed fromPrismaNextConfigtoPrismaConfig, with no alias. The language server's diagnosticPRISMA_NEXT_INTERPRETATION_FAILEDis nowPRISMA_INTERPRETATION_FAILED. Seeconfig-type-renamed-to-prisma-configin the app recipe and the extension recipe. (#31062)Before:
import type { PrismaNextConfig } from '@prisma/orm-toolchain/cli/config-types'; const config: PrismaNextConfig<'sql', 'postgres'> = defineConfig({ /* ... */ });
After:
import type { PrismaConfig } from '@prisma/orm-toolchain/cli/config-types'; const config: PrismaConfig<'sql', 'postgres'> = defineConfig({ /* ... */ });
-
Generated files import from the module the target package names. A generated
contract.d.tsnow imports all its types from one module, such as@prisma/orm-postgres/contract-types; runprisma contract emitto regenerate it. A config that you assemble from the framework's owndefineConfig, not a target package's, must setcontract.typesModuleandmigrations.module, or commands fail withCONFIG.CONTRACT_TYPES_MODULE_MISSINGandCONFIG.MIGRATION_MODULE_MISSING. Control API callers passtypesModuletoemitandrenderContractDts, and theprojectDiroption is gone.@prisma/orm-toolchain/publish-surfaceand its two sub-entries are removed. Extension authors: the emitter, migration renderer and MySQL config factory take the module names too. Seecontract-types-import-from-the-target-package,hand-assembled-config-names-generated-file-modules,control-api-takes-types-moduleandtoolchain-publish-surface-entrypoints-removedin the app recipe, andtarget-package-names-generated-file-modules,extension-config-names-generated-file-modules,family-imports-are-import-requirements,migration-renderer-takes-the-migration-module,emitter-takes-the-types-module,mysql-config-components-carry-family-and-modules,control-api-takes-types-module,component-type-import-module-is-not-a-literal-typeandtoolchain-publish-surface-entrypoints-removedin the extension recipe. (#31078) -
On PostgreSQL and SQLite, a changed stored name is planned as a rename. When a model, field or enum member keeps its name and only its
@@map,@mapor stored value changes,migration plananddb updatenow rename the table or column, or replace the stored value, without asking. A script that passed--deletefor such a change now fails withCLI.CONSENT_UNUSED; remove the flag. To get an empty table under the new name, remove the model in one migration and add it back in the next. Swaps, chains and takeovers of table and column names are refused withMIGRATION.PLANNING_FAILED, and so are enum members that swap stored values or take the stored value of a removed member; make them in two migrations: the first moves every name involved to a name nothing uses, and the second moves them to the final names. Chains of enum stored values are planned. A table that still has the lowered name an earlier release gave a model with no@@mapis renamed to the model name; add@@mapto keep the old name. MySQL and MongoDB plan these changes as before. Seesql-stored-name-change-is-a-rename,sql-stored-name-delete-is-unused,sql-stored-name-empty-table,sql-stored-name-swaps-refusedandsql-lowered-table-names-renamedin the app recipe. Extension authors who call the SQL family's statement planning seeschema-tables-same-name,plan-statements-plans-stored-name-renames,subjects-of-calls-storage-renamesandstored-value-keep-data-edit-removedin the extension recipe. (#31088)Before:
prisma migration plan --name move-users --delete User
After:
prisma migration plan --name move-users
-
sql.String(n)is nowsql.Varchar(n), and PostgreSQL'sjsonColumnisplainJsonColumn.sql.String(n)still works as a deprecated alias that warns withPSL_DEPRECATED_SCALAR_NAME, in PSL and astype.sql.String(n)in TypeScript. The PostgreSQL column helperjsonColumnis removed; importplainJsonColumn. No contract changes. Seepsl-renamed-sql-string,ts-renamed-sql-stringandts-renamed-postgres-json-column-helperin the app recipe, andts-postgres-explicit-json-typein the extension recipe. (#31065)Before:
model Label { id Int @id name sql.String(50) }
After:
model Label { id Int @id name sql.Varchar(50) }
-
On MongoDB,
Int64is nowInt64BigInt.Int64still works in PSL as a deprecated alias that warns. In a TypeScript contract,type.Int64()is removed; writetype.BigInt()ortype.Int64BigInt(). No contract changes. Seepsl-renamed-mongo-int64andts-removed-mongo-int64-helperin the app recipe and the [extension recipe](https://github.com/prisma/...
v8.0.0-rc.24
v8.0.0-rc.24
MongoDB gets the convenience date and time types, and Date becomes a calendar date. A MongoDB TypeScript contract names a field's type with type.X(), as PSL does, and MongoDB clients can prepare a query. MongoDB plans check documents before a validator change and ask about type changes that can lose values. SQL clients take transaction isolation levels and callback timeouts. The CLI manages MariaDB, and answers Prisma 7 commands such as prisma migrate dev with what to run instead. Nested create() and update() gain arrays of operations and filtered updateAll and deleteAll, and db.raw.sql embeds builder queries.
The upgrade recipes for this hop: the app recipe and the extension recipe. Each breaking change below names the change ids to look for in them. The app recipe opens with the order to do the steps in. After upgrading, run prisma contract emit once, so a contract that an extension such as Supabase stamps with its version matches the installed package (contract-artifacts-restamp in the app recipe).
Breaking changes
-
On MongoDB,
Dateis a calendar date.Dateis now stored as a BSON date at midnight UTC and read as a string such as"2024-02-29".DateTimeis whatDatewas: an instant read as a JavaScriptDate.DateTime(as: temporal),TimeandDurationare new. RewriteDatetoDateTimein MongoDB schemas with the script the app recipe ships; the contract does not change. A field you miss still compiles, but@onCreate(now())on it then writes today's date at midnight UTC and loses the time.temporal-polyfillis now a required peer dependency of@prisma/orm-mongoand@prisma/orm-target-mongo; a project that installs with Yarn, or with npm andlegacy-peer-deps, adds it to its dependencies. Seemongo-date-is-a-calendar-date,temporal-polyfill-is-a-peer-dependency-of-mongoandtemporal-polyfill-with-legacy-peer-depsin the app recipe. (#30989)Before:
model Order { id ObjectId @id @map("_id") paidAt Date }
After:
model Order { id ObjectId @id @map("_id") paidAt DateTime }
-
A MongoDB TypeScript contract names a field's type with
type.X().field.objectId(),field.string(),field.date(),field.vector(),field.scalar(codecId)and the other MongoDB field helpers are removed. Writefield.scalar(type.X()), wheretypecomes from thedefineContractcallback, as PSL names the type. The app recipe ships a script that rewrites them; the contract does not change. MongoDB PSL gainsVectorandVector(length), and a type that takes no arguments, written with one, such asString(5), is now refused. Extension authors whose extension has its own MongoDB codec add a type constructor underauthoring.type. Seemongo-fields-take-a-typein the app recipe and the extension recipe. (#30959)Before:
fields: { _id: field.objectId(), embedding: field.vector({ typeParams: { length: 3 } }), raw: field.scalar('mongo/bson@1'), }
After:
fields: { _id: field.scalar(type.ObjectId()), embedding: field.scalar(type.Vector(3)), raw: field.scalar(type.Bson()), }
-
MongoDB plans rewrite the documents a schema change touches. A validator change that
migration planordb updatewrites now checks every document first, and the apply stops withMIGRATION.PRECHECK_FAILEDwhile a document does not fit the new validator. A field type change that can lose values is now a question, answered with--convertor--delete, as on SQL. A new required field is filled with a temporary value in the documents that lack it, unless--backfillnames it. Existingmigration.tsfiles are unchanged. Seemongo-validator-change-checks-documents,mongo-type-change-is-askedandmongo-new-required-field-gets-temporary-valuein the app recipe. (#30970) -
MySQL no longer sets every session to READ COMMITTED. A callback transaction with no isolation level now uses the server or session default. If your code relied on READ COMMITTED, pass
transactionOptions: { isolationLevel: 'ReadCommitted' }to the MySQL client, or pass it totransaction(callback, options). Transactions the ORM opens for its own writes still use READ COMMITTED. Extension authors forward the isolation options through their SQL transaction wrappers. Seemysql-explicit-isolation-defaultin the app recipe andforward-sql-transaction-optionsin the extension recipe. (#30990) -
@prisma/orm-postgres/migrationno longer exports the free functionscreateExtensionanddataTransform. Neither could be called correctly from amigration.ts. Call the methods on the migration class instead:this.createExtension({ extension: 'btree_gist' })andthis.dataTransform(endContract, name, { check, run }). The migration'sops.jsondoes not change. Seecreate-extension-not-exportedanddata-transform-not-exportedin the app recipe. (#30988) -
Prisma 7 commands fail with
CLI.V7_COMMAND.prisma generate,validate,format,studio,db pull,db push,db seed,db executeand the sixprisma migratecommands now fail withCLI.V7_COMMANDinstead ofCLI.COMMAND_MOVED, still with exit code 2. The error names the Prisma 8 commands to run instead, or links the CLI docs when Prisma 8 has none, and says how to install Prisma 7's CLI as@prisma/prisma7to keep running the old command. The toolchain now requires@prisma/[email protected]; a project that depends on it itself moves to0.10.0. Seeprisma-7-commands-answer-v7-commandandengine-pin-moves-to-0-10-0in the app recipe. (#31027) -
The CLI's
--jsonoutput lists planner warnings underplannerWarnings.db update --jsonanddb init --jsonlist the planner's warnings underplannerWarningsinstead ofwarnings, asmigration plan --jsondoes. Seeplanner-warnings-json-fieldin the app recipe. (#30970) -
Raw SQL parts can hold a statement. The
partsofRawExprandRawQueryAstcan now hold aSelectAst,InsertAst,UpdateAstorDeleteAst. Code that walkspartsand treats every non-string part as an expression must handle the four statement kinds. Seeraw-parts-hold-statement-astsin the app recipe and the extension recipe. (#30991) -
PostgreSQL: a statement on a
pgclient that lost its connection is refused. A statement on a pooled connection, on a held connection, and in a transaction or savepoint, including itsBEGIN,COMMIT,ROLLBACKand savepoint statements, and before each later step of a cursor, now rejects withDRIVER.NOT_CONNECTEDand the message "Postgres connection is no longer usable." when itspgclient lost its connection: the client emittederrororendafter the driver first used it, a driver gave up on it, orpgmarks it ended or broken. Before, the statement was sent to the client. On a driver given onepg.Clientthat has already lost its connection, a query, and the start of a transaction or held connection, were already refused at 8.0.0-rc.23 with "Postgres connection lost or closed. Create a new client to reconnect.", and still are; the new message comes on a connection or transaction taken before the loss. The driver keeps this state for the client object, so code that recovers a lost connection by patching the samepgclient, for example by replacing itsquerymethod, stops working: release the client and take a new one from the pool, or create a newpg.Client. (#31012) -
Extension authors: runtime transactions carry an
AbortSignal. Runtime connection and activity wrappers takeRuntimeTransactionOptionsand forward them unchanged, and every hand-writtenRuntimeTransaction, test doubles included, exposes asignal. Seeruntime-transaction-signalin the extension recipe. (#31012)...
v8.0.0-rc.23
v8.0.0-rc.23
MongoDB indexes carry their names, and migrations create and drop each index by its name. On PostgreSQL, Int, BigInt, Float, Decimal, String, Boolean and Bytes become convenience types, and SQLite and MySQL get the convenience date and time types. The pgvector, PostGIS, ParadeDB and citext packs find their extension through the search path, so db sign adopts a Supabase database. MySQL gets ORM writes. mongo() takes extension packs, and supabase() takes the options postgres() takes. Prisma ORM no longer refuses to start when it is loaded from more than one copy.
The upgrade recipes for this hop: the app recipe and the extension recipe. Each breaking change below names the change ids to look for in them. The app recipe opens with the order to do the steps in. After upgrading, run prisma contract emit once, so a contract that an extension such as Supabase stamps with its version matches the installed package (contract-artifacts-restamp in the app recipe).
Breaking changes
-
MongoDB indexes carry their names. Every index of a MongoDB contract records the name MongoDB stores it under, so every MongoDB contract with an index gets a new storage hash. An index written without a name is named after its keys, such as
email_1, the name earlier releases already gave it in the database, so no database changes. Migrations create and drop each index by that name, and an operation id names the index, as inindex.users.create(email_1). Two indexes of one collection that would get one name, such as a unique and a sparse index onemail, are refused; name one of them. A contract read withprisma6Schema()names each index as Prisma 6 did, such asUser_email_key. Runprisma contract emit, run the script the app recipe ships to name the indexes of your migration snapshots, then runprisma db signor plan a migration, which has no operations. Extension authors:MongoIndex,MongoSchemaIndexand their input types take a requiredname,CreateIndexCallandDropIndexCalltake the index's name and options, and code that callsbuildMongoContractFromDefinitioncallsnameIndexesfirst. Seemongo-contracts-record-index-names,mongo-unnamed-indexes-with-one-name-refused,mongo-prisma6-index-namesandmongo-index-operations-by-namein the app recipe, andmongo-index-name-required,mongo-index-calls-take-nameandmongo-build-refusal-index-name-duplicatein the extension recipe. (#30952)Before:
createIndex('users', [{ field: 'email', direction: 1 }], { unique: true }),
After:
createIndex('users', [{ field: 'email', direction: 1 }], { name: 'email_1', unique: true }),
-
The Prisma 6 MongoDB reader keeps indexes as Prisma 6 wrote them.
prisma6Schema()no longer merges indexes. Two indexes of one model with the same fields and the same written sort are refused withPSL.PRISMA6_MONGO_INDEX_ALREADY_EXISTS, as Prisma 6 refuses them. A unique and a plain index on the same keys that Prisma 6 accepts are both kept, so the contract gets a new storage hash; runprisma db signagain. Prisma 8 PSL and TypeScript still merge identical and redundant indexes. Extension authors: the MongoDB contract builder no longer merges indexes,BuildRefusalhas the kindindexDuplicateagain, andmergeRedundantIndexesmerges before building. Seemongo-prisma6-indexes-as-prisma6-reads-themin the app recipe, andmongo-build-refusal-index-duplicate-restoredin the extension recipe. (#30921) -
The pgvector, PostGIS, ParadeDB and citext packs find their extension through the search path. Each pack declares its extension in the unbound namespace, so
db signanddb verifyaccept the extension in any schema on the connection's search path, such as Supabase'sextensions. A project that composes one of these packs runsprisma contract emit, which writes the pack's new migration, and thenprisma db migrate, which applies it without changing the database. An application may no longer declare an extension that a composed pack declares; remove its ownextension vector {}block orextension('vector')handle. Extension authors: a pack declares its Postgres extension in the unbound namespace, or the configuration is refused withCONTRACT.PACK_CONTRIBUTION_INVALID. Seepack-extension-found-on-search-pathandremove-pack-extension-declarationin the app recipe, andpack-declares-extension-unboundin the extension recipe. (#30956) -
mongo()andmongoStatic()refuse a contract whose extension packs they are not given. They take anextensionsoption, aspostgres()does. A MongoDB project whoseprisma.config.tscomposes extension packs passes each pack's runtime descriptor tomongo({ extensions })andmongoStatic({ extensions }); otherwise they fail withRUNTIME.MISSING_EXTENSION_PACK. A MongoDBcontract.jsonmust have"target"; every contractprisma contract emitwrites has it. Extension authors:createMongoExecutionContextchecks the contract against the stack, a MongoDB descriptor declares each codec once as a codec descriptor instead of in acodecs()slot, andmongoStandardCodecsandbuildStandardCodecRegistryare removed. Seemongo-client-takes-extensionsandmongo-contract-requires-targetin the app recipe, andmongo-execution-context-checks-contract-requirements,mongo-codecs-declared-onceandmongo-standard-codecs-removedin the extension recipe. (#30943)Before:
export const db = mongo({ contract, url });
After:
import myPack from 'my-mongo-pack/runtime'; export const db = mongo({ contract, url, extensions: [myPack] });
-
supabase()andpostgres()check their database input when they are called. A wrong input fails withRUNTIME.BINDING_INVALIDat once, not on the first query. Passing bothurlandpgtosupabase()fails; before,pgwon silently. An emptyurl, or one that is notpostgres://orpostgresql://, fails; before, an empty one connected with thePG*environment variables or to localhost.nullaspg,urlorbindingfails, even beside another input, so leave the option out instead. Abindingof an unknown kind fails.supabase()refuses apg.Clientwith the message "Supabase takes a pg.Pool or a url, not a pg.Client". Seesupabase-one-binding-inputandpostgres-checks-database-inputin the app recipe. (#30920)Before:
postgres({ contract, url: process.env['DATABASE_URL'] ?? null });
After:
const url = process.env['DATABASE_URL']; postgres({ contract, ...(url === undefined ? {} : { url }) });
-
On PostgreSQL, seven scalar type names are deprecated, and two column helpers are renamed.
SmallInt,BigIntNumber,Numeric,UnboundedInt,Real,VarCharandVarBitstill work but report the warningPSL_DEPRECATED_SCALAR_NAME. Write the convenience type that gives the same type instead, such asString(storage: varchar, length: 12)forVarChar(12); the contract does not change. The same TypeScript helpers, such astype.VarChar(...), are deprecated too. The column helpersint8ColumnandnumericColumnare renamedint8BigIntColumnandnumericStringColumn, and the old names are removed. Extension authors:postgresScalarAuthoringTypes,postgresNativeAuthoringTypesandpostgresScalarAndNativeTypeConstructorsare replaced bypostgresScalarTypesandpostgresExplicitTypes. Seepsl-renamed-postgres-scalar-types,ts-renamed-postgres-scalar-helpersandts-renamed-postgres-column-helpersin the app recipe, and the same ids plusts-renamed-postgres-type-groupingsin the extension recipe. (#30942)Before:
model Account { id Int @id visits SmallInt price Numeric(10, 2) code VarChar(12) }
After:
model Account { id Int @id visits Int(storage: int2) price Decimal(precision: 10, scale: 2) code String(storage: varchar, length: 12) }
-
**
temporal-polyfillis a peer dependency...
v8.0.0-rc.22
v8.0.0-rc.22
On PostgreSQL, DateTime, Date, Time and the new Duration are convenience types whose defaults read a JavaScript Date or a string, with no Temporal polyfill. Value objects move into the storage plane, so changing one is a migration, and Postgres checks value object and discriminator columns. MongoDB's query builder, raw lane, ORM and runtime take an execution context, as SQL's do, and a MongoDB client creates its driver from the execution stack. A contract can declare the Postgres extensions it needs, so db sign adopts a database that uses pgvector, PostGIS, ParadeDB or the new citext pack. The Prisma 7 reader now reads every Postgres @db.* type Prisma 7 accepts. MySQL gets ORM and SQL builder reads. Prisma ORM refuses to run from two installed copies, and connect() on a client is safe to call again.
The upgrade recipes for this hop: the app recipe and the extension recipe. Each breaking change below names the change ids to look for in them. The app recipe opens with the order to do the steps in. After upgrading, run prisma contract emit once, so a contract that an extension such as Supabase stamps with its version matches the installed package (contract-artifacts-restamp in the app recipe).
Breaking changes
-
On PostgreSQL,
DateTime,DateandTimeare convenience types with new defaults. Each is named for what a field means and becomes one explicit type, chosen by its optionalas,storageandprecisionarguments. At its default,DateTimeis atimestamptz(3)column read as a JavaScriptDate,Datereads a string such as"2024-02-29",Timereads a string such as"09:30:00", and the newDurationreads an ISO 8601 duration such as"P1M". Until now the three names readTemporalvalues. To keep a field as it is, renameDateTimetoTimestamptzTemporal,DatetoDateTemporalandTimetoTimeTemporal; in TypeScript, calltype.TimestamptzTemporal(...),type.DateTemporal()andtype.TimeTemporal(...).temporal.CreatedAtandtemporal.UpdatedAtare now built on the newDateTime, and theirStringandJsDatevariants are removed. A contract read byprisma7Schema(...)now reads a Prisma 7DateTimefield as aDate, as Prisma 7 did, so runprisma db signafter re-emitting it. On PostgreSQL and MySQL, a column read as aDate, such as MySQL'sDateTime, refuses a default with digits below a millisecond. The rest of this change is PostgreSQL only: SQLite, MySQL and MongoDB keep their date and time types.contract inferandcontract printnow write the convenience types: atimestamptz(3)column isDateTime, atimestamptzcolumnDateTime(precision: 6), atimestamp(3)columnDateTime(storage: timestamp),dateisDate,timeisTimeandintervalisDuration. So a contract you infer again reads atimestamptzfield as aDate, where it read an ISO 8601 string, and drops its microseconds; addas: string, as inDateTime(as: string, precision: 6), to keep the string. Seepsl-date-time-types-are-convenience-types,ts-date-time-helpers-are-convenience-types,temporal-type-aliases-on-datetime,prisma7-schema-reads-datesanddate-default-below-a-millisecondin the app recipe. (#30847)Before:
model Event { id Int @id at DateTime day Date opensAt Time(0) }
After, to keep each field and its contract:
model Event { id Int @id at TimestamptzTemporal day DateTemporal opensAt TimeTemporal(0) }
-
Value objects are storage entities, and Postgres checks their columns. A contract keeps its value objects at
storage.namespaces.<ns>.entries.valueObject, and a field names one by its storage coordinate, so changing a value object changes the storage hash and is a migration. On SQL, a discriminator column names a value set of its variants' values, and a discriminator field is typed by those values, such as'bug' | 'feature'. On a managed Postgres table, the contract derives a check for each value object column and each discriminator column; the nextmigration planadds them, anddb migratefails on a row that does not fit. Acontract.jsonthat keepsvalueObjectsin the domain plane is refused withCONTRACT.VALIDATION_FAILED. The app recipe ships a script that rewrites every contract, snapshot and migration that names one; run it, then sign each database before you re-emit. Extension authors:ValueObjectTypesFromDomainis nowValueObjectTypesFromStorage,FieldTypesFromDomaintakes the storage namespaces as a sixth argument,ValueObjectFieldTypeis renamedValueObjectReference, and a Postgres codec descriptor declaresjsonType. Seevalue-objects-in-storage,value-object-types-from-storage,postgres-value-object-checksanddiscriminator-typed-by-variant-valuesin the app recipe, andmongo-result-shapes-read-storage,postgres-check-expression-types-move,field-types-read-storage-value-objects,value-object-reference-typeandpostgres-codec-json-typein the extension recipe. (#30869) -
MongoDB's query builder, raw lane, ORM and runtime take an execution context.
mongoQuery,mongoRawandmongoOrmtake{ context }instead of{ contract }, assql({ context })and the SQL ORM do. A context comes frommongoStatic({ contract })ormongo({ contract }), which validate the contract once.mongoOrmtakes{ context, runtime }and no longer takesexecutor,enumsormutationDefaults.createMongoRuntimetakes{ context, adapter, driver }.buildMongoEnums,MongoEnumAccessors,MongoOrmEnumsandORM.MUTATION_DEFAULTS_MISSINGare removed. Extension authors:createSqlExecutionStack(...)returnsSqlExecutionStackWithDriver, whosedriveris always set, only when given a driver. Seemongo-query-takes-context,mongo-orm-takes-contextandmongo-runtime-takes-adapterin the app recipe, and the same ids plussql-stack-with-driver-requires-driverin the extension recipe. (#30865)Before:
import { mongoQuery } from '@prisma/orm-mongo/query-builder'; const query = mongoQuery({ contract }); const raw = mongoRaw({ contract });
After:
import mongoStatic from '@prisma/orm-mongo/static'; const { query, raw } = mongoStatic({ contract });
-
A MongoDB driver is created from its descriptor.
createMongoDriverandMongoDriverImplare no longer exported. Put the runtime driver descriptor, the default export of@prisma/orm-mongo/driver/runtime, on the execution stack, create the driver from the stack, and connect it. An application that callsmongo({ contract, url })sees no difference. Extension authors:MongoDrivergainsconnect(binding), and code that only sends commands takes the newMongoQueryable. Seemongo-driver-from-runtime-descriptorin the app recipe, andmongo-driver-from-runtime-descriptorandmongo-driver-connectin the extension recipe. (#30906)Before:
import { createMongoDriver } from '@prisma/orm-mongo/driver'; const driver = await createMongoDriver(url, dbName);
After:
import mongoRuntimeDriver from '@prisma/orm-mongo/driver/runtime'; const stack = createMongoExecutionStack({ target, adapter, driver: mongoRuntimeDriver }); const driver = stack.driver.create(); await driver.connect({ kind: 'url', url, dbName });
-
The pgvector, PostGIS and ParadeDB packs declare their Postgres extension, and
contract emitwrites each pack's files. Each pack's contract now declares its extension, and its head no longer requires an install invariant.prisma contract emitwrites each composed pack's head ref, contract snapshot and migrations undermigrations/<space-id>/, asmigration planalready did: commit them, then runprisma db migrateon each database to move the pack's marker.db signnow refuses a contract space whose head requires an invariant its marker does not record, withMIGRATION.SIGN_INVARIANTS_MISSING. Extension authors: declare a pack's extension in its contract instead of installing it withinstallExtension(...)and an invariant. Seecontract-emit-pins-pack-filesandpacks-declare-their-postgres-extensionin the app recipe, anddeclare-postgres-extension-in-pack-contractin the extension recipe. (#30902) -
**Prisma ORM refuses to ru...
v8.0.0-rc.21
v8.0.0-rc.21
migration plan and db update can rename or delete an enum value on Postgres and SQLite, and update the rows that hold it. MongoDB contracts written in TypeScript, PSL or Prisma 6 now build through one builder and follow the same rules. A closed client's members report the failure through the promise or result they return. MySQL gets its first public packages, which can plan and apply migrations. PostgreSQL's date and time types now name the kind of value they read, and the text date and time types read ISO 8601 on every server. Field presets are removed: each is written with a type constructor or type alias that stores the same contract. When a database is at a contract outside the migration graph, db migrate explains why and gives recoveries that work, none of which resets the database. The upgrade guides for rc.18 and rc.19 now work on real projects.
The upgrade recipes for this hop: the app recipe and the extension recipe. Each breaking change below names the change ids to look for in them. After upgrading, run prisma contract emit once, so a contract that an extension such as Supabase stamps with its version matches the installed package (contract-artifacts-restamp in the app recipe).
Breaking changes
-
A client member that returns a promise or a result rejects instead of throwing at the call. On
postgres(),sqlite(), asupabase()role-bound client and a transaction,query,execute,prepare,transaction, ORM calls and a prepared statement'squeryandexecutenow report a closed client, a failed connection or an ended transaction through what they return. The promise rejects, or the result rejects when it is awaited or read. Error codes and messages do not change. So.catch(handle)andPromise.allSettlednow see the error, but atry/catcharound a call withoutawaitno longer catches it: addawait.db.runtime()still throws at the call, and so does a mistake in the call itself. Extension authors:lazyActivitySourceanddelegatingActivitySourcenow reject fromstartActivityandplanContentHashwhen their source throws. Seeclient-members-reject-instead-of-throwingin the app recipe, andclient-members-reject-instead-of-throwingandlazy-activity-source-rejectsin the extension recipe. (#30840)Before:
try { db.transaction(work); // threw at the call after close(), so the catch ran } catch (error) { handle(error); }
After:
try { await db.transaction(work); // the returned promise rejects; await it to catch the error } catch (error) { handle(error); }
-
Removing an enum value is now asked about, like removing a model or a field. On Postgres and SQLite, when the contract removes an enum member or changes the value it stores,
migration plananddb updateask what the change means and rewrite the rows that hold the old value. A script that runs without a terminal fails withCLI.CONSENT_REQUIREDuntil you answer with--rename Status.ARCHIVED:Status.RETIREDor--delete Status.ARCHIVED. Before, Postgres failed at apply when a row held the old value, and SQLite planned nothing. Native Postgres enums (pg.enum(...)) are unchanged. Extension authors: renames and migration subjects gain anenumValuekind, and three optional fields let a target say how to keep the data a removed value would lose. Seeremoved-enum-value-questionsin the app recipe, andenum-value-rename-statementandrows-holding-value-and-keep-data-editin the extension recipe. (#30849) -
MongoDB contract type names and
mongoContractoptions change.mongoContract(schemaPath, options)now requiresoptions.target, the MongoDB target pack; a config written withdefineConfigfrom@prisma/orm-mongo/configneeds no change. The type of the object you pass todefineContractis renamed fromContractDefinitiontoContractInput, as in SQL.MongoModelDefinitionis removed: writeContractModel<MongoModelStorage>. Extension authors:loadContractSourceno longer takesonWarningand returns{ contract, warnings }, and a failed emit carriessourceWarnings. Seemongo-contract-target-option,mongo-contract-inputandmongo-model-definition-removedin the app recipe, and the same ids pluscontract-source-warningsin the extension recipe. (#30846)Before:
import type { ContractDefinition } from '@prisma/orm-mongo/contract-builder'; const contract = mongoContract('./prisma/schema.prisma');
After:
import type { ContractInput } from '@prisma/orm-mongo/contract-builder'; import mongoTargetPack from '@prisma/orm-mongo/target/pack'; const contract = mongoContract('./prisma/schema.prisma', { target: mongoTargetPack });
-
Every MongoDB contract source applies the same rules, so some contracts are now refused.
defineContractnow refuses what PSL refused: a discriminator that is optional, a list or not text; a variant value the discriminator cannot hold; a listed variant no model declares; and a variant stored in another collection than its base. Every source refuses an index MongoDB would refuse, a value object field typed by an undeclared enum, and a variant field that overwrites or restates a base field differently. PSL also refuses a duplicate index in one collection. Some contracts are newly accepted, such as an optional field that a type alias or generator fills. A Prisma 6 schema with two identical indexes in one collection now gives one index, so its storage hash changes: runprisma contract emit, thenprisma db sign. Seemongo-ts-polymorphism-rules,mongo-index-shape-rules,mongo-value-object-enum-check,mongo-newly-acceptedandmongo-prisma6-merged-indexesin the app recipe and the extension recipe. (#30846) -
close()closes the client's runtime even when you passed in the pool, and a SQLite file that cannot be opened is a connection error. When you pass your ownpg.Poolorpg.Clienttopostgres()orsupabase(),close()now also closes the client's runtime, so a runtime captured withdb.runtime()beforeclose()refuses new work. Your pool or client stays open; end it yourself. A SQLite database file that cannot be opened, such as a missing directory or a file that is not a database, is now aSqlConnectionErrorinstead of aSqlQueryError. Seeclose-ends-the-client-not-your-poolandsqlite-open-failure-is-a-connection-errorin the app recipe. (#30833) -
Each target names where its contract markers live.
verifyContractSpacestakes a requiredmarkerLocation. Extension authors:SqlControlAdapter,MongoControlAdapterandControlFamilyInstancegain a requiredmarkerLocation,SqlControlAdaptergains an optionalholdMarkerLock, andSqlPlanTargetDetails.schemais optional, with SQLite operations no longer carryingschema: 'main'. Seeverify-contract-spaces-marker-locationin the app recipe, andverify-contract-spaces-marker-location,control-adapter-marker-location,control-adapter-hold-marker-lockandplan-target-details-schema-optionalin the extension recipe. (#30841) -
PostgreSQL date and time types that read more than one kind of value are renamed. In PSL,
TimestamptzbecomesTimestamptzTemporal,TimestampbecomesTimestampTemporalandIntervalbecomesIntervalParts; the old names are errors. In TypeScript,type.Timestamptz(...),type.Timestamp(...)andtype.Interval(...)are renamed the same way, andintervalColumn(...)becomesintervalPartsColumn(...). Each new name reads the same value with the same codec, so the contract and its hashes do not change.@db.Timestampand@db.Timestamptzin a Prisma 7 schema are not affected. AnIntervalParts(p)column is now typed asPgInterval, the{ months, days, micros }object it reads, instead of a string. The string typesTimestamp,Timestamptz,TimeandIntervalare no longer exported from@prisma/orm-postgres/target/codec-types, so remove them from imports, including those in migration snapshots'contract.d.ts.Temporalfields are now typed with the...
v8.0.0-rc.20
v8.0.0-rc.20
ORM commands run on @prisma/cli-engine 0.9.0, so a piped command prints tab-separated data lines and JSON needs --json. A type alias in PSL can set @default, @onCreate and @onUpdate, and the contract stores each column's real type instead of the alias name. Postgres migrations can rename, move and remove namespaces, and can change a relation's actions or a primary key. A failed migration check now names the object it expected.
The upgrade recipes for this hop: the app recipe and the extension recipe. Each breaking change below names the change ids to look for in them.
Breaking changes
-
A piped ORM command prints data lines, not JSON, unless you pass
--json. The ORM toolchain now requires@prisma/cli-engine0.9.0, up from 0.7.0, the engine theprismaCLI ships since 8.0.0-rc.25. This engine picks the output format from flags only. When stdout is a pipe, a file,$(…), a CI log or an agent, a command used to print JSON. It now prints the human output on stderr and plain data lines on stdout. Add--jsonto every script, CI step or program that reads JSON fromprisma contract …,prisma db …,prisma migration …orprisma orm init. A project that depends on@prisma/cli-engineitself moves to0.9.0. Data lines are a stable interface: fields are tab-separated in a documented order, and new fields are only added at the end. For example,migration listprints space, name, from, to and operation count, one line per migration.db init,db update,db verify,db schemaandmigration ref deleteprint nothing on stdout; read their exit code, or pass--json. Seepiped-output-needs-jsonandengine-pin-moves-to-0-9-0in the app recipe and the extension recipe. (#30835)Before:
prisma migration status | jq '.envelope.result'
After:
prisma migration status --json | jq '.envelope.result' prisma migration list | cut -f2 # or read the data lines: one migration name per line
-
The contract stores a column's type, not the type alias it was written with. A column typed by a
types {}alias now stores the alias's codec and parameters itself, and the contract no longer has the alias instorage.types. Every contract that uses an alias gets a new storage hash. A stored contract whose columns still name an alias intypeRefno longer loads. Run the app recipe's script, which rewrites stored contracts and migration snapshots, then runprisma contract emit, thenprisma db signagainst every database. The database does not change. In the TypeScript builder, thetypeskey is removed andfield.namedType(...)takes only an enum: write an alias as a constantfield.column(type.VarChar(64)). The Supabase extension's contract changes hash for the same reason, so sign a Supabase database too. Seestored-contracts-expand-type-aliases,ts-types-key-removedandsupabase-contract-expandedin the app recipe. Extension authors run the same script from the package root and re-emit the bundled contract. A contract space that registers a database type writes it underdatabaseTypesinstead oftypes.ColumnTypeDescriptor.typeRef,StorageColumn.typeRefandExecutionContext.typesare removed. Seestored-contracts-expand-type-aliases,types-key-is-database-typesandcolumn-type-ref-removedin the extension recipe. (#30819)Before:
const types = { Embedding1536: type.pgvector.Vector(1536) } as const; const Post = model('Post', { fields: { embedding: field.namedType(types.Embedding1536).optional() }, }); return { types, models: { Post } };
After:
const Embedding1536 = field.column(type.pgvector.Vector(1536)); const Post = model('Post', { fields: { embedding: Embedding1536.optional() }, }); return { models: { Post } };
-
A SQL builder insert must include every column the database requires. In
db.sql.<namespace>.<table>.insert(rows), leaving out a column that is not nullable and has no default is now a type error that names the column. Such an insert used to compile and then fail in the database. A value typedT | undefinedfor such a column is an error too; check it before the insert. In ORMcreateandupsert, a field that is not nullable, has no default and generates a value only on update, such as one with@onUpdate(...)and no@onCreate(...), is now required. Seesql-builder-insert-required-columnsandorm-create-on-update-only-fieldin the app recipe, andsql-builder-insert-required-columnsin the extension recipe. (#30830)Before:
// User.displayName is `String` with no default; this compiled, then failed in the database db.sql.public.user.insert([{ email: '[email protected]', kind: 'admin' }]);
After:
db.sql.public.user.insert([{ email: '[email protected]', kind: 'admin', displayName: 'Admin' }]);
-
MongoDB enum members and discriminator values are written in the syntax of their data type. A MongoDB PSL enum member is read as a value of its codec's data type, as on SQL, so a quoted member is text. A quoted member on a type that does not take text is refused with
PSL_VALUE_TYPE_INCOMPATIBLE: write numbers,NaNand the infinities unquoted, and dates and binary values with their tags. An Int32 or Int64 member written with a fraction, such as1.0, is refused; write1. A@@discriminatorfield must be required and hold one value, on SQL and MongoDB alike. When an enum types a discriminator, each@@basevalue must be one of its members. A value the receiving type refuses now reportsPSL_VALUE_REFUSED. A Decimal128 value with leading zeros incontract.json, such as"007.5", is refused when the contract loads; re-emit the contract. Seemongo-quoted-enum-members,mongo-integer-enum-members-with-a-fraction,discriminator-optional-or-list,discriminator-base-value-not-a-member,psl-value-refused-codeanddecimal128-spellingin the app recipe. Extension authors:AuthoringEntityContexttakesdataTypesin place ofdataTypeLookup, thereadWrittenValueForCodechook is removed, and an enum block needswrittenValues. Seeentity-context-data-typesandenum-block-members-written-valuesin the extension recipe. (#30832)Before:
enum Ratio { @@type("mongo/double@1") Unknown = "NaN" Half = 0.5 }
After:
enum Ratio { @@type("mongo/double@1") Unknown = NaN Half = 0.5 }
-
Supabase runs every role operation through
forRole(binding), and itspgoption takes a pool only.SupabaseRuntimeno longer hasqueryWithRole,executeWithRole,preparedQueryWithRoleorpreparedExecuteWithRole. Callruntime.forRole(binding)once and use itsquery,executeandconnectionmembers. Thepgoption ofsupabase()takes apg.Pool; apg.Clientfails withSUPABASE.CONFIG_INVALID.db.close()does not end a pool you pass in.RoleBoundDb,ServiceRoleDband the transaction context gainenumsandnativeEnums, so test doubles of them must add those members. Afterdb.close(), a query on any role-bound client rejects withDRIVER.NOT_CONNECTED"Runtime is closed", andclose()waits for open role transactions. Seesupabase-for-role-replaces-with-role-methods,supabase-role-types-gain-members,supabase-pg-takes-a-poolandsupabase-close-waits-for-workin the app recipe. Extension authors:SqlRuntimeBase.acquireRawConnection()now follows the close rule ofconnection(), and a runtime that shares its driver is built withownsDriver: false. Seesupabase-for-role-replaces-with-role-methods,supabase-role-types-gain-members,supabase-pg-takes-a-poolandraw-connection-obeys-closein the extension recipe. (#30828)Before:
const rows = await runtime.queryWithRole(plan, { role: 'anon' }).toArray(); const db = await supabase({ contract, pg: new Client({ connectionString }), jwtSecret });
After:
const rows = await runtime.forRole({ role: 'anon' }).query(plan).toArray(); const db = await supabase({ contract, pg: new Pool({ connectionString }), jwtSecret });
-
A removed Postgres namespace is asked about, and
accessWideningis renamedaccessChanges. When the cont...
v8.0.0-rc.19
v8.0.0-rc.19
@default now means a database default, and values the client generates are written @onCreate(...) and @onUpdate(...). Every default is stored in one form owned by its column's data type, so date, time and bytes defaults are written with tags. Clients take the contract as a typed value, can render any plan as SQL without a database, and run each ORM call as one activity that middleware and the cache can see. A column of any database type can be declared with Raw(sql`...`), and Prisma 7 schemas with Unsupported(...) fields now load.
The upgrade recipes for this hop: the app recipe and the extension recipe. Each breaking change below names the change ids to look for in them.
Breaking changes
-
Client generators are written
@onCreate(...)and@onUpdate(...), and@defaultmeans a database default.@default(uuid()),@default(cuid(2)),@default(ulid())and@default(nanoid())are refused withPSL_GENERATOR_IN_DEFAULT. Write@onCreate(uuid())and so on instead. The app recipe ships a script that rewrites your Prisma 8 schema files. The contract does not change, so there is nothing to re-emit, sign or migrate.@default(now())and@default(autoincrement())are unchanged.contract printnow writes generated values as@onCreate(...)and@onUpdate(...). Seeclient-functions-move-from-default-to-on-createandcontract-print-writes-generator-attributesin the app recipe. (#30780)Before:
model Post { id String @id @default(uuid(7)) slug String @default(nanoid(12)) }
After:
model Post { id String @id @onCreate(uuid(7)) slug String @onCreate(nanoid(12)) }
-
A client takes the contract as a typed value. The
contractJsonoption and the type argument on the client call are removed frompostgres(),postgresServerless(),sqlite(),supabase(),mongo(),postgresStatic(),sqliteStatic(),mongoStatic()andmongoQuery(). Turn the emitted JSON into a value once withcontractFromJson<Contract>(contractJson)from the facade's/staticentry, and pass{ contract }. The app recipe ships a script that moves your source files; move test files by hand. The*OptionsWithContractand*OptionsWithContractJsontypes are replaced byPostgresOptions<Contract>and the matching types of the other facades. Seeclient-takes-contract-valuein the app recipe. (#30748)Before:
export const db = postgres<Contract>({ contractJson, url: process.env['DATABASE_URL']! });
After:
import { contractFromJson } from '@prisma/orm-postgres/static'; export const contract = contractFromJson<Contract>(contractJson); export const db = postgres({ contract, url: process.env['DATABASE_URL']! });
-
Date, time, interval and bytes defaults are written with tags, and each default has one stored form.
contract emitrefuses a quoted date, time, interval or bytes default and names the tag to write. Abyteadefault takes hexadecimal, not base64. A PostgreSQL contract that stores a default in another form than its column's type gives, such as"1.5"onnumeric(10,2), is refused by the CLI: runprisma contract emit, thenprisma db sign. On SQLite, datetime and JSON columns get their own data types; run the app recipe's script before the next CLI command, because the CLI refuses the old contract. Reading a value that its column's type cannot hold now throwsRUNTIME.DECODE_FAILED. A SQLiteDateTimetext with no UTC offset is read as UTC. Runprisma db signagainst every database after the upgrade. Seedate-time-interval-and-bytes-defaults-use-tags,sqlite-contracts-name-datetime-and-json-data-types,postgres-defaults-stored-in-another-spelling,prisma7-datetime-default-finer-than-column,stored-values-a-column-type-does-not-hold,sqlite-datetime-without-offset-read-as-utc,text-array-min-max-return-arraysandsign-databases-after-data-type-valuesin the app recipe. (#30750)Before:
at DateTime @default("2024-01-01T00:00:00Z") day Date @default("2024-03-15") payload Bytes @default("AQID")
After:
at DateTime @default(timestamptz`2024-01-01T00:00:00Z`) day Date @default(date`2024-03-15`) payload Bytes @default(bytea`\x010203`)
-
@noCheckis removed, and a list that allows null elements is writtenT?[]. A stored contract with anoCheckkey no longer loads. First run the app recipe's script, which rewrites stored contracts and migration snapshots, then runprisma db signagainst every database. Then replaceT[] @noCheck(elementNotNull)withT?[]and delete@noCheck(membership); in TypeScript, use.many({ elementsNullable: true }). A contract read from a Prisma 7 schema now types list elements asT | null, and the Supabase extension's fourtext[]columns allow null elements; both change the storage hash, so sign your databases. Seestored-contracts-drop-nocheck,psl-nocheck-removed,ts-nocheck-method-removed,prisma7-lists-allow-null-elementsandsupabase-contract-lists-allow-null-elementsin the app recipe. Extension authors run the same script from the extension package root, then re-emit the bundled contract; seestored-contracts-drop-nocheck,psl-nocheck-removedandts-nocheck-method-removedin the extension recipe. (#30741)Before:
tags String[] @noCheck(elementNotNull)After:
tags String?[]
-
Type-constructor arguments are values. A quoted number, such as
VarChar("255")orTimestamp("3"), is refused withPSL_VALUE_TYPE_INCOMPATIBLE; write the number without quotes. On Postgres a whole number written with a fraction, such asVarChar(255.0), is refused too, and so is a number the type cannot hold. The same applies to a field preset's precision, such astemporal.timestamp("3"). Seetype-constructor-arguments-are-valuesin the app recipe. (#30801)Before:
name VarChar("255")After:
name VarChar(255)
-
Enum members are values of their data type. A PSL enum member is read as a value of the enum codec's data type, as a
@defaultis. A quoted member is refused on a codec whose type is not text, such aspg/numeric@1orpg/int8@1; write numbers unquoted and dates and times with their tag. Enums typed bypg/jsonb@1,pg/timetz@1,pg/enum@1,arktype/json@1,pg/vector@1orpg/geometry@1are refused; use a text enum, or a native enum instead ofpg/enum@1. Members of apg/numeric@1,pg/interval@1ormongo/decimal128@1enum compare as values, so0.5and0.50are duplicates. Columns of more enum codecs are now typed as the union of their members; re-emit the contract. Seepsl-enum-members-read-by-the-cast-rule,more-codecs-refused-for-enums,enum-members-compare-by-their-data-typeandenum-columns-typed-by-member-literalsin the app recipe. (#30790)Before:
enum Ratio { @@type("pg/numeric@1") Half = "0.5" }
After:
enum Ratio { @@type("pg/numeric@1") Half = 0.5 }
-
Generator arguments are checked, and a generator must fit its column. An argument
uuid,cuidornanoiddoes not take, such asuuid(5), is now refused, in Prisma 8 PSL withPSL_INVALID_GENERATOR_ARGUMENTand in a Prisma 7 schema withPSL.PRISMA7_UNKNOWN_DEFAULT; it used to be read as something else. A number with a fraction, such asnanoid(8.0), is refused too. A generator on a Postgres column too short for what it writes, such asVarChar(5) @onCreate(uuid()), is refused when the contract is built instead of failing at the first insert. A SQL@@discriminatorthat is not text has a new message. Seeprisma7-default-function-arguments-checked,generator-function-argument-diagnostics,generator-function-argument-with-fraction,generator-fits-columnanddiscriminator-must-be-textin the app recipe. (#30792) -
Re-emit
contract.d.ts, and expect more precise types fromdefineContract.prisma contract emitwrites field and column types as generics applied to the contract, so a SQLcontract.d.tsemitted by an earlier release no longer compiles; re-emit it. A contract built withdefineContractnow gets the same ORM types as an emitted one: typedincluderows, aggregates, query operations, parameterized types such asVarchar<50>, ...
7.10.1
Prisma ORM 7.10.1 is a patch release. It fixes a bug where a nested interactive transaction could make later, unrelated transactions run inside the wrong transaction. It also updates dependencies that had security advisories.
Fixes
Prisma Client: nested $transaction no longer changes the options object you pass in
If you passed the same options object to a nested tx.$transaction(...) and later to a top-level prisma.$transaction(...), the nested call wrote the outer transaction's id into that object. Every later top-level transaction that used the object was then treated as nested inside that old transaction:
- if the old transaction had committed, the new one failed with
P2028; - if the old transaction was still open, the new one silently ran as a savepoint inside another request's transaction.
const TX_OPTIONS = { timeout: 30_000, maxWait: 10_000 }
await prisma.$transaction(async (tx) => {
await tx.$transaction(async (inner) => { /* ... */ }, TX_OPTIONS)
})
// Before 7.10.1, this call could fail with P2028 or join another transaction.
await prisma.$transaction(async (tx) => { /* ... */ }, TX_OPTIONS)Prisma Client no longer modifies the options object. (#30368, thanks @lazerg)
Prisma Migrate: refuse a shadow database that is the main database
Prisma Migrate now refuses to run with error P3025 when the shadow database URL points at the same database as the main database URL. Before, prisma migrate diff --from-migrations with that setup dropped the real schema, rebuilt it from the migrations, and reported an empty diff. (prisma/prisma-engines#5851)
MariaDB adapter: updated to mariadb 3.5.4
@prisma/adapter-mariadb now depends on mariadb 3.5.4, which fixes several security advisories in 3.5.3. The adapter no longer rewrites IPv6 hosts in connection strings, because mariadb 3.5.4 accepts them as written. IPv6 connection strings keep working without changes. (#30668)
Dependency updates
Dependencies with security advisories were updated: mysql2, fast-uri, deepmerge-ts, mariadb and source-map-js. (#30314, #30189, #30668)
v8.0.0-rc.18
v8.0.0-rc.18
Raw SQL in a contract is now always a sql literal or value, a full-text index can span several weighted fields and is searched from the ORM by naming it, and middleware observes each statement and transaction as an activity. PSL gains mixins, the SQL ORM gains whereUnique and firstOrThrow, and MongoDB migrations carry out --rename.
The upgrade recipes for this hop: the app recipe and the extension recipe. Each breaking change below names the change ids to look for in them.
Breaking changes
-
Raw SQL in a contract is a
sqlliteral. In PSL,@@index(where:),@@index(expression:),@@fullTextIndex(where:),@@check(expression:)and a policy'susingandwithChecktake asqlliteral, and a quoted string is refused withPSL_VALUE_TYPE_INCOMPATIBLE. The app recipe ships a script that rewrites every.prismafile. In a TypeScript contract the same fields take asqlvalue, and a string does not compile; migration files keep strings. A text with shared indentation, blank lines at its ends or CRLF line breaks is stored as its canonical text, which changes the storage hash once. Seeraw-sql-is-a-sql-literal,builder-raw-sql-is-a-sql-value,psl-storage-hash-may-change-onceandts-storage-hash-may-change-oncein the app recipe. (#30550, #30558)Before:
@@index([email], where: "(archived_at IS NULL)", name: "users_email_active")After:
@@index([email], where: sql`(archived_at IS NULL)`, name: "users_email_active") -
Middleware hooks are activity hooks. The runtime runs every statement and transaction as an activity.
beforeQueryandbeforeExecutebecomebeforeEncode;interceptQueryandinterceptExecutebecomeintercept.onQueryandintercept.onExecute;afterQueryandafterExecutebecomeactivityEnded;afterTransactionbecomesactivityFinalized.RuntimeMiddlewareContextis nowActivityContext, andctx.planExecutionIdis replaced byactivity.id.activityEndedalso fires for a statement the caller stopped reading and for one that failed before it ran, so a metrics middleware checksresult.outcome. Seemiddleware-hooks-are-activity-hooksandevery-started-statement-is-ended-and-finalizedin the app recipe, andstatement-runners-replace-middleware-runnersin the extension recipe. (#30703)Before:
async afterQuery(plan, result, ctx) { if (result.latencyMs > 250) ctx.log.warn({ sql: plan.sql, rowCount: result.rowCount }); },
After:
async beforeEncode(plan, ctx) { ctx.state(statementSql)['sql'] = plan.sql; }, async activityEnded(activity, result, ctx) { if (result.kind !== 'statement' || result.latencyMs <= 250) return; ctx.log.warn({ sql: ctx.state(statementSql)['sql'], ...(result.returns === 'rows' ? { rowCount: result.rowCount } : {}), }); },
-
A full-text index is stored as data.
@@fullTextIndexandfullTextIndexstore an index of typefullTextwith its columns, weight groups and language, not a SQL expression. The schema source does not change, but the index's generated name and the storage hash do: re-emit the contract and runprisma migration plan, which renames the index in place. Avoiddb updatefor a large index, because it drops and rebuilds it. Seere-emit-contracts-with-a-full-text-indexin the app recipe andrender-full-text-index-document-takes-a-definitionin the extension recipe. (#30562)Before:
{ "expression": "to_tsvector('english', \"title\")", "name": "post_title_search_724b05e5", "type": "gin" }After:
{ "columns": ["title"], "name": "post_title_search_e0dd1131", "options": { "language": "english", "weightGroups": [["title"]] }, "type": "fullText" } -
A base model lists its variants by discriminator value. In
contract.jsonandcontract.d.ts, a polymorphic base'svariantsis keyed by discriminator value, and each entry names the variant model and its namespace. A contract in the previous form is refused withCONTRACT.VALIDATION_FAILED. Re-emit the contract and rewritevariantsin the snapshots undermigrations/snapshots/; the storage hash does not change. Seere-emit-contracts-with-polymorphic-modelsandread-variants-by-discriminator-valuein the app recipe. (#30696)Before:
"variants": { "Bug": { "value": "bug" }, "Feature": { "value": "feature" } }
After:
"variants": { "bug": { "model": "Bug", "namespace": "public" }, "feature": { "model": "Feature", "namespace": "public" } }
-
The SQL ORM client accepts only field names. Every name passed to the SQL ORM client must be a field of the model, or of the variant the collection is narrowed to; any other name, including a column name that differs from its field name, throws
ORM.FIELD_UNKNOWN. Rows no longer carry a column no field maps. Seeorm-refuses-names-that-are-not-fieldsin the app recipe. (#30667)Before:
await db.orm.Post.where({ user_id: 1 }).all();
After:
await db.orm.Post.where({ userId: 1 }).all();
-
The query fragment types are renamed, and a fragment is made from the model's root collection.
Fragmentis nowQueryFragmentandFieldFragmentis nowDeclaredFieldsFragment.collection.fragment(body)throwsORM.ARGUMENT_INVALIDon a collection with chained calls, which it used to ignore; chain on the collection directly, or move the calls into the fragment's body. Seefragment-types-are-renamedandfragment-is-made-from-the-root-collectionin the app recipe. (#30652, #30673)Before:
const recentSummary = db.orm.public.Post.orderBy((p) => p.id.desc()).fragment((posts) => posts.select('id', 'title'), );
After:
const recentSummary = db.orm.public.Post.fragment((posts) => posts.orderBy((p) => p.id.desc()).select('id', 'title'), );
-
migration planasks before a lossy type change, and writes placeholders only when asked. On Postgres and SQLite, a type change that can lose values fails withCLI.CONSENT_REQUIREDwhere nobody can answer, until--convert <Model.field>(write the conversion yourself) or--delete <Model.field>(accept the database's cast) answers it. A new required field gets a temporary value in existing rows; pass--backfill <Model.field>to fill them yourself. In a hand-written Postgresmigration.ts,alterColumnTypetakestypeandusingdirectly instead of anoptionsobject. Seelossy-type-changes-ask,placeholders-only-when-askedandpostgres-alter-column-type-plain-optionsin the app recipe. (#30695) -
Removing a field from a MongoDB model asks first. The plan now removes the field from every document that holds it, and
migration plananddb updateask about it; add--delete <Model>.<field>, or--renameif the field was renamed, to scripts and CI. A MongoDB plan's preview writesdb.getCollection("users")where it wrotedb.users, andnode migration.tsuses the config that owns the migration. Seemongo-removed-field-asks,mongo-preview-get-collectionandmigration-ts-finds-its-configin the app recipe. (#30691) -
A Prisma 7 schema's
@ignoreand@@ignoreobjects stay in the contract.prisma7Schema()keeps their columns, tables, keys and indexes in storage, so a schema that uses them gets a new storage hash, and a schema that loaded only because they were dropped can be refused. Emit the contract, then sign each database, or plan a migration first if Prisma 8 already manages your migrations. Seeprisma7-ignore-keeps-storagein the app recipe. (#30672) -
Top-level PSL declarations belong to the default namespace. A top-level declaration and one inside
namespace public { … }on Postgres share one set of names, so the same name declared both ways isPSL_DUPLICATE_DECLARATION, and a top-level declarati...
v8.0.0-rc.17
v8.0.0-rc.17
Migrations no longer lose data without being told to: prisma migration plan and prisma db update ask about each model or field a plan would drop, answered with --delete or with the new --rename, which keeps the rows. The ORM client gains row locks, apply and scope are renamed to with and fragment, and db.enums holds each member as a query returns it.
The upgrade recipes for this hop: the app recipe and the extension recipe. Each breaking change below names the change ids to look for in them.
Breaking changes
-
--confirmno longer consents to data loss.prisma migration planandprisma db updateask one question for each model, field or table a plan would lose data from, before they write or apply anything. Answer with--delete <subject>to let the data go, or--rename <old>:<new>to keep it.db updatealso asks before an operation that widens who can read or write a model's rows, such as dropping a row-level-security policy, answered with--allow <Model>. Where nobody can answer, the command fails withCLI.CONSENT_REQUIRED, whosenextActionsgive the flags. Replace each--confirmin scripts and CI. Seemigration-plan-refuses-data-lossanddb-update-confirm-no-longer-consentsin the app recipe. (#30648)Before:
prisma db update --confirm appdb
After:
prisma db update --delete Legacy --rename User.name:User.fullName
-
destructivenow means data loss. Dropping an index, a constraint, a check, a default or a native enum type, PostgressetNotNull, and type changes that keep every value are nowwideningoperations, and no longer ask for consent. Amigration.tsno database has applied yet writes a differentops.jsonandmigrationHashwhen run again. Seenon-data-drops-are-wideninganddestructive-means-data-lossin the app recipe. (#30638, #30648) -
The control API answers questions through a callback.
executeMigrationPlanCommand,executeDbUpdateand the control client'sdbUpdaterequire ananswerQuestionscallback, and loseconsent.acceptDataLoss: trueno longer covers access widening; passacceptAccessWidening: truetoo. The errorsMIGRATION.DESTRUCTIVE_CHANGESandMIGRATION.CONSENT_PLAN_MISMATCHare no longer raised. Seecontrol-api-answer-questionsandconsent-errors-removedin the app recipe. (#30648) -
The collection method
applyis nowwith, andscopeis nowfragment. A reusable function from a collection to a collection is a query fragment, made withdb.orm.fragment(...)orcollection.fragment(...)and run withcollection.with(...). The typesScope,FieldScopeandScopeFactsare nowFragment,FieldFragmentandFragmentFacts. This applies to the SQL ORM client only. Seecollection-apply-is-now-withandorm-scope-is-now-fragmentin the app recipe. (#30635, #30647)Before:
const postSummary = db.orm.public.Post.scope((posts) => posts.select('id', 'title').include('user')); const posts = await db.orm.public.Post.apply(notDeleted).apply(postSummary).all();
After:
const postSummary = db.orm.public.Post.fragment((posts) => posts.select('id', 'title').include('user')); const posts = await db.orm.public.Post.with(notDeleted).with(postSummary).all();
-
db.enumsholds each member as a query returns it. A member whose codec stores another form incontract.jsonchanges: a bigint member is abigint, a date member aDateor a Temporal value, a byte member aUint8Array, and a NaN or infinite float member a number.has(),nameOf()andordinalOf()now find a value read from the database. Remove conversions your code applied to these members, and re-emit the contract. Code that builds the MongoDB ORM itself withmongoOrm()orcreateMongoCollection()must pass the enum accessors. Seedb-enums-members-hold-read-valuesandmongo-orm-takes-enum-accessorsin the app recipe. (#30628)Before:
// Level is @@type("pg/int8@1") with Low = "1" db.enums.public.Level.members.Low; // "1"
After:
db.enums.public.Level.members.Low; // 1n
-
Enum members and values must be written as the database stores them. A Postgres
numericorinetenum member written in a form Postgres prints differently, such as"01.5"or"10.0.0.1/32", is refused, and the message says what to write. Enums can no longer use codecs whose values never equal a member:pg/timestamp-string@1,pg/timestamptz-string@1,pg/bytea@1,pg/tsquery@1,pg/json@1, and on MongoDBmongo/json@1andmongo/bson@1, plus PSL enums on BSON types the collection validator cannot list. Seets-enum-members-written-as-stored,psl-enum-members-written-as-stored,enum-codecs-refused,enum-json-codec-refusedandpsl-enum-bson-types-refusedin the app recipe. (#30628)Before:
enum Ratio { @@type("pg/numeric@1") Half = "01.5" }
After:
enum Ratio { @@type("pg/numeric@1") Half = "1.5" }
-
Contracts from a Prisma 7 schema state the constraint names Prisma 7 chose.
prisma7Schema(...)now writes the name of each primary key and foreign key whose Prisma 7 name differs from the one Prisma 8 derives. A contract with such a constraint gets a new storage hash: re-emit, then sign the database, plan a migration or rundb update, depending on who manages it. Seeprisma7-schema-states-constraint-namesin the app recipe. (#30606) -
The CHECK constraint on an enum list column compares in the column's own type. The constraint's expression and name change, so re-emit and apply a migration that replaces it. See
enum-list-check-compares-in-column-typein the app recipe. (#30628) -
Each foreign key in
contract.jsonnames the index that backs it. A newindexfield on each foreign key says whether an index, the primary key or a unique constraint serves its lookups, so every SQL contract with a foreign key gets a new storage hash. Re-emit, then followmigration plan's advice: write an empty migration withprisma migration new --from <hash>, or runprisma db signon a database you manage withdb initordb update. Two related changes can alter your database: a partial index, or an index with a non-defaulttypeoroptions, no longer counts as a relation's backing index, somigration plancreates one beside it; and an unnamed@@indexon exactly the columns of a unique constraint or the primary key is left out of the contract, somigration plandrops it. To keep the database as it is, writeindex: "<name>"on the relation, or give the plain index aname. Seeforeign-keys-name-their-backing-index,partial-or-typed-index-no-longer-backs-a-foreign-keyandunnamed-index-on-unique-columns-left-outin the app recipe. (#30561)author User @relation(fields: [authorId], references: [id], index: "post_author_live") -
MongoDB PSL writes an index's sort direction as
sort(field, direction). The oldfield(sort: Desc)form is no longer accepted in@@index,@@uniqueand@@textIndex. The database index does not change. Seemongo-index-sort-functionin the app recipe. (#30636)Before:
@@index([createdAt(sort: Desc), authorId])After:
@@index([sort(createdAt, Desc), authorId]) -
Extension authors: migration planners take statements and report what they lose. A planner's
plan(...)takes requiredstatementsandorigin, and its success result carriesappliedStatements,dataLossandaccessWidening.ControlFamilyInstancerequiresstorageNameOf.plannerSuccesstakesappliedStatementsand the subjects lists. See the planner entries in the extension recipe. (#30638, [#30648](https://github.com/prisma/orm/pull...