Custom migrations

Custom migrations - 图1Supporting repository

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

Custom migrations

In some cases, you may want to write custom migrations that are not automatically generated by Atlas. This can be useful in cases where you want to perform changes to your database that aren’t currently supported by Ent, or if you want to seed the database with data.

In this section, we will learn how to add custom migrations to our project. For the purpose of this guide, let’s assume we want to seed the users table with some data.

Create a custom migration

Let’s start by adding a new migration file to our project:

  1. atlas migrate new seed_users --dir file://ent/migrate/migrations

Observe that a new file named 20221115102552_seed_users.sql was created in the ent/migrate/migrations directory.

Continue by opening the file and adding the following SQL statements:

  1. INSERT INTO `users` (`name`, `email`, `title`)
  2. VALUES ('Jerry Seinfeld', 'jerry@seinfeld.io', 'Mr.'),
  3. ('George Costanza', 'george@costanza.io', 'Mr.')

Recalculating the checksum file

Let’s try to run our new custom migration:

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

Atlas fails with an error:

  1. You have a checksum error in your migration directory.
  2. This happens if you manually create or edit a migration file.
  3. Please check your migration files and run
  4. 'atlas migrate hash'
  5. to re-hash the contents and resolve the error
  6. Error: checksum mismatch

Atlas introduces the concept of migration directory integrity as a means to enforce a linear migration history. This way, if multiple developers work on the same project in parallel, they can be sure that their merged migration history is correct.

Let’s re-hash the contents of our migration directory to resolve the error:

  1. atlas migrate hash --dir file://ent/migrate/migrations

If we run atlas migrate apply again, we will see that the migration was successfully applied:

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

Atlas reports:

  1. Migrating to version 20221115102552 from 20221115101649 (1 migrations in total):
  2. -- migrating version 20221115102552
  3. -> INSERT INTO `users` (`name`, `email`, `title`)
  4. VALUES ('Jerry Seinfeld', 'jerry@seinfeld.io', 'Mr.'),
  5. ('George Costanza', 'george@costanza.io', 'Mr.')
  6. -- ok (9.077102ms)
  7. -------------------------
  8. -- 19.857555ms
  9. -- 1 migrations
  10. -- 1 sql statements

In the next section, we will learn how to automatically verify the safety of our schema migrations using Atlas’s Linting feature.