升級 Prisma ORM 層 (MySQL)
概述
本頁解釋了升級過程的第一步:將你的 Prisma 1 配置升級到 Prisma ORM 2。具體來說,你將學習如何
- 新增 Prisma ORM 2 CLI 作為開發依賴
- 建立你的 Prisma ORM 2 schema
- 確定你的連線 URL 並連線到資料庫
- 內省你的資料庫(到目前為止由 Prisma 1 管理)
- 使用 Prisma 1 升級 CLI 來解決新 Prisma ORM 2 資料模型中的 schema 不相容性
- 安裝並生成 Prisma Client
完成這些步驟後,你可以繼續閱讀下一份指南,它解釋瞭如何升級應用程式層以使用 Prisma Client 進行資料庫查詢。
注意:在升級過程中,獲取資料庫的圖形檢視可能會很有幫助。因此,建議使用圖形資料庫客戶端連線到你的資料庫,例如 TablePlus 或 Postico。
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 來使用其本地安裝。
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 prisma@1.30
npm install prisma@1.30 --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:一個 dotenv 檔案,用於配置你的資料庫 連線 URL。
你的初始 Prisma schema 如下所示
// 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 中,此資訊現在透過 generator 塊在 Prisma schema 中指定。
注意:與 Prisma 1 不同,Prisma Client 2.0 的 TypeScript 和 JavaScript 變體使用相同的生成器,名為
prisma-client-js。index.d.ts中生成的型別始終包含在內,即使在純 JavaScript 專案中也是如此。這使得即使不使用 TypeScript,也能在 VS Code 中實現自動補全等功能。
3. 確定你的連線 URL 並連線到資料庫
在 Prisma 1 中,資料庫連線是在用於啟動 Prisma ORM 伺服器的 Docker Compose 檔案中配置的。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.prisma 中 datasource 塊上的 provider 欄位配置為使用正確的資料庫
- 如果你使用 PostgreSQL,它需要在
provider欄位中定義值"postgresql"。 - 如果你使用 MySQL,它需要在
provider欄位中定義值"mysql"。
在程式碼塊中切換選項卡以檢視兩者的示例
- PostgreSQL
- MySQL
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
datasource db {
provider = "mysql"
url = env("DATABASE_URL")
}
設定 provider 欄位後,你可以繼續在 .env 檔案中配置連線 URL。
假設你用於部署 Prisma ORM 伺服器的 Docker Compose 檔案中的資料庫配置如下所示
PRISMA_CONFIG: |
port: 4466
databases:
default:
connector: mysql
host: mysql
port: 3306
user: root
password: randompassword
另外假設你的 prisma.yml 中的 endpoint 配置如下
endpoint: http://:4466/myproject/dev
根據這些連線詳情,你需要在你的 .env 檔案中配置 DATABASE_URL 環境變數,如下所示
DATABASE_URL="mysql://root:randompassword@localhost:3306/myproject@dev"
請注意,連線 URL 中的資料庫名稱通常由你的服務名稱和服務階段(在 prisma.yml 的 endpoint 中)組成,用 @ 字元分隔。
有時 prisma.yml 中未指定服務名稱和階段
endpoint: http://:4466/
在這種情況下,資料庫名稱必須按如下方式指定
DATABASE_URL="mysql://root:randompassword@localhost:3306/default@default"
在 連線 URL 頁面瞭解更多資訊。
4. 內省你的資料庫
為本指南目的,我們將使用以下 Prisma 1 資料模型(選擇下方的 SQL 選項卡以檢視該資料模型在 SQL 中的對映)
- Prisma 1 資料模型
- 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
}
CREATE TABLE"User" (
id character varying(25) PRIMARY KEY,
email text,
name text NOT NULL,
role text NOT NULL,
"jsonData" text
);
CREATE UNIQUE INDEX "User_pkey" ON"User"(id text_ops);
CREATE UNIQUE INDEX "default$default.User.email._UNIQUE" ON"User"(email text_ops);
CREATE TABLE"Post" (
id character varying(25) PRIMARY KEY,
title text NOT NULL,
published boolean NOT NULL,
"createdAt" timestamp(3) without time zone NOT NULL,
"updatedAt" timestamp(3) without time zone NOT NULL,
content text
);
CREATE UNIQUE INDEX "Post_pkey" ON"Post"(id text_ops);
CREATE TABLE"Profile" (
id character varying(25) PRIMARY KEY,
bio text,
user character varying(25) REFERENCES"User"(id) ON DELETE SET NULL
);
CREATE UNIQUE INDEX "Profile_pkey" ON"Profile"(id text_ops);
CREATE TABLE"Category" (
id character varying(25) PRIMARY KEY,
name text NOT NULL
);
CREATE UNIQUE INDEX "Category_pkey" ON"Category"(id text_ops);
CREATE TABLE"_PostToUser" (
"A" character varying(25) NOT NULL REFERENCES"Post"(id) ON DELETE CASCADE,
"B" character varying(25) NOT NULL REFERENCES"User"(id) ON DELETE CASCADE
);
CREATE UNIQUE INDEX "_PostToUser_AB_unique" ON"_PostToUser"("A" text_ops,"B" text_ops);
CREATE INDEX "_PostToUser_B" ON"_PostToUser"("B" text_ops);
CREATE TABLE"_CategoryToPost" (
"A" character varying(25) NOT NULL REFERENCES"Category"(id) ON DELETE CASCADE,
"B" character varying(25) NOT NULL REFERENCES"Post"(id) ON DELETE CASCADE
);
CREATE UNIQUE INDEX "_CategoryToPost_AB_unique" ON"_CategoryToPost"("A" text_ops,"B" text_ops);
CREATE INDEX "_CategoryToPost_B" ON"_CategoryToPost"("B" text_ops);
請注意,此資料模型有三個 關係
- 1-1:
User↔Profile - 1-n:
User↔Post(透過_PostToUser關係表維護) - m-n:
Post↔Category(透過_CategoryToPost關係表維護)
現在你可以使用以下命令對你的資料庫執行 Prisma ORM 的內省
npx prisma db pull
這是呼叫 db pull 時發生情況的圖形化說明

