跳到主要內容

資料庫基準化

基準化是為資料庫初始化遷移歷史記錄的過程,該資料庫

  • ✔ 在您開始使用 Prisma Migrate 之前就已存在
  • ✔ 包含必須維護的資料(例如生產環境),這表示資料庫無法重置

基準化會告知 Prisma Migrate 假設一個或多個遷移已經套用。這可防止產生的遷移在嘗試建立已存在的資料表和欄位時失敗。

注意:我們假設重置和植入種子開發資料庫是可以接受的。

基準化是將 Prisma Migrate 新增至具有現有資料庫的專案的一部分。

警告

本指南不適用於 MongoDB
對於 MongoDB,使用 db push 而非 migrate deploy

為什麼您需要基準化

當您將 Prisma Migrate 新增至現有專案時,您的初始遷移包含重建資料庫狀態所需的所有 SQL,在您開始使用 Prisma Migrate 之前

The image shows a database labelled 'Existing database', and a list of existing database features next to it - 24 tables, 13 relationships, 92 fields, 3 indexes. An arrow labelled 'represented by' connects the database features list to a box that represents a migration. The existing databases's features are represented by a single migration.

提示

您可以編輯初始遷移,以包含 Prisma Schema 中無法表示的 Schema 元素 - 例如預存程序或觸發器。

您需要此初始遷移來建立和重置開發環境

The image shows a migration history with three migrations. Each migration is represented by a file icon and a name, and all migrations are surrounded by a box labelled 'migration history'. The first migration has an additional label: "State of database before Prisma Migrate", and the two remaining migrations are labelled "Generated as part of the Prisma Migrate workflow". An arrow labelled "prisma migrate dev" connects the migration history box to a database labelled "new development database", signifying that all three migrations are applied to the development database - none are skipped.

但是,當您將遷移 prisma migrate deploy 到已經存在且無法重置的資料庫(例如生產環境)時,您不希望包含初始遷移

目標資料庫已經包含初始遷移所建立的資料表和資料行,並且嘗試再次建立這些元素很可能會導致錯誤。

A migration history represented by three migration files (file icon and name), surrounded by a a box labelled 'migration history'. The first migration is marked 'do not apply', and the second two migrations are marked 'apply'. An arrow labelled with the command 'prisma migrate deploy' points from the migration history to a database labelled 'production'.

基準化透過告知 Prisma Migrate 假裝初始遷移已經套用來解決此問題。

基準化資料庫

若要建立基準遷移

  1. 如果您有 prisma/migrations 資料夾,請刪除、移動、重新命名或封存此資料夾。

  2. 執行以下命令以在其中建立一個名為 migrations 的目錄,並使用您偏好的名稱。此範例將使用 0_init 作為遷移名稱

    mkdir -p prisma/migrations/0_init
    資訊

    然後 0_ 很重要,因為 Prisma Migrate 以字典順序套用遷移。您可以使用不同的值,例如目前的時間戳記。

  3. 產生遷移並使用 prisma migrate diff 將其儲存到檔案

    npx prisma migrate diff \
    --from-empty \
    --to-schema-datamodel prisma/schema.prisma \
    --script > prisma/migrations/0_init/migration.sql
  4. 針對每個應忽略的遷移執行 prisma migrate resolve 命令

    npx prisma migrate resolve --applied 0_init

此命令會將目標遷移新增至 _prisma_migrations 資料表,並將其標記為已套用。當您執行 prisma migrate deploy 以套用新的遷移時,Prisma Migrate 會

  1. 略過所有標記為「已套用」的遷移,包括基準遷移
  2. 套用基準遷移之後出現的任何新遷移