Skip to main content

升级到 Prisma ORM 5

Prisma ORM 5.0.0 引入了许多更改,包括使用我们新的 JSON 协议 默认情况下,Prisma 客户端速度更快。这些更改的完整列表可以在 在我们的发行说明中 中找到。

¥Prisma ORM 5.0.0 introduces a number of changes, including the usage of our new JSON Protocol, which make Prisma Client faster by default. A full list of these changes can be found in our release notes.

本指南解释了升级可能如何影响你的应用,并提供有关如何处理 Prisma ORM 5 中的重大更改的说明。

¥This guide explains how upgrading might affect your application and gives instructions on how to handle breaking changes within Prisma ORM 5.

prisma@prisma/client 软件包升级到版本 5

¥Upgrade the prisma and @prisma/client packages to version 5

要从早期版本升级到 Prisma ORM 5,你需要更新 prisma@prisma/client 软件包。

¥To upgrade to Prisma ORM 5 from an earlier version, you need to update both the prisma and @prisma/client packages.

npm install @prisma/client@5
npm install -D prisma@5
danger

在升级之前,请检查下面的每项重大更改,以了解升级可能如何影响你的应用。

¥Before you upgrade, check each breaking change below to see how the upgrade might affect your application.

版本变更

¥Version changes

Prisma ORM 5 包括 Node.js、TypeScript 和 PostgreSQL 的一些最低版本更改。要使用 Prisma 版本 5.0.0 及更高版本,你至少需要拥有以下最低版本:请参阅我们的 系统要求 了解所有最低版本要求。

¥Prisma ORM 5 includes some minimum version changes for Node.js, TypeScript, and PostgreSQL. To use Prisma version 5.0.0 and up, you will need to have at least the minimum versions below: See our system requirements for all minimum version requirements.

Node.js 最低版本变更

¥Node.js minimum version change

从 Prisma ORM 版本 5.0.0 开始,支持的 Node.js 最低版本为 16.13.0。如果你的项目使用早期版本的 Node.js,你将需要对其进行升级。

¥From Prisma ORM version 5.0.0, the minimum version of Node.js supported is 16.13.0. If your project uses an earlier version of Node.js, you will need to upgrade it.

warning

Node.js v16.x 即将达到 于 2023 年 9 月 11 日报废,以配合 OpenSSL 1.1.1 的生命周期结束。因此,我们建议升级到当前的 Node.js LTS v18.x。请注意,Prisma ORM 5 将是支持 Node.js v16 的最后一个 Prisma ORM 主要版本。

¥Node.js v16.x is reaching end-of-life on 11 September 2023 in order to coincide with the end-of-life of OpenSSL 1.1.1. For that reason, we recommend upgrading to the current Node.js LTS, v18.x. Please note that Prisma ORM 5 will be the last major version of Prisma ORM to support Node.js v16.

TypeScript 最低版本变更

¥TypeScript minimum version change

从 Prisma ORM 版本 5.0.0 开始,支持的 TypeScript 最低版本为 4.7。如果你的项目使用早期版本的 TypeScript,你将需要升级它。

¥From Prisma ORM version 5.0.0, the minimum version of TypeScript supported is 4.7. If your project uses an earlier version of TypeScript, you will need to upgrade it.

PostgreSQL 最低版本变更

¥PostgreSQL minimum version change

从 Prisma ORM 版本 5.0.0 开始,支持的 PostgreSQL 最低版本是 9.6。如果你的项目使用早期版本的 PostgreSQL,你将需要升级它。

¥From Prisma ORM version 5.0.0, the minimum version of PostgreSQL supported is 9.6. If your project uses an earlier version of PostgreSQL, you will need to upgrade it.

warning

虽然 Prisma ORM 支持 PostgreSQL 9.6 及更高版本,但我们强烈建议更新到当前受支持且仍在接收更新的版本。请检查 PostgreSQL 的版本控制策略 以确定当前支持哪些版本。

¥While Prisma ORM supports PostgreSQL versions 9.6 and above, we strongly recommend updating to a version that is currently supported and still receiving updates. Please check PostgreSQL's versioning policy to determine which versions are currently supported.

Prisma Client 嵌入式 SQLite 版本更新

¥Prisma Client embedded SQLite version updated

在 Prisma ORM 版本 5.0.0 中,我们将 SQLite 的嵌入式版本从 3.35.4 升级到了 3.41.2。我们没有看到任何重大更改,并且预计用户项目中不需要任何更改,但如果你使用 SQLite,尤其是使用可能超出 Prisma ORM 功能的原始查询,请务必检查 SQLite 变更日志