對於上述 Prisma 1 資料模型,這將生成以下 Prisma ORM 2 schema(請注意,模型已重新排序以匹配 Prisma 1 資料模型的初始順序)
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上的createdAt和updatedAt欄位沒有自動生成的日期值User上的role欄位沒有預設值Post上的published欄位沒有預設值
此外還存在一些不一致之處,導致 Prisma Client API 不那麼符合慣用/人體工程學
User↔Profile是 1-n 關係而不是 1-1 關係User↔Post是 m-n 關係而不是 1-n 關係- 關係欄位採用大寫(例如
User上的Profile和Post) User上的jsonData欄位是String型別而不是Json型別User上的role欄位是String型別而不是Role,role的enum定義完全缺失
儘管這些不一致實際上不會影響你在 Prisma Client API 中可用的“功能集”,但它們會讓你失去之前存在的某些約束/保證。
例如,Prisma ORM 現在無法保證一個 User 最多連線到一個 Profile,因為表之間的關係在內省期間被識別為 1-n,所以一個 User 記錄現在可能連線到多個 Profile 記錄。
另一個問題是,你可以在 jsonData 和 role 欄位中儲存任何文字,無論它是否為有效的 JSON 或代表 Role 列舉的值。
要了解有關這些不一致的更多資訊,請查閱 Schema 不相容性 頁面。
接下來,我們將使用 Prisma schema 升級 CLI 逐一解決這些不相容性。
5. 使用 Prisma schema 升級 CLI 解決 schema 不相容性
Prisma 1 升級 CLI 是一個互動式工具,可幫助你升級 Prisma schema 並解決上述大部分不一致之處。
Prisma 1 升級 CLI 分兩個主要階段工作
- 透過純 SQL 修復資料庫 schema
- 向 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 資料模型

要使用升級 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 語句被歸類為多個“類別”,所有這些都旨在解決某個 schema 不相容性
- 修復 ENUM 資料型別的列
- 向資料庫新增缺失的
DEFAULT約束 - 修復 JSON 資料型別的列
- 在 Prisma 2 中複製
@createdAt行為 - 透過新增
UNIQUE約束脩復 1-1 關係
作為下一步,你可以開始將 SQL 語句傳送到你的資料庫。請注意,所有這些更改都是非破壞性的,你將能夠繼續與 Prisma ORM 2 同時使用 Prisma 1。
接下來的章節將分別介紹要傳送到資料庫的不同型別的 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;
現在,繼續針對你的資料庫執行這些語句。

5.1.2. 向資料庫新增缺失的 DEFAULT 約束
接下來,升級 CLI 透過生成 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;
你現在可以使用命令列客戶端或像 TablePlus 這樣的 GUI 對你的資料庫執行這些 SQL 語句

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 ;
你現在可以使用命令列客戶端或像 TablePlus 這樣的 GUI 對你的資料庫執行這些 SQL 語句

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;
你現在可以使用命令列客戶端或像 TablePlus 這樣的 GUI 對你的資料庫執行這些 SQL 語句。
5.1.5. 透過新增 UNIQUE 約束脩復 1-1 關係
現在,該工具將透過在資料庫中為名為 user 的外部索引鍵列(以 Prisma 1 資料模型中的關係欄位命名)新增 UNIQUE 約束,幫助你將 User ↔ Profile 之間的當前 1-n 關係 轉回 1-1 關係。
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`);
你現在可以使用命令列客戶端或像 TablePlus 這樣的 GUI 對你的資料庫執行這些 SQL 語句。
5.1.6. 修復 CUID 長度不匹配問題
注意:這些 SQL 語句即使在你更改了底層資料庫中的列型別後,仍會繼續出現在升級 CLI 中。這是升級 CLI 當前的一個限制。
最後,該工具將透過在資料庫中為名為 user 的外部索引鍵列(以 Prisma 1 資料模型中的關係欄位命名)新增 UNIQUE 約束,幫助你將當前型別為 VARCHAR(25) 的 ID 列 轉換為 VARCHAR(30)。
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;
你現在可以使用命令列客戶端或像 TablePlus 這樣的 GUI 對你的資料庫執行這些 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 關係,這些關係在你的新 Prisma ORM 2 schema 中 當前僅作為 m-n 關係存在。具體來說,User ↔ Post 關係就是這種情況,它目前被定義為 m-n 關係,但實際上應該是一個 1-n 關係。
要解決此問題,你需要執行以下遷移
- 在
Post上建立一個新的外部索引鍵列,直接連結到User表。 - 將關係表中的外部索引鍵值遷移到
Post上的新外部索引鍵列中。 - 刪除關係表。
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 語句
- 在
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`); - 編寫一個 SQL 查詢,讀取
_PostToUser關係表中的所有行,並針對每一行- 透過查詢列
A中的值找到相應的Post記錄 - 將列
B中的值作為authorId的值插入到該Post記錄中
UPDATE `Post`, `_PostToUser` SET `Post`.`authorId` = `_PostToUser`.B where `_PostToUser`.A = `Post`.`id`; - 透過查詢列
- 刪除
_PostToUser關係表DROP TABLE `_PostToUser`;

