跳到主要内容

升级 Prisma ORM 层

概述

此页面解释了升级过程的第一步:获取您的 Prisma 1 配置并将其升级到 Prisma ORM 2。具体来说,您将学习如何

  1. 将 Prisma ORM 2 CLI 添加为开发依赖项
  2. 创建您的 Prisma ORM 2 schema
  3. 确定您的连接 URL 并连接到您的数据库
  4. 内省您的数据库(到目前为止使用 Prisma 1 管理)
  5. 使用 Prisma 1 升级 CLI 解决新的 Prisma ORM 2 数据模型中的 schema 不兼容性
  6. 安装并生成 Prisma Client

完成这些步骤后,您可以继续阅读下一份指南,其中解释了如何升级应用程序层以使用 Prisma Client 进行数据库查询。

注意:在升级过程中,获取数据库的图形化视图可能会有所帮助。因此,建议使用图形数据库客户端连接到您的数据库,例如 TablePlusPostico

1. 安装 Prisma ORM 2 CLI

Prisma ORM 2 CLI 在 npm 上以 prisma 包的形式提供,并通过 prisma 命令调用。

请注意,以前用于 Prisma 1 的 prisma 命令已重命名为 prisma1。您可以在 此处 了解更多信息。

您可以在 Node.js 项目中安装 Prisma ORM 2 CLI,如下所示(请确保在 package.json 所在的目录中调用此命令)

npm install prisma --save-dev

注意:对于 Prisma 1,通常建议全局安装 CLI。我们现在建议本地安装 Prisma CLI 以防止版本冲突。

您现在可以通过在 prisma CLI 前面加上 npx 来使用本地安装的 CLI

npx prisma

如果您正在一次性升级整个项目,您现在也可以卸载 Prisma 1 CLI(否则请展开下方内容)

# remove global installation
npm uninstall -g prisma1

# remove local installation
npm uninstall prisma1

如果您想并排使用 Prisma 1 CLI,请展开

如果您想继续使用 Prisma 1 CLI,建议删除它的全局安装,并将 prisma1 CLI 添加为开发依赖项

# installs v1.34 of the Prisma 1 CLI
npm uninstall -g prisma
npm install prisma1 --save-dev

您现在可以按如下方式调用它

npx prisma1

请注意,如果您需要小于 1.34 的 CLI 版本(例如 1.30),您可以按如下方式安装它

# installs v1.30 of the Prisma 1 CLI
npm uninstall -g [email protected]
npm install [email protected] --save-dev

您现在可以按如下方式调用它

npx prisma

2. 创建您的 Prisma ORM 2 schema

在本指南中,您将首先使用 prisma init 命令创建一个新的 Prisma schema,然后使用 内省 用数据模型“填充”它。

运行以下命令创建您的 Prisma schema(请注意,如果您已经有一个名为 prisma 的文件夹,则会抛出错误)

npx prisma init

如果您看到以下错误,则需要重命名当前的 prisma 目录

ERROR  A folder called prisma already exists in your project.
Please try again in a project that is not yet using Prisma.

您可以将当前的 prisma 目录重命名为 prisma1,以明确表示它包含以前的 Prisma 1 配置

mv prisma prisma1

现在您可以运行 init,它将成功

npx prisma init

它应该打印以下输出

✔ Your Prisma schema was created at prisma/schema.prisma.
You can now open it in your favorite editor.

Next steps:
1. Set the `DATABASE_URL` in the `.env` file to point to your existing database. If your database has no tables yet, read https://pris.ly/d/getting-started
2. Set the `provider` of your `datasource` block in `schema.prisma` to match your database: `postgresql`, `mysql` or `sqlite`.
3. Run `prisma db pull` to turn your database schema into a Prisma data model.
4. Run `prisma generate` to install Prisma Client. You can then start querying your database.

More information in our documentation:
https://pris.ly/d/getting-started

该命令创建了一个名为 prisma 的新文件夹和两个文件

  • prisma/schema.prisma:您的 Prisma schema,它指定了 数据源生成器数据模型(请注意,数据模型尚不存在,它将通过内省生成)。
  • .env:用于配置数据库 连接 URLdotenv 文件。

您的初始 Prisma schema 如下所示

schema.prisma
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

datasource db {
provider = "mysql"
url = env("DATABASE_URL")
}

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

使用 Prisma 1,您可以在 prisma.yml 中指定要使用的 Prisma Client 的语言变体。使用 Prisma ORM 2,此信息现在在 Prisma schema 中通过 generator 块指定。

注意:与 Prisma 1 不同,Prisma Client 2.0 的 TypeScript 和 JavaScript 变体使用相同的生成器,称为 prisma-client-jsindex.d.ts 中的生成类型始终包含在内,即使在纯 JavaScript 项目中也是如此。这使得即使在不使用 TypeScript 的情况下,也能在 VS Code 中启用自动完成等功能。