¥With Prisma ORM version 5.0.0, we have upgraded the embedded version of SQLite from 3.35.4 to 3.41.2. We did not see any breaking changes and don't anticipate any changes needed in user projects, but if you are using SQLite, especially with raw queries that might go beyond Prisma ORM's functionality, make sure to check the SQLite changelog.

主要变化

¥Primary changes

本节概述了 Prisma ORM 5 中的主要重大变化。

¥This section gives an overview of the main breaking changes in Prisma ORM 5.

删除 rejectOnNotFound 参数

¥Removal of rejectOnNotFound parameter

在 Prisma ORM 5 中,已弃用的参数 rejectOnNotFound 已被删除。根据你的项目是每个查询使用 rejectOnNotFound 还是全局使用 rejectOnNotFound,更新代码的方式将会有所不同。

¥With Prisma ORM 5, the deprecated parameter rejectOnNotFound has been removed. Depending on if your project used rejectOnNotFound per query or globally, there will be be different ways of updating your code.

如果你在每个查询中使用 rejectOnNotFound 参数,请按照我们针对 在查询级别更新代码 的步骤操作。

¥If you are using the rejectOnNotFound parameter on a per-query basis, then follow our steps for updating your code at the query level.

如果你在客户端级别设置了 rejectOnNotFound 参数,则需要遵循 在客户端级别更新代码的步骤

¥If instead you have set up the rejectOnNotFound parameter at the client level, you will need to follow the steps for updating your code at the client level.

jsonProtocol 已退出预览版

¥jsonProtocol out of Preview

jsonProtocol 预览功能现已全面可用。与我们之前基于 GraphQL 的协议相比,这个新协议导致了 显着缩短启动时间。升级到 Prisma ORM 5 时,请确保从预览功能中删除 jsonProtocol(如果已添加)。

¥The jsonProtocol preview feature is now Generally Available. This new protocol leads to significantly improved startup times when compared to our previous GraphQL-based protocol. When upgrading to Prisma ORM 5, make sure to remove jsonProtocol from your preview features, if added.

Prisma ORM 4 及更低版本:

¥Prisma ORM 4 and lower:

generator client {
provider = "prisma-client-js"
previewFeatures = ["jsonProtocol"]
}

Prisma ORM 5:

generator client {
provider = "prisma-client-js"
}

请查看我们的 json 协议变更指南,了解如何更新你的应用以适应 Prisma ORM 5 中的新协议。你将需要:

¥Please review our jsonProtocol changes guide to learn how to update your app to account for the new protocol in Prisma ORM 5. You will need to:

删除数组快捷方式

¥Removal of array shortcuts

Prisma ORM 5 放弃了对许多 "数组快捷方式" 的支持。这些快捷方式是一种将单个元素作为值添加到基于数组的运算符的方法,而不是将该一个元素封装在数组中。为了使我们的类型更加一致和逻辑并符合新的 JSON 协议,我们现在需要这些运算符的数组值。

¥Prisma ORM 5 drops support for a number of "array shortcuts". These shortcuts were a way to add a single element as a value to an array-based operator instead of wrapping that one element in an array. To make our typings more consistent and logical and to conform to the new JSON Protocol, we now require array values for these operators.

在大多数情况下,修复就像将现有值封装在数组中一样简单。Prisma ORM 5 中删除的快捷方式是:

¥In most cases, the fix will be as simple as wrapping the existing value in an array. The shortcuts removed in Prisma ORM 5 are:

虽然 ORinnotIn 运算符受到影响,但 ANDNOT 不受此更改影响。

¥While OR, in, and notIn operators are affected, AND and NOT are not affected by this change.

连接到 CockroachDB 数据库时现在需要 cockroachdb 提供程序

¥cockroachdb provider is now required when connecting to a CockroachDB database

使用 Prisma ORM 版本 5.0.0,我们要求在连接到 CockroachDB 数据库时使用 cockroachdb 提供程序。此前,我们也接受了 postgresql,但我们正在删除该选项。

¥With Prisma ORM version 5.0.0, we require the cockroachdb provider to be used when connecting to CockroachDB databases. Previously, we had accepted postgresql as well, but we are removing that option.

如果你使用 原生数据库类型postgresql 提供程序,则需要从 PostgreSQL 到 CockroachDB 的 数据库的基线

