跳到主要内容

在 Ent 模式中使用功能索引

功能索引是键部分基于表达式值而非列值的索引。这种索引类型对于不存储在表中的函数或表达式结果的索引比较有用。 MySQL、MariaDBPostgreSQLSQLite 都支持。

本指南说明如何在 Ent 模式中扩展功能索引,并配置模式迁移,以便使用 Atlas 将功能索引和 Ent 模式作为单一迁移单元进行管理。

Atlas 只为专业用户提供 复合模式支持,使用这些功能需运行:

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/schema 包主要用来定义 Ent 类型(对象),包括字段、边和逻辑等。 功能索引在 Ent 模式中没有相应的表达,Ent 通过在字段、边(外键)并将他们结合起来以支持功能索引的定义。

为扩展 PostgreSQL 模式以包含功能索引到 Ent 类型(表),可以配置 Atlas 来读取 复合模式 数据源的模式状态。 跟着以下步骤来配置你的项目:

1. 定义一个简单的模式,具有类型(表):User (表 User):

ent/schema/user.go
// User holds the schema definition for the User entity.
type User struct {
ent.Schema
}

// Fields of the User.
func (User) Fields() []ent.Field {
return []ent.Field{
field.String("name").
Comment("A unique index is defined on lower(name) in schema.sql"),
}
}

2. 下一步在 schema.sql 文件的 name 字段上定义功能索引:

schema.sql
-- Create a functional (unique) index on the lowercased name column.
CREATE UNIQUE INDEX unique_name ON "users" ((lower("name")));

3. 创建一个具有简单的 atlas.hcl 配置文件,配置文件具有包含在 schema.sql 和 Ent 模式中定义功能索引的 composite_schema

atlas.hcl
data "composite_schema" "app" {
# Load the ent schema first with all tables.
schema "public" {
url = "ent://ent/schema"
}
# Then, load the functional indexes.
schema "public" {
url = "file://schema.sql"
}
}

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。

-- Create "users" table
CREATE TABLE "users" ("id" bigint NOT NULL GENERATED BY DEFAULT AS IDENTITY, "name" character varying NOT NULL, PRIMARY KEY ("id"));
-- Create index "unique_name" to table: "users"
CREATE UNIQUE INDEX "unique_name" ON "users" ((lower((name)::text)));

注意我们的功能索引定义在 users 表的 name 字段。

为模式生成迁移

运行以下命令为模式生成迁移:

atlas migrate diff \
--env local

注意可生成以下内容的新的迁移文件:

migrations/20240712090543.sql
-- Create "users" table
CREATE TABLE "users" ("id" bigint NOT NULL GENERATED BY DEFAULT AS IDENTITY, "name" character varying NOT NULL, PRIMARY KEY ("id"));
-- Create index "unique_name" to table: "users"
CREATE UNIQUE INDEX "unique_name" ON "users" ((lower((name)::text)));

应用迁移

运行以下命令将生成的迁移应用到数据库:

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?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?sslmode=disable",
AutoApprove: true,
}); err != nil {
log.Fatalf("failed to apply schema changes: %w", err)
}

代码示例

在设置 Ent 模式中的功能索引后,我们期望数据库在 users 表中使 name 字段唯一:

// Test that the unique index is enforced.
client.User.Create().SetName("Ariel").SaveX(ctx)
err = client.User.Create().SetName("ariel").Exec(ctx)
require.EqualError(t, err, `ent: constraint failed: pq: duplicate key value violates unique constraint "unique_name"`)

// Type-assert returned error.
var pqerr *pq.Error
require.True(t, errors.As(err, &pqerr))
require.Equal(t, `duplicate key value violates unique constraint "unique_name"`, pqerr.Message)
require.Equal(t, user.Table, pqerr.Table)
require.Equal(t, "unique_name", pqerr.Constraint)
require.Equal(t, pq.ErrorCode("23505"), pqerr.Code, "unique violation")

本指南的代码参见 GitHub