3. 确定您的连接 URL 并连接到您的数据库

使用 Prisma 1,数据库连接在 Docker Compose 文件中配置,该文件用于启动 Prisma ORM 服务器。然后,Prisma ORM 服务器公开一个 GraphQL 端点(通过 HTTP),该端点代理来自 Prisma Client 应用程序代码的所有数据库请求。该 HTTP 端点在您的 prisma.yml 中指定。

使用 Prisma ORM 2,HTTP 层不再公开,Prisma Client 2.0 配置为“直接”针对数据库运行请求(即,请求由 Prisma ORM 的 查询引擎 代理,但不再有额外的服务器)。

因此,作为下一步,您需要告诉 Prisma ORM 2 您使用哪种数据库(MySQL 或 PostgreSQL)以及它位于何处

首先,您需要确保 schema.prismadatasource 块上的 provider 字段配置为使用正确的数据库

  • 如果您使用 PostgreSQL,则需要在 provider 字段中定义值 "postgresql"
  • 如果您使用 MySQL,则需要在 provider 字段中定义值 "mysql"

在代码块中的选项卡之间切换以查看两者的示例

datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}

设置 provider 字段后,您可以继续在 .env 文件中配置连接 URL。

假设您用于部署 Prisma ORM 服务器的 Docker Compose 文件中的数据库配置如下所示

docker-compose.yml
PRISMA_CONFIG: |
port: 4466
databases:
default:
connector: mysql
host: mysql
port: 3306
user: root
password: randompassword

还假设您的 prisma.yml 中的 endpoint 配置如下

prisma.yml
endpoint: http://127.0.0.1:4466/myproject/dev

根据这些连接详细信息,您需要在 .env 文件中将 DATABASE_URL 环境变量配置为如下所示

.env
DATABASE_URL="mysql://root:randompassword@localhost:3306/myproject@dev"

请注意,连接 URL 中的数据库名称通常由您的服务名称服务阶段(它们是 prisma.ymlendpoint 的一部分)组成,以 @ 字符分隔。

有时 prisma.yml 中未指定服务名称和阶段

prisma.yml
endpoint: http://127.0.0.1:4466/

在这种情况下,数据库名称必须按如下方式指定

.env
DATABASE_URL="mysql://root:randompassword@localhost:3306/default@default"

连接 URL 页面上了解更多信息。

4. 内省您的数据库

为了本指南的目的,我们将使用以下 Prisma 1 数据模型(选择下面的 SQL 选项卡以查看数据模型在 SQL 中的映射)

type User {
id: ID! @id
email: String @unique
name: String!
role: Role! @default(value: CUSTOMER)
jsonData: Json
profile: Profile
posts: [Post!]!
}

type Post {
id: ID! @id
createdAt: DateTime! @createdAt
updatedAt: DateTime! @updatedAt
title: String!
content: String
published: Boolean! @default(value: false)
author: User @relation(link: TABLE)
categories: [Category!]!
}

type Profile {
id: ID! @id
bio: String
user: User! @relation(link: INLINE)
}

type Category {
id: ID! @id
name: String!
posts: [Post!]!
}

enum Role {
ADMIN
CUSTOMER
}

请注意,此数据模型有三个关系

  • 1-1:UserProfile
  • 1-n:UserPost(通过 _PostToUser 关系表维护)
  • m-n:PostCategory(通过 _CategoryToPost 关系表维护)

现在您可以使用以下命令对数据库运行 Prisma ORM 的内省

npx prisma db pull

这是一个图形化说明,说明了调用 db pull 时发生的情况

Introspect your database

对于上述 Prisma 1 数据模型,这将产生以下 Prisma ORM 2 schema(请注意,模型已重新排序以匹配 Prisma 1 数据模型的初始顺序)

schema.prisma
model User {
id String @id @default(cuid())
email String? @unique
name String
role String
jsonData String?
Profile Profile[]
Post Post[]
}

model Post {
id String @id @default(cuid())
createdAt DateTime
updatedAt DateTime
title String
content String?
published Boolean
Category Category[]
User User[]
}

model Profile {
id String @id @default(cuid())
bio String?
user String? @unique
User User? @relation(fields: [user], references: [id])
}

model Category {
id String @id @default(cuid())
name String
Post Post[]
}

虽然这已经是一个有效的 Prisma ORM 2 schema,但它缺少许多功能,这些功能是其 Prisma 1 等价物的一部分

  • Post 上的 createdAtupdatedAt 字段没有自动生成的日期值
  • User 上的 role 字段没有默认值
  • Post 上的 published 字段没有默认值