¥If you were using native database types and also the postgresql provider, you will need to baseline your database from PostgreSQL to CockroachDB:

  1. 备份现有的 schema.prisma 文件(例如使用版本控制)

    ¥Backup your existing schema.prisma file (e.g. use version control)

  2. 将你的 datasource 提供商从 postgresql 更新为 cockroachdb

    ¥Update your datasource provider from postgresql to cockroachdb

  3. 使用 npx prisma db pull --force 将现有 Prisma 架构(包括原生类型)覆盖为 CockroachDB 实例上的架构。

    ¥Use npx prisma db pull --force in order to overwrite your existing Prisma schema (including native types) to those that are on your CockroachDB instance.

  4. 查看 Prisma 架构备份和 db pull 生成的新 Prisma 架构之间的更改。你可以按原样使用新架构,也可以更新它以包含你喜欢的间距、注释等。

    ¥Review changes between your Prisma schema backup and the new Prisma schema generated by db pull. You can either use the new schema as is, or update it to include your preferred spacing, comments, etc.

  5. 删除你现有的迁移。我们将进行 执行基线 以使你的本地设置与你现有的 CockroachDB 实例一致。

    ¥Delete your existing migrations. We will be performing a baseline in order to make your local setup agree with your existing CockroachDB instance.

  6. 执行 基线步骤。完成这些步骤后,你将成功从 postgresql 提供商迁移到 cockroachdb 提供商!

    ¥Perform the baselining steps. After these steps, you'll have migrated successfully from the postgresql provider to the cockroachdb provider!

从生成的客户端中删除 runtime/index.js

¥Removal of runtime/index.js from generated client

runtime/index.js 文件已从 Prisma 客户端中删除。

¥The runtime/index.js file has been removed from Prisma Client.

使用 @prisma/client/runtime 的公共 API

¥Using public APIs from @prisma/client/runtime

Prisma ORM 5 中不再提供从 @prisma/client/runtime 导入。如果你之前使用过此命名空间中可用的公共 API,则可以导入 Prisma 并访问它们。例如:

¥Importing from @prisma/client/runtime is no longer available in Prisma ORM 5. If you were using public APIs available in this namespace before, you can instead import Prisma and access them. For example:

import { Decimal, NotFoundError } from '@prisma/client/runtime'
const num = new Decimal(24.454545)
const notFound = new NotFoundError()

将需要更改为

¥will need to be changed to

import { Prisma } from '@prisma/client'
const num = new Prisma.Decimal(24.454545)
const notFound = new Prisma.NotFoundError()

对特定运行时使用私有 API

¥Using private APIs for a specific runtime

我们强烈反对使用内部私有 API,因为它们可能会在没有警告的情况下发生更改,并且不保证受到支持。如果你的使用需要以前可用的私有 API 请在 GitHub 上联系我们。

¥We highly discourage the use of internal private APIs as they can change without warning and are not guaranteed to be supported. If your usage requires a private API that was previous available please reach out to us on GitHub.

生成的类型变化

¥Generated type changes

更改 RelationFilterInput 以考虑可为空性

¥Changes to RelationFilterInput to account for nullability

在 Prisma ORM 5 之前,存在一个长期存在的错误,导致可空反向关系在我们生成的类型中未被标记为可空。例如,采用以下架构:

¥Prior to Prisma ORM 5, there was a long-standing bug that caused nullable reverse relations to not be marked as nullable in our generated types. For example, take the following schema:

model User {
id Int @id

addressId Int @unique
address Address @relation(fields: [addressId], references: [id])

post Post[]
}

model Address {
id Int @id

user User?
}

model Post {
id Int @id

userId Int
user User @relation(fields: [userId], references: [id])
}

在生成的类型中,Address.userPost.user 将使用相同的类型 UserRelationFilter。这显然是无意的,因为 Address.user 可以为空,而 Post.user 则不能。在 Prisma ORM 5 中,Address.user 的类型将是 UserNullableRelationFilter,解决了这个问题。

¥In the generated types, Address.user and Post.user would use the same type, UserRelationFilter. This is obviously unintended as Address.user is nullable while Post.user is not. In Prisma ORM 5, the type of Address.user would be UserNullableRelationFilter, resolving this issue.

如果你在代码中导入生成的类型,则需要更新此类实例才能使用新的 Nullable 类型。

¥If you import generated types in your code, you will need to update instances like this to utilize the new Nullable types.

更改为 UncheckedUpdateManyInput 以避免名称冲突

