跳至主要內容

為資料庫設定基線

基線化是指為滿足以下條件的資料庫初始化遷移歷史記錄的過程:

  • ✔ 在您開始使用 Prisma Migrate 之前就已經存在
  • ✔ 包含必須維護的資料(如生產環境),這意味著資料庫不能重置

基線化告訴 Prisma Migrate 假定一個或多個遷移**已經應用**。這可以防止在生成的遷移嘗試建立已存在的表和欄位時失敗。

**注意**:我們假定重置和填充開發資料庫是可以接受的。

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

警告

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

為什麼需要設定基線

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

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. 應用基線遷移**之後**的任何新遷移
© . This site is unofficial and not affiliated with Prisma Data, Inc.