此外,还存在许多不一致之处,这些不一致之处导致 Prisma Client API 不太符合习惯/人体工程学

  • UserProfile 是 1-n 关系,而不是 1-1 关系
  • UserPost 是 m-n 关系,而不是 1-n 关系
  • 关系字段为大写(例如 User 上的 ProfilePost
  • User 上的 jsonData 字段类型为 String,而不是 Json
  • User 上的 role 字段类型为 String,而不是 Role,角色枚举定义完全缺失

虽然这些不一致实际上不会影响您在 Prisma Client API 中可用的“功能集”,但它们会让您失去以前存在的某些约束/保证。

例如,Prisma ORM 现在不能保证 User 最多连接到一个 Profile,因为表之间的关系在内省期间被识别为 1-n,因此一个 User 记录可能现在连接到多个 Profile 记录。

另一个问题是,您可以为 jsonDatarole 字段存储任何文本,无论它是否是有效的 JSON 或表示 Role 枚举的值。

要了解有关这些不一致之处的更多信息,请查看 Schema 不兼容性 页面。

在下面,我们将逐步解决这些不兼容性,并使用 Prisma schema 升级 CLI 逐个修复它们。

5. 使用 Prisma schema 升级 CLI 解决 schema 不兼容性

Prisma 1 升级 CLI 是一个交互式工具,可帮助您升级 Prisma schema 并消除上面列出的大部分不一致之处。

Prisma 1 升级 CLI 分为两个主要阶段

  1. 通过纯 SQL 修复数据库 schema
  2. 向 Prisma ORM 2 schema 添加缺失的属性和其他 schema 修复

在第一阶段,它将生成并打印一些 SQL 语句,您应该针对数据库运行这些语句以调整数据库 schema。您可以运行所有语句或其中一部分,然后再继续第二阶段。

在第二阶段,您无需手动执行任何操作。升级 CLI 将通过添加某些 Prisma ORM 级别属性(例如 @default(cuid))@updatedAt)、调整关系字段的名称以匹配 Prisma 1 数据模型中的名称,并确保 Prisma 1 数据模型中双向必需的 1-1 关系在 Prisma ORM 2 schema 中也是必需的,从而更改您的 Prisma schema。

请注意,您可以在流程中的任何时候重新开始,并从第二阶段返回到第一阶段。

在此图中,绿色区域显示第一阶段,蓝色区域显示第二阶段。请注意,您可以选择在阶段之间运行 prisma db pull 以更新您的 Prisma ORM 数据模型

Fixing the schema incompatibilities

要使用升级 CLI,您可以将其本地安装在您的项目中,也可以使用 npx 一次性调用它,如下所示

npx prisma-upgrade prisma1/prisma.yml prisma/schema.prisma

CLI 将向您显示以下消息

◮ Welcome to the interactive Prisma Upgrade CLI that helps with the
upgrade process from Prisma 1 to Prisma ORM 2.

Please read the docs to learn more about the upgrade process:
https://pris.ly/d/how-to-upgrade

➤ Goal
The Upgrade CLI helps you resolve the schema incompatibilities
between Prisma 1 and Prisma ORM 2. Learn more in the docs:
https://pris.ly/d/schema-incompatibilities

➤ How it works
Throughout the process, you'll need to adjust your database schema by sending
SQL statements to it. The SQL statements are provided by the Upgrade CLI.

Note that the Upgrade CLI never makes changes to your database,
you are in full control over any operations that are executed against it.

You can stop and re-run the Upgrade CLI at any time.

These are the different steps of the upgrade process:

1. The Upgrade CLI generates SQL commands for you to run on your database.
2. You run the SQL commands against your database.
3. You run the `npx prisma db pull` command again.
4. You run the `npx prisma-upgrade` command again.
5. The Upgrade CLI adjusts the Prisma ORM 2 schema by adding missing attributes.

➤ Note
It is recommended that you make a full backup of your existing data before starting
the upgrade process. If possible, the migration should be performed in a staging
environment before executed against a production environment.

➤ Help
If you have any questions or run into any problems along the way,
please create an issue at:
https://github.com/prisma/prisma1-upgrade/issues/new

Are you ready? [Y/n]

按下 Y 按钮,然后按 RETURN 键确认以继续。

确认后,CLI 会输出您应该针对数据库运行的 SQL 语句

➤ Adjust your database schema
Run the following SQL statements against your database:

Fix columns with ENUM data types
https://pris.ly/d/schema-incompatibilities#enums-are-represented-as-text-in-database

ALTER TABLE `User` CHANGE `role` `role` ENUM('ADMIN', 'CUSTOMER') NOT NULL;


Add missing `DEFAULT` constraints to the database
https://pris.ly/d/schema-incompatibilities#default-values-arent-represented-in-database

