规划迁移
支持的代码仓库
本部门描述的修改可以在支持的代码仓库中的 PR #6 找到。
规划迁移
在本部分我们讨论如何在修改项目 Ent 模式时规划新的模式迁移。
假设我们想向 User 实体添加一个新的名为 title 的可选字段:
// Fields of the User.
func (User) Fields() []ent.Field {
return []ent.Field{
field.String("name"),
field.String("email"). // <-- Our new field
Unique(),
field.String("title").
Optional(),
}
}
添加完新的字段后,我们需要为项目重新运行代码生成:
go generate ./...
下一步我们需要使用 Atlas CLI 来为这一变更创建新的迁移文件:
- MySQL
- MariaDB
- PostgreSQL
- SQLite
atlas migrate diff add_user_title \
--dir "file://ent/migrate/migrations" \
--to "ent://ent/schema" \
--dev-url "docker://mysql/8/ent"
atlas migrate diff add_user_title \
--dir "file://ent/migrate/migrations" \
--to "ent://ent/schema" \
--dev-url "docker://mariadb/latest/test"
atlas migrate diff add_user_title \
--dir "file://ent/migrate/migrations" \
--to "ent://ent/schema" \
--dev-url "docker://postgres/15/test?search_path=public"
atlas migrate diff add_user_title \
--dir "file://ent/migrate/migrations" \
--to "ent://ent/schema" \
--dev-url "sqlite://file?mode=memory&_fk=1"
可以看到一个新的名为 20221115101649_add_user_title.sql 在 ent/migrate/migrations/ 目录下被创建了。
此文件包含在 users 表中创建最新添加的 title 字段的 SQL 语句:
-- modify "users" table
ALTER TABLE `users` ADD COLUMN `title` varchar(255) NULL;
很好!我们成功使用 Atlas CLI 来为我们的变更自动生成了新的迁移文件。
若要应用这个迁移,可以运行如下命令:
atlas migrate apply --dir file://ent/migrate/migrations --url mysql://root:pass@localhost:3306/db
Atlas 报告:
Migrating to version 20221115101649 from 20221114165732 (1 migrations in total):
-- migrating version 20221115101649
-> ALTER TABLE `users` ADD COLUMN `title` varchar(255) NULL;
-- ok (36.152277ms)
-------------------------
-- 44.1116ms
-- 1 migrations
-- 1 sql statements
在下一部分我们将会讨论如何为项目规划自定义模式迁移。