mirror of
https://github.com/ent/ent.git
synced 2026-05-24 09:31:56 +03:00
202 lines
6.3 KiB
Plaintext
202 lines
6.3 KiB
Plaintext
---
|
|
title: Using Postgres Enum Types in Ent Schema
|
|
id: enum
|
|
slug: enum-types
|
|
---
|
|
|
|
import Tabs from '@theme/Tabs';
|
|
import TabItem from '@theme/TabItem';
|
|
import InstallationInstructions from '../components/_installation_instructions.mdx';
|
|
|
|
|
|
Enum types are data structures that consist of a predefined, ordered set of values. By default, when using `field.Enum`
|
|
in your Ent schema, Ent uses simple string types to represent the enum values in **PostgreSQL and SQLite**. However, in some
|
|
cases, you may want to use the native enum types provided by the database.
|
|
|
|
This guide explains how to define a schema field that uses a native PostgreSQL enum type and configure the schema migration
|
|
to manage both Postgres enums and the Ent schema as a single migration unit using Atlas.
|
|
|
|
:::info [Atlas Pro Feature](https://atlasgo.io/features#pro-plan)
|
|
Atlas support for [Composite Schema](https://atlasgo.io/atlas-schema/projects#data-source-composite_schema) used in this
|
|
guide is available exclusively to Pro users. To use this feature, run:
|
|
```
|
|
atlas login
|
|
```
|
|
:::
|
|
|
|
## Install Atlas
|
|
|
|
<InstallationInstructions />
|
|
|
|
## Login to Atlas
|
|
|
|
```shell
|
|
$ atlas login a8m
|
|
//highlight-next-line-info
|
|
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. External enum types,
|
|
or any other database objects do not have representation in Ent models - A Postgres enum type can be defined once in your Postgres
|
|
schema, and may be used multiple times in different fields and models.
|
|
|
|
In order to extend our PostgreSQL schema to include both custom enum types and our Ent types, we configure Atlas to
|
|
read the state of the schema from a [Composite Schema](https://atlasgo.io/atlas-schema/projects#data-source-composite_schema)
|
|
data source. Follow the steps below to configure this for your project:
|
|
|
|
1\. Create a `schema.sql` that defines the necessary enum type there. In the same way, you can define the enum type in
|
|
[Atlas Schema HCL language](https://atlasgo.io/atlas-schema/hcl-types#enum):
|
|
|
|
<Tabs>
|
|
<TabItem value={"sql"} label={"Using SQL"}>
|
|
|
|
```sql title="schema.sql"
|
|
CREATE TYPE status AS ENUM ('active', 'inactive', 'pending');
|
|
```
|
|
|
|
</TabItem>
|
|
<TabItem value={"hcl"} label={"Using HCL"}>
|
|
|
|
```hcl title="schema.hcl"
|
|
schema "public" {}
|
|
|
|
enum "status" {
|
|
schema = schema.public
|
|
values = ["active", "inactive", "pending"]
|
|
}
|
|
```
|
|
|
|
</TabItem>
|
|
</Tabs>
|
|
|
|
2\. In your Ent schema, define an enum field that uses the underlying Postgres `ENUM` type:
|
|
|
|
```go title="ent/schema/user.go" {6-8}
|
|
// 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",
|
|
}),
|
|
}
|
|
}
|
|
```
|
|
|
|
:::note
|
|
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., `TEXT` in SQLite and `ENUM (...)` in MariaDB or MySQL)s.
|
|
:::
|
|
|
|
3\. Create a simple `atlas.hcl` config file with a `composite_schema` that includes both your custom enum types defined in
|
|
`schema.sql` and your Ent schema:
|
|
|
|
```hcl title="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"
|
|
}
|
|
```
|
|
|
|
## 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:
|
|
|
|
```shell
|
|
atlas schema inspect \
|
|
--env local \
|
|
--url env://src \
|
|
--format '{{ sql . }}'
|
|
```
|
|
|
|
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:
|
|
|
|
```sql
|
|
-- 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"));
|
|
```
|
|
|
|
#### Generate Migrations For the Schema
|
|
|
|
To generate a migration for the schema, run the following command:
|
|
|
|
```shell
|
|
atlas migrate diff \
|
|
--env local
|
|
```
|
|
|
|
Note that a new migration file is created with the following content:
|
|
|
|
```sql title="migrations/20240712090543.sql"
|
|
-- 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"));
|
|
```
|
|
|
|
#### Apply the Migrations
|
|
|
|
To apply the migration generated above to a database, run the following command:
|
|
|
|
```
|
|
atlas migrate apply \
|
|
--env local \
|
|
--url "postgres://postgres:pass@localhost:5432/database?search_path=public&sslmode=disable"
|
|
```
|
|
|
|
:::info Apply 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:
|
|
|
|
```shell
|
|
atlas schema apply \
|
|
--env local \
|
|
--url "postgres://postgres:pass@localhost:5432/database?search_path=public&sslmode=disable"
|
|
```
|
|
|
|
Or, using the [Atlas Go SDK](https://github.com/ariga/atlas-go-sdk):
|
|
|
|
```go
|
|
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",
|
|
}); err != nil {
|
|
log.Fatalf("failed to apply schema changes: %w", err)
|
|
}
|
|
```
|
|
|
|
:::
|
|
|
|
The code for this guide can be found in [GitHub](https://github.com/ent/ent/tree/master/examples/enumtypes).
|