ALTER TABLE `User` CHANGE `role` `role` ENUM('ADMIN', 'CUSTOMER') NOT NULL DEFAULT 'CUSTOMER';
ALTER TABLE `Post` CHANGE `published` `published` TINYINT(1) NOT NULL DEFAULT 0;


Fix columns with JSON data types
https://pris.ly/d/schema-incompatibilities#json-type-is-represented-as-text-in-database

ALTER TABLE `User` CHANGE `jsonData` `jsonData` JSON ;


Replicate `@createdAt` behavior in Prisma ORM 2.0
https://pris.ly/d/schema-incompatibilities#createdat-isnt-represented-in-database

ALTER TABLE `Post` CHANGE `createdAt` `createdAt` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP;


Fix 1-1 relations by adding `UNIQUE` constraints
https://pris.ly/d/schema-incompatibilities#inline-1-1-relations-are-recognized-as-1-n-missing-unique-constraint

ALTER TABLE `Profile` ADD UNIQUE (`user`);


Migrate IDs from varchar(25) to varchar(30)
https://pris.ly/d/schema-incompatibilities#mismatching-cuid-length

SET FOREIGN_KEY_CHECKS=0;
ALTER TABLE `Category` CHANGE `id` `id` char(30) CHARACTER SET utf8 NOT NULL;
ALTER TABLE `Post` CHANGE `id` `id` char(30) CHARACTER SET utf8 NOT NULL;
ALTER TABLE `Profile` CHANGE `id` `id` char(30) CHARACTER SET utf8 NOT NULL;
ALTER TABLE `Profile` CHANGE `user` `user` char(30) CHARACTER SET utf8 ;
ALTER TABLE `User` CHANGE `id` `id` char(30) CHARACTER SET utf8 NOT NULL;
SET FOREIGN_KEY_CHECKS=1;

➤ Breaking changes detected

In order to fully optimize your database schema, you'll need to run a few SQL
statements that can break your Prisma 1 setup. Note that these changes are optional
and if you are upgrading gradually and running Prisma 1 and Prisma ORM 2 side-by-side,
you should not perform these changes yet. Instead, you can perform them whenever
you are ready to completely remove Prisma 1 from your project.
If you are upgrading all at once, you can safely perform these changes now.

Learn more in the docs:
https://pris.ly/d/how-to-upgrade'

注意:如果您看到关于重大更改的注释,您可以暂时忽略它。我们稍后会讨论它。

显示的 SQL 语句分为多个“buckets”,所有这些都旨在解决某个 schema 不兼容性

  • 修复具有 ENUM 数据类型的列
  • 向数据库添加缺失的 DEFAULT 约束
  • 修复具有 JSON 数据类型的列
  • 在 Prisma 2 中复制 @createdAt 行为
  • 通过添加 UNIQUE 约束来修复 1-1 关系

下一步,您可以开始将 SQL 语句发送到您的数据库。请注意,所有这些更改都是非破坏性的,您将能够继续将 Prisma 1 与 Prisma ORM 2 并排使用。

接下来的部分分别介绍了要发送到数据库的不同类型的 SQL 语句。

5.1. 通过纯 SQL 修复数据库 schema(非破坏性)

在本节中,我们将逐步完成打印的 SQL 语句,并逐个针对数据库运行它们。

5.1.1. 修复具有 ENUM 数据类型的列

该工具做的第一件事是帮助您确保 Prisma 1 数据模型中的 enum 定义将在底层数据库中表示为实际的 ENUM 类型,现在它们表示为纯字符串(例如在 MySQL 中为 MEDIUMTEXT)。

CLI 当前显示以下输出

Fix columns with ENUM data types
https://pris.ly/d/schema-incompatibilities#enums-are-represented-as-text-in-database

ALTER TABLE `User` CHANGE `role` `role` ENUM('ADMIN', 'CUSTOMER') NOT NULL;

继续并立即针对您的数据库运行这些语句。

Altering columns to use ENUM with SQL

5.1.2. 向数据库添加缺失的 DEFAULT 约束

接下来,升级 CLI 通过生成 SQL 语句来帮助您解决 默认值未在数据库中表示 的问题,这些 SQL 语句直接将相应的 DEFAULT 约束添加到数据库。

在本例中,缺少两个 DEFAULT 约束,这些约束由该工具建议

Add missing `DEFAULT` constraints to the database
https://pris.ly/d/schema-incompatibilities#default-values-arent-represented-in-database

ALTER TABLE `User` CHANGE `role` `role` ENUM('ADMIN', 'CUSTOMER') NOT NULL DEFAULT 'CUSTOMER';
ALTER TABLE `Post` CHANGE `published` `published` TINYINT(1) NOT NULL DEFAULT 0;

