跳至主要内容

为数据库设置基线

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

  • ✔ 在您开始使用 Prisma Migrate 之前就已存在
  • ✔ 包含必须维护的数据(如生产环境),这意味着数据库不能重置

基线化(Baselining)告诉 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.