Databases

Elixir Database Migrations

Running Migrations

Elixir database migrations use Ecto.Migrator for schema changes.

Introduction to Elixir Database Migrations

Database migrations in Elixir are essential for managing schema changes over time. They allow you to evolve your database schema without losing data and ensure that your application remains consistent. In Elixir, migrations are managed using Ecto.Migrator, a tool provided by the Ecto library.

Ecto is a database wrapper and language integrated query for Elixir. It provides a robust and flexible way to manage your database schemas with migrations, which are simply scripts that alter your database schema.

Setting Up Ecto for Migrations

Before you can use Ecto to handle migrations, you need to set up Ecto in your Elixir project. If you haven't already done so, you need to add Ecto and a database adapter as dependencies in your mix.exs file. For instance, to use PostgreSQL, you would include:

After adding the dependencies, run the following command to fetch them:

Next, you need to set up a repository which serves as the interface to your database. Generate a repository using the following command:

This command will create a repository module, typically located in lib/my_app/repo.ex, and will also modify your configuration files to include your database details.

Creating and Running Migrations

Once Ecto is set up, you can start creating migrations. A migration file contains instructions on how to modify your database schema. You can generate a new migration with the following command:

This will create a new migration file in the priv/repo/migrations directory. The filename will be prefixed with a timestamp, ensuring that each migration is unique and ordered.

Edit the generated migration file to define the changes you want to make to your database schema. For example, to create a users table, you could write:

Once your migration file is ready, run the migrations to update the database schema with the following command:

This command will apply all pending migrations, updating your database schema to its latest version.

If you need to roll back a migration, you can do so with:

The rollback command will undo the most recent migration, allowing you to revert the schema changes if necessary.

Best Practices for Database Migrations

When working with database migrations, consider the following best practices:

  • Version Control: Always commit your migration files to version control to keep a record of all schema changes.
  • Test Migrations: Test your migrations in a development environment before applying them to production to avoid data loss or corruption.
  • Backup Data: Always back up your production database before running migrations.

By following these practices, you can ensure a smooth transition and maintain data integrity during schema updates.