您现在可以使用命令行客户端或 GUI(如 TablePlus)针对数据库运行这些 SQL 语句

TablePlus GUI

5.1.3. 修复具有 JSON 数据类型的列

接下来,该工具帮助您确保 Prisma 1 数据模型中的 Json 字段将在底层数据库中表示为 JSON 列,现在它们表示为纯字符串(例如在 MySQL 中为 MEDIUMTEXT)。

将列类型更改为 JSON 将确保在 Prisma ORM 2 内省期间将该字段正确识别为 Json

CLI 当前显示以下输出

Fix columns with JSON data types
https://pris.ly/d/schema-incompatibilities#json-type-is-represented-as-text-in-database

ALTER TABLE `User` CHANGE `jsonData` `jsonData` JSON ;

您现在可以使用命令行客户端或 GUI(如 TablePlus)针对数据库运行这些 SQL 语句

TablePlus GUI

5.1.4. 在 Prisma ORM 2 中复制 @createdAt 行为

该工具接下来要做的是帮助您解决 @createdAt 的行为未在数据库中表示 的问题

CLI 当前显示以下输出

Replicate `@createdAt` behavior in Prisma ORM 2.0
https://pris.ly/d/schema-incompatibilities#createdat-isnt-represented-in-database

ALTER TABLE `Post` CHANGE `createdAt` `createdAt` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP;

您现在可以使用命令行客户端或 GUI(如 TablePlus)针对数据库运行这些 SQL 语句。

5.1.5. 通过添加 UNIQUE 约束来修复 1-1 关系

现在,该工具将帮助您UserProfile 之间的当前 1-n 关系恢复为 1-1 关系,方法是在数据库中名为 user 的外键列(以 Prisma 1 数据模型中的关系字段命名)中添加 UNIQUE 约束。

CLI 当前显示以下输出

Fix 1-1 relations by adding `UNIQUE` constraints
https://pris.ly/d/schema-incompatibilities#inline-1-1-relations-are-recognized-as-1-n-missing-unique-constraint

ALTER TABLE `Profile` ADD UNIQUE (`user`);

您现在可以使用命令行客户端或 GUI(如 TablePlus)针对数据库运行这些 SQL 语句。

5.1.6. 修复 CUID 长度不匹配

注意:即使在您更改了底层数据库中的列类型之后,这些 SQL 语句仍将继续出现在升级 CLI 中。这目前是升级 CLI 中的一个限制。

最后,该工具将帮助您将当前类型为 VARCHAR(25) 的 ID 列转换为 VARCHAR(30),方法是在数据库中名为 user 的外键列(以 Prisma 1 数据模型中的关系字段命名)中添加 UNIQUE 约束。

CLI 当前显示以下输出

Migrate IDs from varchar(25) to varchar(30)
https://pris.ly/d/schema-incompatibilities#mismatching-cuid-length

SET FOREIGN_KEY_CHECKS=0;
ALTER TABLE `Category` CHANGE `id` `id` char(30) CHARACTER SET utf8 NOT NULL;
ALTER TABLE `Post` CHANGE `id` `id` char(30) CHARACTER SET utf8 NOT NULL;
ALTER TABLE `Profile` CHANGE `id` `id` char(30) CHARACTER SET utf8 NOT NULL;
ALTER TABLE `Profile` CHANGE `user` `user` char(30) CHARACTER SET utf8 ;
ALTER TABLE `User` CHANGE `id` `id` char(30) CHARACTER SET utf8 NOT NULL;
SET FOREIGN_KEY_CHECKS=1;

您现在可以使用命令行客户端或 GUI(如 TablePlus)针对数据库运行这些 SQL 语句。

5.1.7. 检测到重大更改

如果升级 CLI 打印了关于重大更改的注释,则您的数据库 schema 需要进行一些调整,这些调整将破坏 Prisma 1 兼容性才能完全优化。

如果没有检测到重大更改,您可以跳到第 5.2 节

根据您的升级策略,您可以立即执行这些更改,也可以跳到升级 CLI 的下一阶段

  • 如果您遵循逐步并排升级策略,请勿立即执行这些更改,因为它们会破坏您的 Prisma 1 设置。在这种情况下,您可以通过键入 n 并按 RETURN 来继续升级 CLI 的下一阶段。
  • 如果您遵循一次性升级策略,您可以立即执行这些更改。在这种情况下,请继续键入 Y 并按 RETURN

5.2. 通过纯 SQL 修复数据库 schema(破坏性)

在本节中,您将解决破坏您的 Prisma 1 设置的 schema 不兼容性。如果您仍在项目中运行 Prisma 1,请勿执行这些更改!

5.2.1. 修复不正确的 m-n 关系

