Using Composite Types in Ent Schema

In PostgreSQL, a composite type is structured like a row or record, consisting of field names and their corresponding data types. Setting an Ent field as a composite type enables you to store complex and structured data in a single column.

This guide explains how to define a schema field type as a composite type in your Ent schema and configure the schema migration to manage both the composite types and the Ent schema as a single migration unit using Atlas.

Composite Types - 图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. Composite types, or any other database objects do not have representation in Ent models - A composite type can be defined once, and may be used multiple times in different fields and models.

In order to extend our PostgreSQL schema to include both custom composite types and our Ent types, 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. Create a schema.sql that defines the necessary composite type. In the same way, you can configure the composite type in Atlas Schema HCL language:
  • Using SQL
  • Using HCL

schema.sql

  1. CREATE TYPE address AS (
  2. street text,
  3. city text
  4. );

schema.hcl

  1. schema "public" {}
  2. composite "address" {
  3. schema = schema.public
  4. field "street" {
  5. type = text
  6. }
  7. field "city" {
  8. type = text
  9. }
  10. }
  1. In your Ent schema, define a field that uses the composite type only in PostgreSQL dialect:
  • Schema
  • Address Type

ent/schema/user.go

  1. // Fields of the User.
  2. func (User) Fields() []ent.Field {
  3. return []ent.Field{
  4. field.String("address").
  5. GoType(&Address{}).
  6. SchemaType(map[string]string{
  7. dialect.Postgres: "address",
  8. }),
  9. }
  10. }

Composite Types - 图2note

In case a schema with custom driver-specific types is used with other databases, Ent falls back to the default type used by the driver (e.g., “varchar”).

ent/schematype/address.go

  1. type Address struct {
  2. Street, City string
  3. }
  4. var _ field.ValueScanner = (*Address)(nil)
  5. // Scan implements the database/sql.Scanner interface.
  6. func (a *Address) Scan(v interface{}) (err error) {
  7. switch v := v.(type) {
  8. case nil:
  9. case string:
  10. _, err = fmt.Sscanf(v, "(%q,%q)", &a.Street, &a.City)
  11. case []byte:
  12. _, err = fmt.Sscanf(string(v), "(%q,%q)", &a.Street, &a.City)
  13. }
  14. return
  15. }
  16. // Value implements the driver.Valuer interface.
  17. func (a *Address) Value() (driver.Value, error) {
  18. return fmt.Sprintf("(%q,%q)", a.Street, a.City), nil
  19. }
  1. Create a simple atlas.hcl config file with a composite_schema that includes both your custom types defined in schema.sql and your Ent schema:

atlas.hcl

  1. data "composite_schema" "app" {
  2. # Load first custom types first.
  3. schema "public" {
  4. url = "file://schema.sql"
  5. }
  6. # Second, load the Ent schema.
  7. schema "public" {
  8. url = "ent://ent/schema"
  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 schema, we can get its representation using the atlas schema inspect command, generate 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. Note, the address composite type is defined in the schema before its usage in the address field:

  1. -- Create composite type "address"
  2. CREATE TYPE "address" AS ("street" text, "city" text);
  3. -- Create "users" table
  4. CREATE TABLE "users" ("id" bigint NOT NULL GENERATED BY DEFAULT AS IDENTITY, "address" "address" NOT NULL, PRIMARY KEY ("id"));

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 composite type "address"
  2. CREATE TYPE "address" AS ("street" text, "city" text);
  3. -- Create "users" table
  4. CREATE TABLE "users" ("id" bigint NOT NULL GENERATED BY DEFAULT AS IDENTITY, "address" "address" NOT NULL, PRIMARY KEY ("id"));

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"

Composite Types - 图3Apply 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?search_path=public&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?search_path=public&sslmode=disable",
  10. }); err != nil {
  11. log.Fatalf("failed to apply schema changes: %w", err)
  12. }

The code for this guide can be found in GitHub.