跳至主要内容

为数据库设置基线

基线化是指为满足以下条件的数据库初始化迁移历史记录的过程:

  • ✔ 在您开始使用 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. 应用基线迁移**之后**的任何新迁移
© . All rights reserved.