现在,升级 CLI 帮助您修复 Prisma 1 用关系表表示的所有 1-1 和 1-n 关系,以及 当前仅作为 m-n 关系存在 在您的新 Prisma ORM 2 schema 中。具体来说,UserPost 关系就是这种情况,它当前定义为 m-n,但应该真正是 1-n 关系。

要解决此问题,您需要执行以下迁移

  1. Post 上创建一个新的外键列,以直接链接到 User 表。
  2. 将外键值从关系表迁移到 Post 上的新外键列中。
  3. 删除关系表。

这些说明现在由 CLI 打印

➤ Adjust your database schema
Run the following SQL statements against your database:

Fix one-to-many table relations
https://pris.ly/d/schema-incompatibilities#all-non-inline-relations-are-recognized-as-m-n

ALTER TABLE `Post` ADD COLUMN `authorId` char(25) CHARACTER SET utf8 ;
ALTER TABLE `Post` ADD CONSTRAINT author FOREIGN KEY (`authorId`) REFERENCES `User`(`id`);
UPDATE `Post`, `_PostToUser` SET `Post`.`authorId` = `_PostToUser`.B where `_PostToUser`.A = `Post`.`id`;
DROP TABLE `_PostToUser`;


➤ Next Steps

After you executed one or more of the above SQL statements against your database,
please run the following two commands to refresh your Prisma ORM 2 Schema and check
the changes.

1. Run `npx prisma db pull` again to refresh your Prisma ORM 2 schema.
2. Run `npx prisma-upgrade` again.

If you can't or don't want to execute the remaining SQL statements right now, you can
skip to the last step where the Upgrade CLI adds missing attributes to your Prisma ORM 2
schema that are not picked up by introspection.

Skip to the last step? [Y/n]?

对于此修复,您需要运行三个 SQL 语句

  1. Post 表上创建新列 authorId。此列应为引用 User 表的 id 字段的外键
    ALTER TABLE `Post` ADD COLUMN `authorId` char(25) CHARACTER SET utf8 ;
    ALTER TABLE `Post` ADD CONSTRAINT author FOREIGN KEY (`authorId`) REFERENCES `User`(`id`);
  2. 编写一个 SQL 查询,该查询读取 _PostToUser 关系表中的所有行,并针对每一行
    1. 通过查找列 A 中的值来查找相应的 Post 记录
    2. 将列 B 中的值作为 authorId 的值插入到该 Post 记录中
    UPDATE `Post`, `_PostToUser` SET `Post`.`authorId` = `_PostToUser`.B where `_PostToUser`.A = `Post`.`id`;
  3. 删除 _PostToUser 关系表
    DROP TABLE `_PostToUser`;

Fixing incorrect m-n relations with SQL

在这些命令之后,关系表的列 B 中记录的用户 ID 值将迁移到新的 authorId 列。

5.2. 重新内省您的数据库以更新您的 Prisma schema

此时,您已经使用升级 CLI 解决了 schema 不兼容性。您现在可以通过键入 n 并按 RETURN 来退出升级 CLI。

在本节中,您将通过另一轮内省来更新您的 Prisma schema。这一次,由于数据库 schema 已调整,因此 Prisma schema 之前的缺陷将得到解决

npx prisma db pull

这一次,生成的 Prisma schema 如下所示

schema.prisma
model User {
id String @id
name String
email String? @unique
jsonData Json?
role Role @default(CUSTOMER)
Post Post[]
Profile Profile?
}

model Post {
id String @id
createdAt DateTime @default(now())
updatedAt DateTime
title String
content String?
published Boolean @default(false)
authorId String?
User User? @relation(fields: [authorId], references: [id])
Category Category[] @relation(references: [id])
}

model Category {
id String @id
name String
Post Post[] @relation(references: [id])
}

model Profile {
bio String?
id String @id
user String? @unique
User User? @relation(fields: [user], references: [id])
}

enum Role {
ADMIN
CUSTOMER
}

此 schema 大部分问题已解决,但仍缺少以下内容

5.2. 向 Prisma 2 schema 添加缺失的属性和其他 schema 修复

CLI 现在打印以下内容

➤ What happens next
As a last step, some final adjustments will be made to your Prisma ORM 2 schema
to carry over some Prisma ORM-level attributes that aren't picked up by introspection.

As a last step, some final adjustments will be made to your Prisma ORM 2.0
schema to carry over some Prisma ORM-level attributes that aren't picked
up by introspection.

Warning
Your current Prisma ORM 2.0 schema will be overwritten, so please
make sure you have a backup!

Are you ready? [Y/n]

