← 中文资源

简体中文版本

数据库迁移创建工作流

创建新的数据库迁移文件包含 up 和 down 脚本,本地测试并验证回滚。

阅读英文原文

概述

数据库迁移创建工作流是一个初级难度的工作流。创建新的数据库迁移文件包含 up 和 down 脚本,本地测试并验证回滚。该工作流的目标是:Create and test a reversible database migration before applying it to staging or production.

环境准备

执行本工作流需要以下环境:A project with a migration tool;A local database for testing;Migration tool CLI available。请确保在开始前准备好所有必需的工具和资源,以避免中途因环境问题中断。

执行步骤

本工作流包含4个步骤。步骤1:Generate migration——Use the migration tool to create a new migration file with a descriptive name. 步骤2:Apply migration——Run the migration tool to apply the new migration to the local database. 步骤3:Test rollback——Run the rollback command to revert the migration and confirm the database returns to the previous state. 步骤4:Re-apply——Apply the migration again to confirm it is idempotent.

验证与清理

预期结果:A tested migration that can be safely applied and rolled back in production.。验证方法:Apply the migration, rollback, and re-apply; confirm the database state is correct at each step.。清理操作:Roll back the migration if you do not want it applied locally.。estimatedMinutes 为 25 分钟。

代码示例

npx prisma migrate dev --name add_users
npx prisma migrate rollback