¥Changes to UncheckedUpdateManyInput to avoid name collisions

在某些情况下,当一个模型具有指向另外两个模型的两个外键(这两个模型具有相同的反向关系属性名称)时,可能会发生名称冲突。作为示例,以下架构:

¥In certain instances it was possible for name collisions to occur when one model had two foreign keys to two other models that had the same property name for the reverse relation. As an example, the following schema:

model Invoice {
InvoiceId Int @id @default(autoincrement())

invoice_items InvoiceItem[]
}

model InvoiceItem {
InvoiceLineId Int @id @default(autoincrement())

InvoiceItemInvoiceId Int @map("InvoiceId")
invoices Invoice @relation(fields: [InvoiceItemInvoiceId], references: [InvoiceId])

TrackId Int
tracks Track @relation(fields: [TrackId], references: [TrackId])
}

model Track {
TrackId Int @id @default(autoincrement())
Name String

invoice_items InvoiceItem[]
}

会导致 InvoiceItem 上两个关系之间的名称冲突。相反的关系,即 Invoice.invoice_itemsTrack.invoice_items 都将得到类型 InvoiceItemUncheckedUpdateManyWithoutInvoice_itemsInput。在 Prisma ORM 5 中,这个问题已得到解决,Prisma 客户端将分别生成 InvoiceItemUncheckedUpdateManyWithoutInvoicesInputInvoiceItemUncheckedUpdateManyWithoutTracksInput

¥Would lead to conflicting names between the two relations on InvoiceItem. The reverse relations, that is Invoice.invoice_items and Track.invoice_items would both get the type InvoiceItemUncheckedUpdateManyWithoutInvoice_itemsInput. In Prisma ORM 5, this is resolved and Prisma Client will generate InvoiceItemUncheckedUpdateManyWithoutInvoicesInput and InvoiceItemUncheckedUpdateManyWithoutTracksInput respectively.

如果你在代码中导入生成的类型,则需要将此类实例更新为更正的类型。

¥If you import generated types in your code, you will need to update instances like this to the corrected types.

其他变化

¥Other changes

以下更改可能会导致应用在升级到 Prisma ORM 5 后最初抛出错误消息。幸运的是,它们很容易解决,因为底层功能已被删除一段时间,或者更改只是简单的字符串替换。

¥The following changes may cause an application to initially throw an error message after upgrading to Prisma ORM 5. Fortunately, they are easy to solve, as the underlying functionality has been removed for a while or the change is a simple string replace.

删除已弃用的 Prisma CLI 标志

¥Removal of deprecated Prisma CLI flags

多个已弃用的 CLI 标志已被删除。以下所有标志均来自以前的 API,不再需要:

¥Several deprecated CLI flags have been removed. All following flags are from previous APIs and are no longer needed:

  • --preview-feature 用于 db executedb seeddb diff

    ¥--preview-feature used in db execute, db seed, and db diff

  • --experimental--early-access-feature 用于 migrate

    ¥--experimental and --early-access-feature used in migrate

  • --force/-f 用于 db push

    ¥--force/-f used in db push

  • --experimental-reintrospection--clean 用于 db pull

    ¥--experimental-reintrospection and --clean used in db pull

过时的 db push --force 用法可以用较新的实现 db push --accept-data-loss 代替。

¥The outdated use of db push --force can be replaced with the newer implementation db push --accept-data-loss.

所有其他标志均来自以前的 API,不再需要。

¥All other flags are from previous APIs and are no longer needed.

从库引擎中删除 beforeExit 钩子

¥Removal of the beforeExit hook from the library engine

beforeExit 钩子已从 Prisma ORM 库引擎中删除。虽然 Prisma ORM 二进制引擎仍然需要此功能才能运行最后一刻查询或执行关闭相关操作,但与库引擎中的原生 Node.js 退出钩子相比,它没有任何优势。我们建议使用内置的 Node.js 退出事件来代替此钩子。

¥The beforeExit hook has been removed from the Prisma ORM library engine. While this functionality is still required for the Prisma ORM binary engine in order to run last minute queries or perform shutdown related operations, it provides no benefit over native Node.js exit hooks in the library engine. Instead of this hook we recommend using built-in Node.js exit events.

使用 Prisma ORM 4 的以下代码:

¥The following code with Prisma ORM 4:

const exitHandler = () => {
// your exit handler code
}

prisma.$on('beforeExit', exitHandler)

可能会变成:

¥Could become:

