升级到 Prisma ORM 7
从早期 Prisma ORM 版本升级到 Prisma ORM v7 会引入重大变更。本指南解释了此升级可能如何影响你的应用,并提供有关如何处理任何更改的说明。
¥Prisma ORM v7 introduces breaking changes when you upgrade from an earlier Prisma ORM version. This guide explains how this upgrade might affect your application and gives instructions on how to handle any changes.
Questions answered in this page
-
Prisma 7 有哪些变化?
¥What changed in Prisma 7?
-
如何安全升级?
¥How do I upgrade safely?
-
哪些重大更改会影响我的应用?
¥Which breaking changes affect my app?
对于使用 AI 代理的开发者,我们提供了一个 迁移提示,你可以将其添加到你的项目中以实现自动迁移。
¥For developers using AI Agents, we have a migration prompt that you can add to your project for automatic migrations.
如果你使用的是 MongoDB,请注意 Prisma ORM v7 尚不支持 MongoDB。目前,你应该继续使用 Prisma ORM v6。v7 版本即将支持 MongoDB。
¥If you are using MongoDB, please note that Prisma ORM v7 does not yet support MongoDB. You should continue using Prisma ORM v6 for now. Support for MongoDB is coming soon in v7.
将 prisma 和 @prisma/client 包升级到 v7
¥Upgrade the prisma and @prisma/client packages to v7
要从早期版本升级到 Prisma ORM v7,你需要同时更新 prisma 和 @prisma/client 软件包:
¥To upgrade to Prisma ORM v7 from an earlier version, you need to update both the prisma and @prisma/client packages:
- npm
- yarn
- pnpm
- bun
npm install @prisma/client@7
npm install -D prisma@7
yarn up prisma@7 @prisma/client@7
pnpm upgrade prisma@7 @prisma/client@7
bun add @prisma/client@7
bun add prisma@7 --dev
在升级之前,请检查下面的每项重大更改,以了解升级可能如何影响你的应用。
¥Before you upgrade, check each breaking change below to see how the upgrade might affect your application.
重大变化
¥Breaking changes
本节概述了 Prisma ORM v7 中的重大变更。
¥This section gives an overview of breaking changes in Prisma ORM v7.
最低支持的 Node.js 和 TypeScript 版本
¥Minimum supported Node.js & TypeScript versions
| 最低版本 | 推荐 | |
|---|---|---|
| 节点 | 20.19.0 | 22.x |
| TypeScript | 5.4.0 | 5.9.x |
ESM 支持
¥ESM support
Prisma ORM 现在以 ES 模块的形式发布,该模块格式受 Bun、Deno 和 Node 支持。将 package.json 中的 type 字段设置为 module
¥Prisma ORM now ships as an ES module, the module format supported in Bun, Deno, and Node. Set the
type field in your package.json to module
{
"type": "module",
"scripts": {...},
}
如果你使用 TypeScript,则需要配置 tsconfig.json 以使其能够使用 ES 模块。
¥If you are using TypeScript, you need to configure your tsconfig.json to be able to consume ES modules
{
"compilerOptions": {
"module": "ESNext",
"moduleResolution": "node",
"target": "ES2023",
"strict": true,
"esModuleInterop": true
}
}
Prisma schema 更改
¥Prisma schema changes
旧版 prisma-client-js 提供程序将在 Prisma ORM 的未来版本中移除。升级到使用全新无 Rust 客户端的 prisma-client 提供程序。这将加快查询速度,减小包大小,并在部署到服务器时占用更少的系统资源。
¥The older prisma-client-js provider will be removed in future releases of Prisma ORM. Upgrade to
the new prisma-client provider which uses the new Rust-free client. This will give you faster
queries, smaller bundle size, and require less system resources when deployed to your server.
此外,生成器块中的 output 字段现在是必填项。默认情况下,Prisma Client 将不再在 node_modules 中生成。你必须指定自定义输出路径。
¥Additionally, the output field is now required in the generator block. Prisma Client will no longer be generated in node_modules by default. You must specify a custom output path.
之前
¥Before
generator client {
provider = "prisma-client-js"
engineType = "binary"
}
之后
¥After
generator client {
provider = "prisma-client"
output = "./generated/prisma"
}
运行 npx prisma generate 后,你需要更新导入语句以使用新生成的路径:
¥After running npx prisma generate, you'll need to update your imports to use the new generated path:
// Before
import { PrismaClient } from '@prisma/client'
// After
import { PrismaClient } from './generated/prisma/client'
导入路径取决于你放置生成的客户端的位置。根据你的 output 配置和要导入的文件位置调整路径。
¥The import path depends on where you place your generated client. Adjust the path based on your output configuration and the location of the file you're importing from.
此外,datasource 块中的其他字段(例如 url、directUrl 和 shadowDatabaseUrl)已被弃用。你可以在 Prisma Config 中进行配置。
¥Additionally other fields such as url, directUrl, and shadowDatabaseUrl in the datasource block are deprecated. You can configure them in the Prisma Config.
如果你之前使用 directUrl 运行迁移,则需要将 directUrl 的值传递到 prisma.config.ts 的 url 字段中,因为 Prisma CLI 使用 url 中定义的连接字符串进行迁移。
¥If you were previously using directUrl to run migrations then you need to pass the directUrl value in the url field of prisma.config.ts instead as the connection string defined in url is used by Prisma CLI for migrations.
import 'dotenv/config'
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
datasource: {
url: env('DATABASE_URL'),
shadowDatabaseUrl: env('SHADOW_DATABASE_URL')
},
})
驱动程序适配器和客户端实例化
¥Driver adapters and client instantiation
创建新 Prisma Client 的方式已更改,现在所有数据库都需要驱动程序适配器。此更改符合使 Prisma 主客户端尽可能精简和开放的趋势。例如,如果你使用的是 Prisma Postgres,则现在需要 @prisma/adapter-pg 适配器。这也意味着创建新 Prisma 客户端的签名略有变化:
¥The way to create a new Prisma Client has changed to require a driver adapter for all databases.
This change aligns with the move to make the main Prisma Client as lean and open as possible. For
instance, if you are using Prisma Postgres, you now need the @prisma/adapter-pg adapter. This also
means the signature for creating a new Prisma Client has changed slightly:
驱动程序适配器使用底层 Node.js 数据库驱动程序的连接池设置,这可能与 Prisma ORM v6 的默认设置有很大差异。例如,pg 驱动程序默认没有连接超时(0),而 Prisma ORM v6 使用 5 秒超时。
¥Driver adapters use the connection pool settings from the underlying Node.js database driver, which may differ significantly from Prisma ORM v6 defaults. For example, the pg driver has no connection timeout by default (0), while Prisma ORM v6 used a 5-second timeout.
如果在升级后遇到超时问题,请配置你的驱动程序适配器以匹配 v6 的行为。有关每个数据库的详细配置示例,请参阅 连接池指南。
¥If you experience timeout issues after upgrading, configure your driver adapter to match v6 behavior. See the connection pool guide for detailed configuration examples for each database.
之前
¥Before
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient({
datasources: {
db: { url: process.env.DATABASE_URL },
},
datasourceUrl: process.env.DATABASE_URL,
});
之后
¥After
import { PrismaClient } from './generated/prisma/client';
import { PrismaPg } from '@prisma/adapter-pg';
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL
});
const prisma = new PrismaClient({ adapter });
如果你使用 SQLite,则可以使用 @prisma/adapter-better-sqlite3:
¥If you are using SQLite, you can use the @prisma/adapter-better-sqlite3:
import { PrismaClient } from './generated/prisma/client';
import { PrismaBetterSqlite3 } from '@prisma/adapter-better-sqlite3';
const adapter = new PrismaBetterSqlite3({
url: process.env.DATABASE_URL || 'file:./dev.db'
})
export const prisma = new PrismaClient({ adapter })
Prisma Accelerate 从 v6 升级的用户加速
¥Prisma Accelerate users upgrading from v6
如果你在 v6 中使用了 Prisma Accelerate(包括 Prisma Postgres 的 prisma+postgres:// URL),请继续使用带有 Accelerate 扩展的 Accelerate URL。不要将 Accelerate URL 传递给驱动程序适配器 - PrismaPg 需要直接的数据库连接字符串,否则将使用 prisma:// 或 prisma+postgres:// 失败。
¥If you used Prisma Accelerate (including Prisma Postgres' prisma+postgres:// URLs) in v6, keep using the Accelerate URL with the Accelerate extension. Do not pass the Accelerate URL to a driver adapter—PrismaPg expects a direct database connection string and will fail with prisma:// or prisma+postgres://.
-
将你的 Accelerate URL 保留在
.env中(例如DATABASE_URL="prisma://..."或prisma+postgres://...)。¥Keep your Accelerate URL in
.env(for exampleDATABASE_URL="prisma://..."orprisma+postgres://...). -
你可以将
prisma.config.ts直接指向同一个 Accelerate URL 以进行 CLI 操作:¥You can point
prisma.config.tsdirectly to that same Accelerate URL for CLI operations:
import 'dotenv/config'
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
schema: 'prisma/schema.prisma',
datasource: {
url: env('DATABASE_URL'),
},
})
-
如果你希望为迁移使用单独的直接 URL,你仍然可以像上面一样使用
DIRECT_DATABASE_URL,但这对于 Accelerate 用户来说是可选的。¥If you prefer a separate direct URL for migrations, you can still use
DIRECT_DATABASE_URLas above—but it's optional for Accelerate users.
-
使用 Accelerate URL 和扩展名实例化 Prisma Client(无需适配器):
¥Instantiate Prisma Client with the Accelerate URL and extension (no adapter):
import { PrismaClient } from './generated/prisma/client'
import { withAccelerate } from '@prisma/extension-accelerate'
export const prisma = new PrismaClient({
accelerateUrl: process.env.DATABASE_URL,
}).$extends(withAccelerate())
如果你之后从 Accelerate 切换到直接 TCP,请提供指向相应驱动程序适配器的直接 URL(例如 PrismaPg),而不是 accelerateUrl。
¥If you later switch away from Accelerate to direct TCP, provide the direct URL to the appropriate driver adapter (for example PrismaPg) instead of accelerateUrl.
显式加载环境变量
¥Explicit loading of environment variables
在 Prisma ORM 7.0.0 中,默认情况下不加载环境变量。开发者需要在调用 prisma CLI 时显式加载变量。可以使用 dotenv 等库来管理环境变量的加载,方法是读取相应的 .env 文件。
¥In Prisma ORM 7.0.0, environment variables are not loaded by default. Instead developers need to
explicitly load the variables when calling the prisma CLI. Libraries like dotenv can be used to manage loading environment variables by reading the appropriate .env file.
- npm
- yarn
- pnpm
npm install dotenv
yarn add dotenv
pnpm add dotenv
对于 bun 用户,无需任何操作,bun 会自动加载 .env 文件。
¥For bun users, no action is required as bun will automatically load .env files.
Prisma 配置现在用于配置 Prisma CLI
¥Prisma config is now used to configure the Prisma CLI
Prisma 配置现在是配置 Prisma CLI 与数据库交互方式的默认位置。现在,你可以配置数据库 URL、模式位置、迁移输出和自定义种子脚本。
¥Prisma Config is now the default place for configuring how the Prisma CLI interacts with your database. You now configure your database URL, schema location, migration output, and custom seed scripts.
prisma.config.ts 文件应放置在项目根目录(即 package.json 所在的目录)。
¥The prisma.config.ts file should be placed at the root of your project (where your package.json is located).
import 'dotenv/config'
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
// the main entry for your schema
schema: 'prisma/schema.prisma',
// where migrations should be generated
// what script to run for "prisma db seed"
migrations: {
path: 'prisma/migrations',
seed: 'tsx prisma/seed.ts',
},
// The database URL
datasource: {
// Type Safe env() helper
// Does not replace the need for dotenv
url: env('DATABASE_URL'),
},
})
客户端扩展中已移除指标功能
¥Metrics has been removed from the Client extensions
指标预览功能在 Prisma ORM 6.14.0 中已弃用,并在 Prisma ORM 7.0.0 中移除。如果你需要此功能,可以使用数据库的底层驱动程序适配器或客户端扩展来提供此信息。
¥The Metrics preview feature was deprecated in Prisma ORM 6.14.0 and has been removed for Prisma ORM 7.0.0. If you need this feature, you can use the underlying driver adapter for your database, or Client Extensions to make this information available.
例如,一个基本的 totalQueries 计数器:
¥For example, a basic totalQueries counter:
const total = 0
const prisma = new PrismaClient().$extends({
client: {
$log: (s: string) => console.log(s),
async $totalQueries() { return total; },
},
query: {
$allModels: {
async $allOperations({ query, args }) {
total += 1;
return query(args);
},
},
},
})
async function main() {
prisma.$log('Hello world')
const totalQueries = await prisma.$totalQueries()
console.log(totalQueries)
}
在生成的数据库中映射枚举值 TypeScript
¥Mapped enum values in generated TypeScript
目前已知一个 bug,即在 Prisma Client 操作中使用映射枚举值(例如 create、update 等)会导致运行时错误。生成的 TypeScript 类型需要映射值,但 Prisma Client 引擎需要模式名称。此问题正在 GitHub 问题 #28591 中跟踪。在问题修复之前,你需要使用下面描述的解决方法。
¥There is currently a known bug where using mapped enum values with Prisma Client operations (like create, update, etc.) causes runtime errors. The generated TypeScript types expect the mapped values, but the Prisma Client engine expects the schema names. This issue is being tracked in GitHub issue #28591. Until this is fixed, you need to use workarounds described below.
在 Prisma ORM v7 中,生成的 TypeScript 枚举值现在使用 @map 值而不是模式名称。这是 v6 版本的重大变更。
¥In Prisma ORM v7, the generated TypeScript enum values now use the @map values instead of the schema names. This is a breaking change from v6.
Prisma ORM v6 版本更新前
¥Before Prisma ORM v6
给定以下 Prisma schema:
¥Given this Prisma schema:
enum SuggestionStatus {
PENDING @map("pending")
ACCEPTED @map("accepted")
REJECTED @map("rejected")
}
在 v6 版本中,生成的 TypeScript 枚举如下:
¥In v6, the generated TypeScript enum would be:
export const SuggestionStatus = {
PENDING: 'PENDING',
ACCEPTED: 'ACCEPTED',
REJECTED: 'REJECTED'
} as const
Prisma ORM v7 版本更新后
¥After Prisma ORM v7
在 v7 版本中,相同的模式会生成:
¥In v7, the same schema generates:
export const SuggestionStatus = {
PENDING: 'pending',
ACCEPTED: 'accepted',
REJECTED: 'rejected'
} as const
这意味着 SuggestionStatus.PENDING 现在的计算结果为 "pending" 而不是 "PENDING"。
¥This means that SuggestionStatus.PENDING now evaluates to "pending" instead of "PENDING".
迁移步骤
¥Migration steps
如果你使用映射枚举,则需要更新所有依赖于枚举值是模式名称而非映射值的代码。
¥If you're using mapped enums, you'll need to update any code that relies on the enum values being the schema names rather than the mapped values.
临时解决方案
¥Temporary workaround
在解决 未解决的问题 问题之前,你需要使用字符串字面值作为模式名称,而不是生成的枚举值:
¥Until we resolve the open issue, you need to use the schema name as a string literal instead of the generated enum value:
// This may cause a TypeScript error but works at runtime
await prisma.suggestion.create({
data: {
status: "PENDING" as any, // Use schema name, not mapped value
},
});
或者,如果你不需要数据库值与模式名称完全不同,可以暂时从枚举值中移除 @map 指令:
¥Alternatively, you can temporarily remove the @map directives from your enum values if you don't strictly need the database values to differ from the schema names:
// Before: with @map directives
enum SuggestionStatus {
PENDING @map("pending")
ACCEPTED @map("accepted")
REJECTED @map("rejected")
}
// After: without @map directives
enum SuggestionStatus {
PENDING
ACCEPTED
REJECTED
}
更改后,模式名称和数据库值都将是 PENDING、ACCEPTED 和 REJECTED,生成的 TypeScript 枚举将能与 Prisma 客户端操作正确配合使用。
¥With this change, both the schema names and the database values will be PENDING, ACCEPTED, and REJECTED, and the generated TypeScript enum will work correctly with Prisma Client operations.
客户端中间件已移除
¥Client middleware has been removed
客户端中间件 API 已被移除。如果可能,请使用 客户端扩展。
¥The client middleware API has been removed. If possible, use Client Extensions.
// ❌ Old (removed)
prisma.$use(async (params, next) => {
// middleware logic
return next(params)
})
// ✅ New (use extensions)
const prisma = new PrismaClient().$extends({
query: {
user: {
async findMany({ args, query }) {
// extension logic
return query(args)
}
}
}
})
已移除迁移期间的自动填充功能
¥Automatic seeding during migrations has been removed
在 Prisma ORM v6 及更早版本中,运行 prisma migrate dev 或 prisma migrate reset 会在应用迁移后自动执行你的种子脚本。Prisma ORM v7 中已移除此自动初始化行为。
¥In Prisma ORM v6 and earlier, running prisma migrate dev or prisma migrate reset would automatically execute your seed script after applying migrations. This automatic seeding behavior has been removed in Prisma ORM v7.
要在 v7 中初始化数据库,你必须显式运行:
¥To seed your database in v7, you must explicitly run:
npx prisma db seed
已移除 CLI 标志 --skip-generate 和 --skip-seed
¥CLI flags --skip-generate and --skip-seed removed
prisma migrate dev 和 prisma db push 中已移除 --skip-generate 标志。prisma migrate dev 中已移除 --skip-seed 标志。
¥The --skip-generate flag was removed from prisma migrate dev and prisma db push. The --skip-seed flag was removed from prisma migrate dev.
migrate dev 和 db push 不再自动运行 prisma generate。你必须显式运行 prisma generate 才能生成 Prisma Client。
¥migrate dev and db push no longer run prisma generate automatically. You must run prisma generate explicitly to generate Prisma Client.
--schema 和 --url 标志已从 prisma db execute 中移除
¥--schema and --url flags removed from prisma db execute
prisma db execute 命令已移除 --schema 和 --url 标志。以前,你可以使用 --schema 指定 Prisma 模式文件的路径,或使用 --url 直接指定数据库 URL。接下来,需要在 prisma.config.ts 中配置数据库连接。
¥The --schema and --url flags have been removed from the prisma db execute command. Previously, you could use --schema to specify the path to your Prisma schema file, or --url to specify the database URL directly. Now, the database connection must be configured in prisma.config.ts.
版本更新前 (v6)
¥Before (v6)
# Using --schema
prisma db execute --file ./script.sql --schema prisma/schema.prisma
# Using --url
prisma db execute --file ./script.sql --url "$DATABASE_URL"
版本更新后 (v7)
¥After (v7)
请在 prisma.config.ts 中配置数据库连接:
¥Configure your database connection in prisma.config.ts instead:
import 'dotenv/config'
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
schema: 'prisma/schema.prisma',
datasource: {
url: env('DATABASE_URL'),
},
})
然后运行不带 --schema 或 --url 的命令:
¥Then run the command without --schema or --url:
prisma db execute --file ./script.sql
prisma migrate diff CLI 选项已更改
¥prisma migrate diff CLI options changed
prisma migrate diff 中的几个选项已被移除,并替换为使用 prisma.config.ts 的新选项:
¥Several options have been removed from prisma migrate diff and replaced with new options that use prisma.config.ts:
| 已移除选项 | 替代方案 |
|---|---|
--from-url | --from-config-datasource |
--to-url | --to-config-datasource |
--from-schema-datasource | --from-config-datasource |
--to-schema-datasource | --to-config-datasource |
--shadow-database-url | 在 prisma.config.ts 中配置 |
版本更新前 (v6)
¥Before (v6)
prisma migrate diff \
--from-url "$DATABASE_URL" \
--to-schema schema.prisma \
--script
版本更新后 (v7)
¥After (v7)
请在 prisma.config.ts 中配置数据库连接,然后使用 --from-config-datasource 或 --to-config-datasource:
¥Configure your database connection in prisma.config.ts, then use --from-config-datasource or --to-config-datasource:
prisma migrate diff \
--from-config-datasource \
--to-schema schema.prisma \
--script
已移除各种环境变量
¥Various environment variables have been removed
我们移除了一些 Prisma 特有的环境变量。
¥We've removed a small selection of Prisma-specific environment variables.
-
PRISMA_CLI_QUERY_ENGINE_TYPE -
PRISMA_CLIENT_ENGINE_TYPE -
PRISMA_QUERY_ENGINE_BINARY -
PRISMA_QUERY_ENGINE_LIBRARY -
PRISMA_GENERATE_SKIP_AUTOINSTALL -
PRISMA_SKIP_POSTINSTALL_GENERATE -
PRISMA_GENERATE_IN_POSTINSTALL -
PRISMA_GENERATE_DATAPROXY -
PRISMA_GENERATE_NO_ENGINE -
PRISMA_CLIENT_NO_RETRY -
PRISMA_MIGRATE_SKIP_GENERATE -
PRISMA_MIGRATE_SKIP_SEED