Track Ecto Migrations
Here's how to create, apply and rollback db migrations with ecto.
List all ecto migrations
mix ecto.migrationsGives something like:
mix ecto.migrations
Repo: BookStore.Repo
Status Migration ID Migration Name
--------------------------------------------------
...
up 20260107001015 my_other_migration
up 20260115213050 my_migration_nameGenerate an ecto migration
When you have new changes you want to make to your database schema, you create a migration file to track those changes:
mix ecto.gen.migration my_migration_nameThis will give you a scaffold something like this file, priv/repo/migrations/20260115213050_my_migration_name.exs:
defmodule BookStore.MyMigrationName do
use Ecto.Migration
def change do
# for you to fill in.
end
endOr if you have a cool framework like Ash, it'll generate migration content for you based on the definition of the domain's resources:
mix ash_postgres.generate_migrations my_migration_nameThis will generate a migration with the appropriate alter, drop calls, etc.
Run ecto migrations
To apply your migration to the database, run:
mix ecto.migrateMigrate down or rollback
If you want to reverse what you just migrated, you can migrate down, reverse course, and go the other direction.
To roll back just the latest migration, choose -n 1:
mix ecto.rollback -n 1Permanently remove a migration
Only change or remove migrations that you haven't deployed to prod. Migrations are generally meant to comply to a roll-forward type strategy. We make changes upon our previous changes, but we don't go backward.
But in dev, you might have a reason to change or permanently remove a migration.
First rollback the migration, as above, then remove the /priv/repo/migrations/my_migration_name.exs file. Then gen new migrations and migrate, and you'll be good.