此时,您要么运行了 CLI 打印的所有 SQL 语句,要么跳过了一些语句。无论哪种方式,您现在都可以继续执行最后一步,让升级 CLI 添加缺失的 Prisma ORM 2 属性。通常,这些属性是以下内容

  • @default(cuid()) 用于您的 @id 字段
  • @updatedAt 用于 Prisma 1 中使用此属性的任何字段
  • @map@@map 作为 Prisma 1 中 @db@@db 的替代品

在这一步中,升级 CLI 还修复了过渡到 Prisma ORM 2 中发生的其他问题

  • 它确保 Prisma 1 中双向必需的 1-1 关系在您的 Prisma ORM 2 schema 中也是必需的
  • 它将关系字段重命名为与 Prisma 1 数据模型中相同的名称 (即将推出)

要应用这些更改,您可以重新运行升级 CLI

npx prisma-upgrade prisma1/prisma.yml prisma/schema.prisma

如果您未解决所有 schema 不兼容性,升级 CLI 现在会打印剩余的 SQL 语句(以及用于迁移 ID 的语句)。您可以在此时忽略它们,并通过在提示时连续键入 Y 并按 RETURN 继续执行最后一步。

如果您已解决所有 schema 不兼容性,则不会打印任何 SQL 语句,并且升级 CLI 仅输出以下内容

$ npx prisma-upgrade prisma1/prisma.yml prisma/schema.prisma

➤ Next Steps

After you executed one or more of the previous SQL statements against your database,
please run the following two commands to refresh your Prisma ORM 2 schema and check
the changes.

1. Run `npx prisma db pull` again to refresh your Prisma ORM 2 schema.
2. Run `npx prisma-upgrade` again.

If you can't or don't want to execute the remaining SQL statements right now, you can
skip to the last step where the Upgrade CLI adds missing attributes to your Prisma ORM 2
schema that are not picked up by introspection.

Skip to the last step? [Y/n]?

再次键入 Y 并按 RETURN 以确认。

升级 CLI 的最终提示现在要求您确认它将对您的 Prisma schema 进行的上述更改

➤ What happens next
As a last step, some final adjustments will be made to your Prisma ORM 2 schema
to carry over some Prisma ORM-level attributes that aren't picked up by introspection.

As a last step, some final adjustments will be made to your Prisma ORM 2.0
schema to carry over some Prisma ORM-level attributes that aren't picked
up by introspection.

Warning
Your current Prisma ORM 2.0 schema will be overwritten, so please
make sure you have a backup!

Are you ready? [Y/n]

最后一次,键入 Y 并按 RETURN 以确认。

这是升级 CLI 的最终输出

Updating prisma/schema.prisma...
Done updating prisma/schema.prisma!

✔ Congratulations, you're all set!

➤ Note
If you didn't execute all generated SQL commands against your database,
you can re-run the Upgrade CLI at any time.

Note that the Upgrade CLI doesn't resolve all of the schema incompatibilities
between Prisma 1 and Prisma ORM 2. If you want to resolve the remaining ones,
you can do so manually by following this guide:
https://pris.ly/d/upgrading-the-prisma-layer

➤ Next steps
Otherwise you can continue your upgrade process by installing Prisma Client 2:
npm install @prisma/client

You can find guides for different upgrade scenarios in the docs:
https://pris.ly/d/upgrade-from-prisma-1

5.3. 最终结果

Prisma schema 的最终版本应如下所示

schema.prisma
model User {
id String @id @default(cuid())
name String
email String? @unique
jsonData Json?
role Role @default(CUSTOMER)
Post Post[]
Profile Profile?
}

model Post {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
title String
content String?
published Boolean @default(false)
authorId String?
User User? @relation(fields: [authorId], references: [id])
Category Category[] @relation(references: [id])
}

model Profile {
id String @id @default(cuid())
bio String?
user String? @unique
User User? @relation(fields: [user], references: [id])
}

model Category {
id String @id @default(cuid())
name String
Post Post[] @relation(references: [id])
}

enum Role {
ADMIN
CUSTOMER
}

5.4. 重命名关系字段

您会注意到此版本的 Prisma ORM 2 schema 的一件事是,所有 关系字段 都以其各自的模型命名,例如

schema.prisma
model User {
Post Post[]
Profile Profile?
}

model Post {
User User? @relation(fields: [authorId], references: [id])
Category Category[] @relation(references: [id])
}

model Profile {
User User? @relation(fields: [user], references: [id])
}

model Category {
Post Post[] @relation(references: [id])
}

这并不理想,实际上您可以手动将所有这些字段重命名为以前的版本!

由于所有关系字段都是虚拟的,这意味着它们不会在数据库中显式存在,因此您可以随意命名它们。在本例中,所有关系字段均为小写,有时为复数形式。

以下是重命名后的外观

schema.prisma
model User {
posts Post[]
profile Profile?
}

