DataMigration (data_migration v0.2.0)

View Source

Lists data migrations that have not run, runs one by version, and marks a data migration as one-shot or repeatable.

A data migration is an Ecto.Migration kept in a folder of its own, such as priv/repo/data_migrations, and recorded in the repo's schema_migrations table like any other migration. DataMigration.LiveDashboard.Page shows them on a LiveDashboard page.

paths below are directories, as Ecto.Migrator.migrations/3 takes them. Ecto.Migrator.migrations_path(repo, "data_migrations") gives the usual one.

One-shot and repeatable

defmodule MyApp.Repo.DataMigrations.MirrorAvatars do
  use DataMigration, repeatable: true

  def up, do: MyApp.Avatars.mirror_all()
  def down, do: :ok
end

use DataMigration is use Ecto.Migration plus that annotation. A data migration is one-shot unless it says repeatable: true, and so is one that uses Ecto.Migration directly. Either kind is pending until it has run once. run/4 refuses to run a one-shot data migration a second time, and runs a repeatable one again.

Summary

Functions

The data migrations in paths that have not run, oldest first, as {version, name}.

Whether the migration module was declared with use DataMigration, repeatable: true.

Runs the data migration with version in paths, and no other.

Functions

pending(repo, paths)

The data migrations in paths that have not run, oldest first, as {version, name}.

Reads the recorded versions without taking the migration lock, so a deploy that holds it does not block the caller, and without creating the schema_migrations table.

repeatable?(module)

Whether the migration module was declared with use DataMigration, repeatable: true.

run(repo, version, paths, opts \\ [])

Runs the data migration with version in paths, and no other.

Returns :ok once it has run. Otherwise it runs nothing and returns:

  • {:error, :not_found} when no file in paths has version.
  • {:error, :duplicate_version} when more than one does.
  • {:error, :already_applied} when the data migration is one-shot and has run.

A repeatable data migration that has run is run again: its row in schema_migrations is deleted, then Ecto.Migrator.up/4 runs it and records it again. If that run raises, the row stays deleted, so the data migration is pending.

opts are passed to Ecto.Migrator.up/4.