跳到主要内容

建立数据库基线

建立基线是为符合以下条件的数据库初始化迁移历史记录的过程:

  • ✔ 在你开始使用 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. 应用基线迁移之后的任何新迁移