跳到主要内容

多模式迁移

当使用 Atlas 迁移引擎时,可以在多个数据库模式之间定义和管理 Ent 模式。 本指南用三个简要步骤展示如何做到这一点:

多模式迁移 在 Atlas CLI中已完全实现,使用时要求登录:

atlas login

安装 Atlas

要安装Atlas的最新版本,只需在终端中运行以下任一命令,或访问Atlas 官方网站

curl -sSf https://atlasgo.sh | sh

登录 Atlas

$ atlas login a8m
You are now connected to "a8m" on Atlas Cloud.

对 Ent 模式进行注解

entsql 包允许使用数据库模式名称对 Ent 模式进行注解,例如:

// Annotations of the User.
func (User) Annotations() []schema.Annotation {
return []schema.Annotation{
entsql.Schema("db3"),
}
}

你可以使用 ent.Mixin 或定义一个嵌入的 基础 模式在多个 Ent 模式中共享相同的模式配置:

mixin.go
// Mixin holds the default configuration for most schemas in this package.
type Mixin struct {
mixin.Schema
}

// Annotations of the Mixin.
func (Mixin) Annotations() []schema.Annotation {
return []schema.Annotation{
entsql.Schema("db1"),
}
}
user.go
// User holds the edge schema definition of the User entity.
type User struct {
ent.Schema
}

// Mixin defines the schemas that mixed into this schema.
func (User) Mixin() []ent.Mixin {
return []ent.Mixin{
Mixin{},
}
}

生成前迁移

使用 atlas migrate diff 来生成迁移,例如:

atlas migrate diff \
--to "ent://ent/schema" \
--dev-url "docker://mysql/8"
备注

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`