开始使用 Prisma Migrate
本页介绍如何开始使用 Prisma Migrate 在开发环境中迁移架构。
¥This page explains how to get started with migrating your schema in a development environment using Prisma Migrate.
从头开始使用 Prisma Migrate
¥Get started with Prisma Migrate from scratch
要在开发环境中开始使用 Prisma Migrate:
¥To get started with Prisma Migrate in a development environment:
-
创建 Prisma 架构:
¥Create a Prisma schema:
schema.prismadatasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model User {
id Int @id @default(autoincrement())
name String
posts Post[]
}
model Post {
id Int @id @default(autoincrement())
title String
published Boolean @default(true)
authorId Int
author User @relation(fields: [authorId], references: [id])
}提示你可以在架构中使用 原生类型映射属性 来决定要创建哪种确切的数据库类型(例如,
String
可以映射到varchar(100)
或text
)。¥You can use native type mapping attributes in your schema to decide which exact database type to create (for example,
String
can map tovarchar(100)
ortext
).-
创建第一个迁移:
¥Create the first migration:
prisma migrate dev --name init
Show CLI results你的 Prisma 架构现已与数据库架构同步,并且你已初始化迁移历史记录:
¥Your Prisma schema is now in sync with your database schema and you have initialized a migration history:
migrations/
└─ 20210313140442_init/
└─ migration.sql -
-
将其他字段添加到你的架构中:
¥Add additional fields to your schema:
model User {
id Int @id @default(autoincrement())
jobTitle String
name String
posts Post[]
} -
创建第二个迁移:
¥Create the second migration:
prisma migrate dev --name added_job_title
Show CLI results你的 Prisma 架构再次与数据库架构同步,并且你的迁移历史记录包含两次迁移:
¥Your Prisma schema is once again in sync with your database schema, and your migration history contains two migrations:
migrations/
└─ 20210313140442_init/
└─ migration.sql
└─ 20210313140442_added_job_title/
└─ migration.sql
你现在拥有了可以 源代码控制 并用于 将更改部署到测试环境和生产 的迁移历史记录。
¥You now have a migration history that you can source control and use to deploy changes to test environments and production.
将 Prisma Migrate 添加到现有项目
¥Adding Prisma Migrate to an existing project
将 Prisma Migrate 添加到现有项目所涉及的步骤是:
¥The steps involved in adding Prisma Migrate to your existing project are:
-
检查你的数据库以更新你的 Prisma 架构
¥Introspect your database to update your Prisma schema
-
创建基线迁移
¥Create a baseline migration
-
更新你的架构或迁移到 Prisma 架构语言不支持的解决方法功能
¥Update your schema or migration to workaround features not supported by Prisma Schema Language
-
应用基线迁移
¥Apply the baseline migration
-
提交迁移历史记录和 Prisma 架构
¥Commit the migration history and Prisma schema
Introspect 以创建或更新你的 Prisma 架构
¥Introspect to create or update your Prisma schema
确保你的 Prisma 架构与数据库架构同步。如果你使用的是以前版本的 Prisma Migrate,这应该已经是正确的。
¥Make sure your Prisma schema is in sync with your database schema. This should already be true if you are using a previous version of Prisma Migrate.
-
检查数据库以确保你的 Prisma 架构是最新的:
¥Introspect the database to make sure that your Prisma schema is up-to-date:
prisma db pull
创建基线迁移
¥Create a baseline migration
基线化是初始化数据库迁移历史记录的过程:
¥Baselining is the process of initializing a migration history for a database that:
-
在你开始使用 Prisma Migrate 之前就已存在
¥Existed before you started using Prisma Migrate
-
包含必须维护的数据(如生产),这意味着数据库无法重置
¥Contains data that must be maintained (like production), which means that the database cannot be reset
基线告诉 Prisma Migrate 假设已应用一项或多项迁移。这可以防止生成的迁移在尝试创建已存在的表和字段时失败。
¥Baselining tells Prisma Migrate to assume that one or more migrations have already been applied. This prevents generated migrations from failing when they try to create tables and fields that already exist.
要创建基线迁移:
¥To create a baseline migration:
-
如果你有
prisma/migrations
文件夹,请删除、移动、重命名或存档该文件夹。¥If you have a
prisma/migrations
folder, delete, move, rename, or archive this folder. -
运行以下命令以你喜欢的名称在其中创建
migrations
目录。此示例将使用0_init
作为迁移名称:¥Run the following command to create a
migrations
directory inside with your preferred name. This example will use0_init
for the migration name:mkdir -p prisma/migrations/0_init
note0_
is important because Prisma Migrate applies migrations in a lexicographic order. You can use a different value such as the current timestamp. ::::这 -
使用
prisma migrate diff
生成迁移并将其保存到文件中:¥Generate a migration and save it to a file using
prisma migrate diff
:npx prisma migrate diff \
--from-empty \
--to-schema-datamodel prisma/schema.prisma \
--script > prisma/migrations/0_init/migration.sql -
查看生成的迁移。
¥Review the generated migration.
解决 Prisma Schema Language 不支持的功能
¥Work around features not supported by Prisma Schema Language
要包含数据库中已存在的 不支持的数据库功能,你必须替换或修改初始迁移 SQL:
¥To include unsupported database features that already exist in the database, you must replace or modify the initial migration SQL:
-
打开 创建基线迁移 部分中生成的
migration.sql
文件。¥Open the
migration.sql
file generated in the Create a baseline migration section. -
修改生成的 SQL。例如:
¥Modify the generated SQL. For example:
-
如果更改很小,你可以将其他自定义 SQL 附加到生成的迁移中。以下示例创建部分索引:
¥If the changes are minor, you can append additional custom SQL to the generated migration. The following example creates a partial index:
/* Generated migration SQL */
CREATE UNIQUE INDEX tests_success_constraint ON posts (subject, target)
WHERE success; -
如果更改很大,可以更轻松地用数据库转储的结果(
mysqldump
,pg_dump
)替换整个迁移文件。当使用pg_dump
进行此操作时,你需要使用以下命令更新search_path
:SELECT pg_catalog.set_config('search_path', '', false);
;否则你将遇到以下错误:The underlying table for model '_prisma_migrations' does not exist.
:::info Note that the order of the tables matters when creating all of them at once, since foreign keys are created at the same step. Therefore, either re-order them or move constraint creation to the last step after all tables are created, so you won't face
can't create constraint` errors :::¥If the changes are significant, it can be easier to replace the entire migration file with the result of a database dump (
mysqldump
,pg_dump
). When usingpg_dump
for this, you'll need to update thesearch_path
as follows with this command:SELECT pg_catalog.set_config('search_path', '', false);
; otherwise you'll run into the following error:The underlying table for model '_prisma_migrations' does not exist.
:::info Note that the order of the tables matters when creating all of them at once, since foreign keys are created at the same step. Therefore, either re-order them or move constraint creation to the last step after all tables are created, so you won't face
can't create constraint` errors :::
应用初始迁移
¥Apply the initial migrations
要应用你的初始迁移:
¥To apply your initial migration(s):
-
针对你的数据库运行以下命令:
¥Run the following command against your database:
npx prisma migrate resolve --applied 0_init
-
检查数据库架构以确保迁移达到所需的最终状态(例如,通过将架构与生产数据库进行比较)。
¥Review the database schema to ensure the migration leads to the desired end-state (for example, by comparing the schema to the production database).
新的迁移历史记录和数据库架构现在应该与你的 Prisma 架构同步。
¥The new migration history and the database schema should now be in sync with your Prisma schema.
提交迁移历史记录和 Prisma 架构
¥Commit the migration history and Prisma schema
向源代码控制提交以下内容:
¥Commit the following to source control:
-
整个迁移历史文件夹
¥The entire migration history folder
-
schema.prisma
文件¥The
schema.prisma
file
更进一步
¥Going further
-
有关将迁移部署到生产的更多信息,请参阅 使用 Prisma Migrate 部署数据库更改 指南。
¥Refer to the Deploying database changes with Prisma Migrate guide for more on deploying migrations to production.
-
请参阅 生产故障排除 指南,了解如何使用
prisma migrate diff
、prisma db execute
和/或prisma migrate resolve
调试和解决生产中失败的迁移。¥Refer to the Production Troubleshooting guide to learn how to debug and resolve failed migrations in production using
prisma migrate diff
,prisma db execute
and/ orprisma migrate resolve
.