Planning a Migration

Planning a Migration - 图1Supporting repository

The change described in this section can be found in PR #6 in the supporting repository.

Planning a migration

In this section, we will discuss how to plan a new schema migration when we make a change to our project’s Ent schema. Consider we want to add a new field to our User entity, adding a new optional field named title:

ent/schema/user.go

  1. // Fields of the User.
  2. func (User) Fields() []ent.Field {
  3. return []ent.Field{
  4. field.String("name"),
  5. field.String("email"). // <-- Our new field
  6. Unique(),
  7. field.String("title").
  8. Optional(),
  9. }
  10. }

After adding the new field, we need to rerun code-gen for our project:

  1. go generate ./...

Next, we need to create a new migration file for our change using the Atlas CLI:

  • MySQL
  • MariaDB
  • PostgreSQL
  • SQLite
  1. atlas migrate diff add_user_title \
  2. --dir "file://ent/migrate/migrations" \
  3. --to "ent://ent/schema" \
  4. --dev-url "docker://mysql/8/ent"
  1. atlas migrate diff add_user_title \
  2. --dir "file://ent/migrate/migrations" \
  3. --to "ent://ent/schema" \
  4. --dev-url "docker://mariadb/latest/test"
  1. atlas migrate diff add_user_title \
  2. --dir "file://ent/migrate/migrations" \
  3. --to "ent://ent/schema" \
  4. --dev-url "docker://postgres/15/test?search_path=public"
  1. atlas migrate diff add_user_title \
  2. --dir "file://ent/migrate/migrations" \
  3. --to "ent://ent/schema" \
  4. --dev-url "sqlite://file?mode=memory&_fk=1"

Observe a new file named 20221115101649_add_user_title.sql was created under the ent/migrate/migrations/ directory. This file contains the SQL statements to create the newly added title field in the users table:

ent/migrate/migrations/20221115101649_add_user_title.sql

  1. -- modify "users" table
  2. ALTER TABLE `users` ADD COLUMN `title` varchar(255) NULL;

Great! We’ve successfully used the Atlas CLI to automatically generate a new migration file for our change.

To apply the migration, we can run the following command:

  1. atlas migrate apply --dir file://ent/migrate/migrations --url mysql://root:pass@localhost:3306/db

Atlas reports:

  1. Migrating to version 20221115101649 from 20221114165732 (1 migrations in total):
  2. -- migrating version 20221115101649
  3. -> ALTER TABLE `users` ADD COLUMN `title` varchar(255) NULL;
  4. -- ok (36.152277ms)
  5. -------------------------
  6. -- 44.1116ms
  7. -- 1 migrations
  8. -- 1 sql statements

In the next section, we will discuss how to plan custom schema migrations for our project.