跳转到主要内容

数据库基线

基线化是为一个数据库初始化迁移历史记录的过程,该数据库

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