使用 Prisma ORM、TypeScript 和 CockroachDB 建立基线
创建初始迁移
¥Create an initial migration
要将 Prisma Migrate 与你在上一节中反思的数据库一起使用,你将需要 数据库的基线。
¥To use Prisma Migrate with the database you introspected in the last section, you will need to baseline your database.
基线是指初始化可能已包含数据且无法重置的数据库(例如生产数据库)的迁移历史记录。基线告诉 Prisma Migrate 假设一项或多项迁移已应用到你的数据库。
¥Baselining refers to initializing your migration history for a database that might already contain data and cannot be reset, such as your production database. Baselining tells Prisma Migrate to assume that one or more migrations have already been applied to your database.
要为数据库建立基线,请使用 prisma migrate diff
比较你的架构和数据库,并将输出保存到 SQL 文件中。
¥To baseline your database, use prisma migrate diff
to compare your schema and database, and save the output into a SQL file.
首先,创建一个 migrations
目录,并在其中添加一个目录,其中包含你用于迁移的首选名称。在此示例中,我们将使用 0_init
作为迁移名称:
¥First, create a migrations
directory and add a directory inside with your preferred name for the migration. In this example, we will use 0_init
as the migration name:
mkdir -p prisma/migrations/0_init
-p
将在你提供的路径中递归创建任何丢失的文件夹。
¥-p
will recursively create any missing folders in the path you provide.
接下来,使用 prisma migrate diff
生成迁移文件。使用以下参数:
¥Next, generate the migration file with prisma migrate diff
. Use the following arguments:
-
--from-empty
:假设你要迁移的数据模型为空¥
--from-empty
: assumes the data model you're migrating from is empty -
--to-schema-datamodel
:使用datasource
块中的 URL 获取当前数据库状态¥
--to-schema-datamodel
: the current database state using the URL in thedatasource
block -
--script
:输出 SQL 脚本¥
--script
: output a SQL script
npx prisma migrate diff --from-empty --to-schema-datamodel prisma/schema.prisma --script > prisma/migrations/0_init/migration.sql
检查迁移
¥Review the migration
该命令将生成类似于以下脚本的迁移:
¥The command will generate a migration that should resemble the following script:
CREATE TABLE "User" (
id INT8 PRIMARY KEY DEFAULT unique_rowid(),
name STRING(255),
email STRING(255) UNIQUE NOT NULL
);
CREATE TABLE "Post" (
id INT8 PRIMARY KEY DEFAULT unique_rowid(),
title STRING(255) UNIQUE NOT NULL,
"createdAt" TIMESTAMP NOT NULL DEFAULT now(),
content STRING,
published BOOLEAN NOT NULL DEFAULT false,
"authorId" INT8 NOT NULL,
FOREIGN KEY ("authorId") REFERENCES "User"(id)
);
CREATE TABLE "Profile" (
id INT8 PRIMARY KEY DEFAULT unique_rowid(),
bio STRING,
"userId" INT8 UNIQUE NOT NULL,
FOREIGN KEY ("userId") REFERENCES "User"(id)
);