Using Functional Indexes in Ent Schema

A functional index is an index whose key parts are based on expression values, rather than column values. This index type is helpful for indexing the results of functions or expressions that are not stored in the table. Supported by MySQL, MariaDB, PostgreSQL and SQLite.

This guide explains how to extend your Ent schema with functional indexes, and configure the schema migration to manage both functional indexes and the Ent schema as a single migration unit using Atlas.

Functional Indexes - 图1Atlas Pro Feature

  1. atlas login

Install 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
  1. curl -sSf https://atlasgo.sh | sh
  1. brew install ariga/tap/atlas
  1. docker pull arigaio/atlas
  2. 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:

  1. docker run --rm --net=host \
  2. -v $(pwd)/migrations:/migrations \
  3. arigaio/atlas migrate apply
  4. --url "mysql://root:pass@:3306/test"

Download the latest release and move the atlas binary to a file location on your system PATH.

Login to Atlas

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

Composite Schema

An ent/schema package is mostly used for defining Ent types (objects), their fields, edges and logic. Functional indexes, do not have representation in Ent schema, as Ent supports defining indexes on fields, edges (foreign-keys), and the combination of them.

In order to extend our PostgreSQL schema migration with functional indexes to our Ent types (tables), we configure Atlas to read the state of the schema from a Composite Schema data source. Follow the steps below to configure this for your project:

  1. Let’s define a simple schema with one type (table): User (table users):

ent/schema/user.go

  1. // User holds the schema definition for the User entity.
  2. type User struct {
  3. ent.Schema
  4. }
  5. // Fields of the User.
  6. func (User) Fields() []ent.Field {
  7. return []ent.Field{
  8. field.String("name").
  9. Comment("A unique index is defined on lower(name) in schema.sql"),
  10. }
  11. }
  1. Next step, we define a functional index on the name field in the schema.sql file:

schema.sql

  1. -- Create a functional (unique) index on the lowercased name column.
  2. CREATE UNIQUE INDEX unique_name ON "users" ((lower("name")));
  1. Create a simple atlas.hcl config file with a composite_schema that includes both the functional indexes defined in schema.sql and your Ent schema:

atlas.hcl

  1. data "composite_schema" "app" {
  2. # Load the ent schema first with all tables.
  3. schema "public" {
  4. url = "ent://ent/schema"
  5. }
  6. # Then, load the functional indexes.
  7. schema "public" {
  8. url = "file://schema.sql"
  9. }
  10. }
  11. env "local" {
  12. src = data.composite_schema.app.url
  13. dev = "docker://postgres/15/dev?search_path=public"
  14. }

Usage

After setting up our composite schema, we can get its representation using the atlas schema inspect command, generate schema migrations for it, apply them to a database, and more. Below are a few commands to get you started with Atlas:

Inspect the Schema

The atlas schema inspect command is commonly used to inspect databases. However, we can also use it to inspect our composite_schema and print the SQL representation of it:

  1. atlas schema inspect \
  2. --env local \
  3. --url env://src \
  4. --format '{{ sql . }}'

The command above prints the following SQL.

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

Note, our functional index is defined on the name field in the users table.

Generate Migrations For the Schema

To generate a migration for the schema, run the following command:

  1. atlas migrate diff \
  2. --env local

Note that a new migration file is created with the following content:

migrations/20240712090543.sql

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

Apply the Migrations

To apply the migration generated above to a database, run the following command:

  1. atlas migrate apply \
  2. --env local \
  3. --url "postgres://postgres:pass@localhost:5432/database?search_path=public&sslmode=disable"

Functional Indexes - 图2Apply the Schema Directly on the Database

Sometimes, there is a need to apply the schema directly to the database without generating a migration file. For example, when experimenting with schema changes, spinning up a database for testing, etc. In such cases, you can use the command below to apply the schema directly to the database:

  1. atlas schema apply \
  2. --env local \
  3. --url "postgres://postgres:pass@localhost:5432/database?sslmode=disable"

Or, using the Atlas Go SDK:

  1. ac, err := atlasexec.NewClient(".", "atlas")
  2. if err != nil {
  3. log.Fatalf("failed to initialize client: %w", err)
  4. }
  5. // Automatically update the database with the desired schema.
  6. // Another option, is to use 'migrate apply' or 'schema apply' manually.
  7. if _, err := ac.SchemaApply(ctx, &atlasexec.SchemaApplyParams{
  8. Env: "local",
  9. URL: "postgres://postgres:pass@localhost:5432/database?sslmode=disable",
  10. }); err != nil {
  11. log.Fatalf("failed to apply schema changes: %w", err)
  12. }

Code Example

After setting up our Ent schema with functional indexes, we expect the database to enforce the uniqueness of the name field in the users table:

  1. // Test that the unique index is enforced.
  2. client.User.Create().SetName("Ariel").SaveX(ctx)
  3. err = client.User.Create().SetName("ariel").Exec(ctx)
  4. require.EqualError(t, err, `ent: constraint failed: pq: duplicate key value violates unique constraint "unique_name"`)
  5. // Type-assert returned error.
  6. var pqerr *pq.Error
  7. require.True(t, errors.As(err, &pqerr))
  8. require.Equal(t, `duplicate key value violates unique constraint "unique_name"`, pqerr.Message)
  9. require.Equal(t, user.Table, pqerr.Table)
  10. require.Equal(t, "unique_name", pqerr.Constraint)
  11. require.Equal(t, pq.ErrorCode("23505"), pqerr.Code, "unique violation")

The code for this guide can be found in GitHub.