const exitHandler = () => {
// your exit handler code
}

process.on('exit', exitHandler)
process.on('beforeExit', exitHandler)
process.on('SIGINT', exitHandler)
process.on('SIGTERM', exitHandler)
process.on('SIGUSR2', exitHandler)

如果你在 NestJS 中使用 beforeExit 钩子,则可以通过删除服务中的自定义 enableShutdownHooks 方法来升级到 Prisma ORM 5:

¥If you're using the beforeExit hook in NestJS, you can upgrade to Prisma ORM 5 by removing the custom enableShutdownHooks method in your service:

"prisma.service.ts"
@Injectable()
export class PrismaService extends PrismaClient implements OnModuleInit {
async onModuleInit() {
await this.$connect()
}

- async enableShutdownHooks(app: INestApplication) {
- this.$on('beforeExit', async () => {
- await app.close()
- })
- }
}

相反,如果你需要处理生命周期事件,请使用 NestJS 中内置的 enableShutdownHooks 方法:

¥Instead, use the built-in enableShutdownHooks method in NestJS if you need to handle lifecycle events:

"main.ts"
- prismaService.enableShutdownHooks(app)
+ app.enableShutdownHooks()

删除已弃用的 prisma2 可执行文件

¥Removal of deprecated prisma2 executable

当我们发布 Prisma ORM 2 时,使用了 prisma2 可执行文件以区别于 Prisma 1。在后续版本中,prisma2 cli 接管了 prisma 可执行文件名称。

¥When we released Prisma ORM 2, the prisma2 executable was used in order to differentiate from Prisma 1. In a later release, the prisma2 cli took over the prisma executable name.

不用说,prisma2 可执行文件已被弃用一段时间,现已被删除。如果你的脚本使用 Prisma CLI 作为 prisma2,请将其替换为简单的 prisma

¥Needless to say, the prisma2 executable has been deprecated for some time and is now removed. If your scripts use Prisma CLI as prisma2, please replace it with simply prisma.

删除已弃用的 experimentalFeatures 属性

¥Removal of deprecated experimentalFeatures property

生成器组previewFeatures 字段曾经被称为 experimentalFeatures。我们正在删除该已弃用的属性。

¥The previewFeatures field of the generator block used to be called experimentalFeatures. We are removing that deprecated property.

在 Prisma ORM 5 中,你需要手动更新 experimentalFeaturespreviewFeatures 的引用,或者使用 Prisma VSCode 扩展中的新代码操作。

¥In Prisma ORM 5, you will need to update references of experimentalFeatures to previewFeatures manually or use the new code action in the Prisma VSCode extension.

migration-engine 更名为 schema-engine

¥migration-engine renamed to schema-engine

负责 prisma migrateprisma db 等命令的引擎已从 migration-engine 重命名为 schema-engine,以更好地描述其用途。对于许多用户来说,不需要进行任何更改。但是,如果你需要显式包含或排除此引擎文件,或者出于任何其他原因引用引擎名称,则需要更新代码引用。

¥The engine responsible for commands like prisma migrate and prisma db has been renamed from migration-engine to schema-engine to better describe its use. For many users, no changes will be required. However, if you need to explicitly include or exclude this engine file, or refer to the engine name for any other reason, you will need to update your code references.

无服务器框架示例

¥Example with the Serverless Framework

我们看到的一个例子是使用无服务器框架的项目。在这些情况下,你需要将引用 migration-engine 的所有模式更新为引用 schema-engine

¥One example we have seen is projects using the Serverless Framework. In these instances, you will need to update any patterns that reference migration-engine to instead reference schema-engine.

package:
patterns:
- '!node_modules/.prisma/client/libquery_engine-*'
- 'node_modules/.prisma/client/libquery_engine-rhel-*'
- '!node_modules/prisma/libquery_engine-*'
-- '!node_modules/prisma/migration-engine-*'
-- '!node_modules/prisma/schema-engine-*'
Serverless Framework pattern suggestion

我们文档中的推荐规则 不受此更改的影响,因为它排除了所有不需要的引擎文件。

¥The recommended rule from our documentation is not affected by this change as it excludes all non desired engine files.

package:
patterns:
- '!node_modules/.prisma/client/libquery_engine-*'
- 'node_modules/.prisma/client/libquery_engine-rhel-*'
- '!node_modules/prisma/libquery_engine-*'
-- '!node_modules/@prisma/engines/**'

享受 Prisma ORM 5!

¥Enjoy Prisma ORM 5!