model Post {
author User? @relation(fields: [authorId], references: [id])
categories Category[] @relation(references: [id])
}

model Profile {
user String? @unique
owner User? @relation(fields: [user], references: [id])
}

model Category {
posts Post[] @relation(references: [id])
}

注意:对于 UserProfile 之间的 1-1 关系,无法为关系字段设置旧名称 user。这是因为与已存在的保存外键的 关系标量 字段存在命名冲突。在这种情况下,您可以选择其他名称,或者通过 SQL 直接在数据库中重命名外键列。

5.5. 解决剩余的 schema 不兼容性

升级 CLI 尚未解决一些 schema 不兼容性。此时,您仍然没有修复 标量列表。您可以在 Schema 不兼容性 页面上找到针对此问题和其他问题的推荐解决方法。

6. 安装并生成 Prisma Client

现在您已经准备好 Prisma ORM 2 schema,您可以使用以下命令安装 Prisma Client

npm install @prisma/client

7. 后续步骤

恭喜,您现在已将 Prisma ORM 层升级到 Prisma ORM 2!从这里开始,您可以继续使用以下指南之一更新您的应用程序代码

  • 旧版 Nexus 到新版 Nexus:如果您当前正在使用 GraphQL Nexus 运行 Prisma 1,请选择本指南。
  • prisma-binding 到 Nexus:如果您当前正在使用 prisma-binding 运行 Prisma 1,并且想要升级到 Nexus (和 TypeScript),请选择本指南。
  • prisma-binding 到 SDL-first:如果您当前正在使用 prisma-binding 运行 Prisma 1,并且想要升级到 SDL-first GraphQL 服务器,请选择本指南。
  • REST API:如果您当前正在使用 Prisma Client 1 运行 Prisma 1 并且正在构建 REST API,请选择本指南。

奖励:Prisma Client API 比较

本节包含 Prisma 1 和 Prisma ORM 2 的 Prisma Client API 的高级并排比较。有关新 Prisma Client API 的更多详细信息,您可以浏览 Prisma Client 文档。

读取单个记录

Prisma Client (v1)
const user = await prisma.user({ id: 1 })
Prisma Client (v2)
await prisma.user.findUnique({
where: { id: 1 },
})

读取记录列表

Prisma Client (v1)
const user = await prisma.users()
Prisma Client (v2)
await prisma.user.findMany()

过滤列表

Prisma Client (v1)
const users = await prisma.users({
where: {
name: 'Alice',
},
})
Prisma Client (v2)
await prisma.user.findMany({
where: {
name: 'Alice',
},
})

分页列表

Prisma Client (v1)
const posts = await prisma.posts({
skip: 5,
first: 10,
})
Prisma Client (v2)
await prisma.user.findMany({
skip: 5,
take: 10,
})

注意:您可以在相应的发行说明或文档中的 分页 页面了解有关新分页 API 的更多信息。

排序列表

Prisma Client (v1)
await prisma.posts({
orderBy: 'title_ASC',
})
Prisma Client (v2)
await prisma.posts({
orderBy: {
title: 'asc',
},
})

创建记录

Prisma Client (v1)
await prisma.createUser({
name: 'Alice',
})
Prisma Client (v2)
await prisma.user.create({
data: {
name: 'Alice',
},
})

更新记录

Prisma Client (v1)
await prisma.updateUser({
where: { id: 1 },
data: {
name: 'James',
email: '[email protected]',
},
})
Prisma Client (v2)
await prisma.user.update({
where: { id: 1 },
data: {
name: 'James',
email: '[email protected]',
},
})

删除记录

Prisma Client (v1)
await prisma.deleteUser({ id: 1 })
Prisma Client (v2)
await prisma.user.delete({
where: { id: 1 },
})

选择字段 & 加载关联关系

在 Prisma 1 中,选择特定字段和/或加载对象关联关系的唯一方法是使用基于字符串的 $fragment$graphql 函数。 使用 Prisma ORM 2,现在可以使用 selectinclude 以清晰且类型安全的方式完成此操作。

这种方法的另一个好处是您可以在任何 Prisma Client 查询上使用 selectinclude,例如 findUniquefindManycreateupdatedelete 等。

Prisma Client (v1)
await prisma.user({ id: 1 }).$fragment(`
fragment NameAndEmail on User { id email }`
`)
Prisma Client (v2)
await prisma.user.findUnique({
where: { id: 1 },
select: {
id: true,
email: true,
},
})

例如,在 Prisma 1 中,创建新记录并且仅检索返回对象中的 id 是不可能的。使用 Prisma ORM 2,您可以按如下方式实现此目的

await prisma.user.create({
data: {
name: 'Alice',
},
select: {
id: true,
},
})