自定义迁移
支持的代码仓库
本部分描述的修改可以在支持的代码仓库的 PR #7 中找到。
自定义迁移
有时可能想编写自定义迁移而非使用 Atlas 自动生成的迁移。 这在你想要对数据进行目前 Ent 不支持的修改是很有用,或者你想要向数据库注入初始数据。
在本部分我们将会学习如何向项目添加自定义迁移。本教程的目的是假设我们想要向用户表注入一些初始数据。
创建自定义迁移
让我们先向项目添加一个新的迁移文件:
atlas migrate new seed_users --dir file://ent/migrate/migrations
可以看到在 ent/migrate/migrations 目录下一个新的名为 20221115102552_seed_users.sql 的文件被创建了。
继续打开这个文件并添加如下 SQL 语句:
INSERT INTO `users` (`name`, `email`, `title`)
VALUES ('Jerry Seinfeld', 'jerry@seinfeld.io', 'Mr.'),
('George Costanza', 'george@costanza.io', 'Mr.')
重新计算校验文件
让我们尝试运行新的自定义迁移:
atlas migrate apply --dir file://ent/migrate/migrations --url mysql://root:pass@localhost:3306/db
Atlas 运行失败并报错:
You have a checksum error in your migration directory.
This happens if you manually create or edit a migration file.
Please check your migration files and run
'atlas migrate hash'
to re-hash the contents and resolve the error
Error: checksum mismatch
Atlas 引入 迁移目录完整性 的概念来强制线性迁移历史。 通过这种方法如果多个开发者并行工作于同一项目时,他们可以确认合并的迁移历史是正确的。
让我们为迁移目录内容重新生成哈希值来解决这个错误:
atlas migrate hash --dir file://ent/migrate/migrations
如果我们再次运行 atlas migrate apply,我们将会看到迁移被成功应用了:
atlas migrate apply --dir file://ent/migrate/migrations --url mysql://root:pass@localhost:3306/db
Atlas 报告:
Migrating to version 20221115102552 from 20221115101649 (1 migrations in total):
-- migrating version 20221115102552
-> INSERT INTO `users` (`name`, `email`, `title`)
VALUES ('Jerry Seinfeld', 'jerry@seinfeld.io', 'Mr.'),
('George Costanza', 'george@costanza.io', 'Mr.')
-- ok (9.077102ms)
-------------------------
-- 19.857555ms
-- 1 migrations
-- 1 sql statements
在下一部分我们将学习如何确认使用 Atlas 静态检查(Linting) 功能来验证模式迁移的安全性。