多模式迁移
使用 Atlas 迁移引擎,Ent 模式可以在多个数据库模式中定义和管理。本指南展示了如何用三步实现此功能:
多模式迁移功能已在 Atlas CLI 完全实现,并且需要登录后才能使用:
atlas login
安装 Atlas
To install the latest release of Atlas, simply run one of the following commands in your terminal, or check out the Atlas website:
- macOS + Linux
- Homebrew
- Docker
- Windows
curl -sSf https://atlasgo.sh | sh
brew install ariga/tap/atlas
docker pull arigaio/atlas
docker run --rm arigaio/atlas --help
If the container needs access to the host network or a local directory, use the --net=host flag and mount the desired
directory:
docker run --rm --net=host \
-v $(pwd)/migrations:/migrations \
arigaio/atlas migrate apply
--url "mysql://root:pass@:3306/test"
Download the latest release and move the atlas binary to a file location on your system PATH.
登录 Atlas
$ atlas login a8m
You are now connected to "a8m" on Atlas Cloud.
注解你的 Ent 模式
entsql 包允许使用数据库模式名称注解 Ent 模式。例如:
// User 的注解
func (User) Annotations() []schema.Annotation {
return []schema.Annotation{
entsql.Schema("db3"),
}
}
要在多个 Ent 模式中共享相同的模式配置,可以使用 ent.Mixin 或定义并嵌入 base 模式:
- Mixin schema
- Base schema
// Mixin 持有此包中大多数模式的默认配置
type Mixin struct {
mixin.Schema
}
// Mixin 的注解
func (Mixin) Annotations() []schema.Annotation {
return []schema.Annotation{
entsql.Schema("db1"),
}
}
// User 持有 User 实体的边缘模式定义
type User struct {
ent.Schema
}
// Mixin 定义混入此模式的模式
func (User) Mixin() []ent.Mixin {
return []ent.Mixin{
Mixin{},
}
}
// base 持有此包中大多数模式的默认配置
type base struct {
ent.Schema
}
// base 模式的注解
func (base) Annotations() []schema.Annotation {
return []schema.Annotation{
entsql.Schema("db1"),
}
}
// User 持有 User 实体的边缘模式定义
type User struct {
base
}
生成迁移
要生成迁移,请使用 atlas migrate diff 命令。例如:
- MySQL
- MariaDB
- PostgreSQL
atlas migrate diff \
--to "ent://ent/schema" \
--dev-url "docker://mysql/8"
atlas migrate diff \
--to "ent://ent/schema" \
--dev-url "docker://maria/8"
atlas migrate diff \
--to "ent://ent/schema" \
--dev-url "docker://postgres/15/dev"
migrate diff 命令默认生成不带缩进的 SQL 语句列表。如果你希望生成带缩进的 SQL 语句,请使用 --format 标志。例如:
atlas migrate diff \
--to "ent://ent/schema" \
--dev-url "docker://postgres/15/dev" \
--format "{{ sql . \" \" }}"
控制 Ent 客户端
当 sql/schemaconfig 功能标志启用时,Ent 会自动使用你在 ent/schema 中定义的模式名称作为默认运行时配置。这意味着任何 entsql.Schema(\"db_name\") 注解默认会被应用,你可以在需要时在运行时选择性地覆盖它。
要为你的项目启用该功能,请使用 --feature 标志:
--feature sql/schemaconfig
启用后,你还可以使用 ent.AlternateSchema 选项在运行时覆盖模式配置:
c, err := ent.Open(dialect, conn, ent.AlternateSchema(ent.SchemaConfig{
User: "usersdb",
Car: "carsdb",
}))
c.User.Query().All(ctx) // SELECT * FROM `usersdb`.`users`
c.Car.Query().All(ctx) // SELECT * FROM `carsdb`.`cars`