Examples

Elixir Ecto Migration

Running an Ecto Migration

Elixir Ecto migration updates database schemas with mix ecto.migrate.

Introduction to Ecto Migrations

Ecto is a powerful database wrapper and query generator for Elixir applications. An integral part of Ecto is its ability to manage database schema changes over time through migrations. Migrations allow developers to evolve their database schema incrementally and keep track of changes in a systematic way.

Creating a New Migration

To create a new migration in an Ecto project, you can use the mix ecto.gen.migration task. This task generates a new migration file with a timestamp in the priv/repo/migrations directory.

Writing a Migration Script

Each migration file contains two functions: up and down. The up function defines the changes to apply to the database, while the down function reverses those changes.

Here is an example of a migration script that adds a new table:

Running Migrations

Once you have defined your migration, you can apply it to your database using the mix ecto.migrate command. This command will execute all pending migrations, updating your database schema to the latest version.

Reverting Migrations

If you need to reverse a migration, you can use the mix ecto.rollback command. This command will roll back the last executed migration, reverting the database schema to its previous state.

Best Practices for Ecto Migrations

  • Keep Migrations Small and Focused: Each migration should accomplish a single task to ensure clarity and simplicity.
  • Test Migrations: Always test migrations in a development environment before applying them to production.
  • Backup Database: Before running migrations on a production database, ensure you have a backup.

Following these best practices helps maintain a clean and reliable database schema evolution process.