執行這些命令後,關係表中列 B 的記錄的使用者 ID 值將遷移到新的 authorId 列。
5.2. 重新內省你的資料庫以更新你的 Prisma schema
至此,你已使用升級 CLI 解決了 schema 不相容性。現在,你可以透過鍵入 n 並按下 RETURN 來暫時退出升級 CLI。
在本節中,你將透過另一次內省來更新你的 Prisma schema。這一次,Prisma schema 之前的缺陷將得到解決,因為資料庫 schema 已經調整
npx prisma db pull
這次,生成的 Prisma schema 如下所示
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 屬性。通常這些屬性是以下內容
- 你的
@id欄位的@default(cuid()) - Prisma 1 中使用此屬性的任何欄位的
@updatedAt @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 的最終版本應如下所示
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 的一件事是所有 關係欄位 都以其各自的模型命名,例如
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])
}
這並不理想,你實際上可以手動將它們全部重新命名為以前的版本!
因為所有關係欄位都是虛擬的,這意味著它們不會在資料庫中顯現,所以你可以隨意命名它們。在這種情況下,所有關係欄位都小寫,有時是複數形式。
重新命名後它們是這樣的
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])
}
注意:對於
User和Profile之間的 1-1 關係,無法將舊名稱user設定為關係欄位。這是因為會與已存在的持有外部索引鍵的 關係標量 欄位發生命名衝突。在這種情況下,你可以選擇一個不同的名稱,或者透過 SQL 直接在資料庫中重新命名外部索引鍵列。
5.5. 解決剩餘的 schema 不相容性
還有一些 schema 不相容性尚未由升級 CLI 解決。此時,你仍未修復 標量列表。你可以在 Schema 不相容性 頁面上找到針對此問題及其他問題的推薦解決方案。
6. 安裝並生成 Prisma Client
現在你的 Prisma ORM 2 schema 已準備就緒,你可以使用以下命令安裝 Prisma Client
npm install @prisma/client
7. 下一步
恭喜你,你已成功將 Prisma ORM 層升級到 Prisma ORM 2!接下來,你可以使用以下指南之一更新你的應用程式程式碼
- 從舊版到新版 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 文件。
讀取單個記錄
const user = await prisma.user({ id: 1 })
await prisma.user.findUnique({
where: { id: 1 },
})
讀取記錄列表
const user = await prisma.users()
await prisma.user.findMany()
過濾列表
const users = await prisma.users({
where: {
name: 'Alice',
},
})
await prisma.user.findMany({
where: {
name: 'Alice',
},
})
分頁列表
const posts = await prisma.posts({
skip: 5,
first: 10,
})
await prisma.user.findMany({
skip: 5,
take: 10,
})
排序列表
await prisma.posts({
orderBy: 'title_ASC',
})
await prisma.posts({
orderBy: {
title: 'asc',
},
})
建立記錄
await prisma.createUser({
name: 'Alice',
})
await prisma.user.create({
data: {
name: 'Alice',
},
})
更新記錄
await prisma.updateUser({
where: { id: 1 },
data: {
name: 'James',
email: 'james@prisma.io',
},
})
await prisma.user.update({
where: { id: 1 },
data: {
name: 'James',
email: 'james@prisma.io',
},
})
刪除記錄
await prisma.deleteUser({ id: 1 })
await prisma.user.delete({
where: { id: 1 },
})
選擇欄位與載入關係
在 Prisma 1 中,選擇特定欄位和/或載入物件關係的唯一方法是使用基於字串的 $fragment 和 $graphql 函式。在 Prisma ORM 2 中,現在可以使用 select 和 include 以簡潔且型別安全的方式完成此操作。
這種方法的另一個好處是,你可以在任何 Prisma Client 查詢中使用 select 和 include,例如 findUnique、findMany、create、update、delete 等。
await prisma.user({ id: 1 }).$fragment(`
fragment NameAndEmail on User { id email }`
`)
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,
},
})