在 Ent 模式中使用 Postgres 枚举类型
枚举类型是由预定义有序值组成的数据结构。
默认情况下,当在 Ent 模式中使用 field.Enum 时,Ent 会采用简单的字符串类型表示 PostgreSQL 和 SQLite 中的枚举值。
但在某些情况下,你可能需要使用数据库提供的原生枚举类型。
本指南说明如何使用原生 PostgreSQL 枚举类型定义模式字段,并配置模式迁移,以便使用 Atlas 将 Postgres 枚举和 Ent 模式作为单一迁移单元进行管理。
Atlas 只为专业用户提供 复合类型支持,使用这些功能需运行:
atlas login
安装 Atlas
要安装Atlas的最新版本,只需在终端中运行以下任一命令,或访问Atlas 官方网站:
- 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
如果容器需要访问主机网络或本地目录,请使用 --net=host 标志挂载所需目录:
docker run --rm --net=host \
-v $(pwd)/migrations:/migrations \
arigaio/atlas migrate apply
--url "mysql://root:pass@:3306/test"
下载 最新版本 并将 atlas 二进制执行文件所在目录加入到系统路径中。
登录 Atlas
$ atlas login a8m
You are now connected to "a8m" on Atlas Cloud.
复合模式
ent/schema 包主要用来定义 Ent 类型(对象),包括字段、边和逻辑等。
外部枚举类型或其他数据库对象在 Ent 模式中不体现,Postgres 枚举类型定义一次,并在不同的字段和模式中可以使用多次。
为扩展 PostgreSQL 模式以包含自定义枚举类型和 Ent 类型,可以配置 Atlas 来读取 复合模式 数据源的模式状态。 跟着以下步骤来配置你的项目:
1. 创建 schema.sql 来定义必要的枚举类型。同样你可以用 Atlas 模式 HCL 语言 来配置复合类型:
- Using SQL
- Using HCL
CREATE TYPE status AS ENUM ('active', 'inactive', 'pending');
schema "public" {}
enum "status" {
schema = schema.public
values = ["active", "inactive", "pending"]
}
2. 在 Ent 模式中,使用以下 Postgres ENUM 类型定义枚举字段:
// Fields of the User.
func (User) Fields() []ent.Field {
return []ent.Field{
field.Enum("status").
Values("active", "inactive", "pending").
SchemaType(map[string]string{
dialect.Postgres: "status",
}),
}
}
有时模式使用某些数据库自定义驱动特定类型时,Ent 返回驱动使用的默认类型(例如 SQLite 中的 TEXT 和 MariaDB 或 MariaDB 中的 ENUM (...) )。
3. 使用包含在 schema.sql 中自定义枚举类型和 Ent 模式的 composite_schema 来创建 atlas.hcl 配置文件:
data "composite_schema" "app" {
# Load first custom types first.
schema "public" {
url = "file://schema.sql"
}
# Second, load the Ent schema.
schema "public" {
url = "ent://ent/schema"
}
}
env "local" {
src = data.composite_schema.app.url
dev = "docker://postgres/15/dev?search_path=public"
}
使用
设置完模式后,我们可以使用 atlas schema inspect 命令来查看其表示、生成迁移或将它们应用到数据库等。以下是几个帮助你开始使用 Atlas 的几个命令:
检查模式
atlas schema inspect 命令通常用来检查数据库。然而我们也可以用它来检查 composite_schema 并打印其 SQL 表示形式:
atlas schema inspect \
--env local \
--url env://src \
--format '{{ sql . }}'
以上命令打印下述 SQL。需要注意 status 枚举类型在 users.status 列中使用之前需要在模式中定义。
The command above prints the following SQL. Note, the status enum type is defined in the schema before
its usage in the users.status column:
-- Create enum type "status"
CREATE TYPE "status" AS ENUM ('active', 'inactive', 'pending');
-- Create "users" table
CREATE TABLE "users" ("id" bigint NOT NULL GENERATED BY DEFAULT AS IDENTITY, "status" "status" NOT NULL, PRIMARY KEY ("id"));
为模式生成迁移
运行以下命令为模式生成迁移:
atlas migrate diff \
--env local
注意可生成以下内容的新的迁移文件:
-- Create enum type "status"
CREATE TYPE "status" AS ENUM ('active', 'inactive', 'pending');
-- Create "users" table
CREATE TABLE "users" ("id" bigint NOT NULL GENERATED BY DEFAULT AS IDENTITY, "status" "status" NOT NULL, PRIMARY KEY ("id"));
应用迁移
运行以下命令将生成的迁移应用到数据库:
atlas migrate apply \
--env local \
--url "postgres://postgres:pass@localhost:5432/database?search_path=public&sslmode=disable"
有时需要在不生成迁移文件的时候将模式直接应用于数据库。例如,尝试模式变更、创建测试数据库等。这种情况下,可以使用下面的命令将模式直接应用于数据库:
atlas schema apply \
--env local \
--url "postgres://postgres:pass@localhost:5432/database?search_path=public&sslmode=disable"
或使用 Atlas Go SDK:
ac, err := atlasexec.NewClient(".", "atlas")
if err != nil {
log.Fatalf("failed to initialize client: %w", err)
}
// Automatically update the database with the desired schema.
// Another option, is to use 'migrate apply' or 'schema apply' manually.
if _, err := ac.SchemaApply(ctx, &atlasexec.SchemaApplyParams{
Env: "local",
URL: "postgres://postgres:pass@localhost:5432/database?search_path=public&sslmode=disable",
AutoApprove: true,
}); err != nil {
log.Fatalf("failed to apply schema changes: %w", err)
}
本指南的代码参见 GitHub。