Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,12 @@ mix deps.get
- Caches migration list in `:persistent_term` for performance
- In dev mode, automatically recompiles migrations on each page load

2. **DataMigration.Logger** (`lib/data_migration/logger.ex`)
2. **DataMigration** (`lib/data_migration.ex`)
- `pending/2` lists the data migrations that have not run; `run/4` runs one by version
- `use DataMigration, repeatable: true` marks a data migration that `run/4` may run again;
anything else, including a plain `use Ecto.Migration`, is one-shot

3. **DataMigration.Logger** (`lib/data_migration/logger.ex`)
- Custom logger backend that captures Ecto migration logs
- Implements both `:gen_event` (legacy) and `:logger_handler` (OTP 21+) behaviors
- Filters logs by MFA (module/function/arity) patterns
Expand Down
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,17 @@
# Changelog

## unreleased

- Add `DataMigration.pending/2`, which lists the data migrations that have not
run, oldest first.
- Add `DataMigration.run/4`, which runs one data migration by version. It runs
nothing and returns an error for a version no file has, or for a one-shot data
migration that has run.
- Add `use DataMigration, repeatable: true` to mark a data migration that can
run again. A data migration is one-shot unless it says so.
- Tests run the sandbox in manual mode, so a migration a test runs no longer
leaves its row in the test database.

## 0.1.2 (2026-08-05)

- Fixup Elixir 1.20 type warning
Expand Down
38 changes: 38 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,44 @@ Options you may supply to the page:
the app will listen to `Ecto.Adapters.SQL`, Ecto.Migration.Runner, and `Ecto.Migrator` for logs.


### Running data migrations by version

`DataMigration.pending/2` lists the data migrations that have not run, oldest
first, and `DataMigration.run/4` runs one by version, and no other:

```elixir
path = Ecto.Migrator.migrations_path(MyApp.Repo, "data_migrations")

DataMigration.pending(MyApp.Repo, path)
#=> [{20260101120000, "mirror_avatars"}]

DataMigration.run(MyApp.Repo, 20260101120000, path)
#=> :ok
```

`run/4` runs nothing and returns `{:error, :not_found}` for a version no file
has, and `{:error, :already_applied}` for a one-shot data migration that has
run.

### One-shot and repeatable data migrations

A data migration is one-shot unless it says otherwise. Mark one that is safe to
run again with `use DataMigration, repeatable: true` in place of
`use Ecto.Migration`:

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

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

Either kind is pending until it has run once. `DataMigration.run/4` runs a
repeatable one again, and refuses to run a one-shot one twice. The dashboard
page's "Migrate up" still runs a data migration once.

Requires OTP 27+

### Screenshots
Expand Down
11 changes: 8 additions & 3 deletions config/config.exs
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,17 @@ if config_env() == :test do
pool_size = max(10, System.schedulers_online() * 2)
database = "data_migration_test"

# `migration_lock: false` on every repo: the lock holds the test's sandboxed
# connection while the migrator runs `up/0` from a task that needs it too.
config :data_migration, Test.PGRepo,
database: database,
hostname: "localhost",
port: 15435,
username: "postgres",
password: "postgres",
pool_size: pool_size,
pool: Ecto.Adapters.SQL.Sandbox
pool: Ecto.Adapters.SQL.Sandbox,
migration_lock: false

config :data_migration, Test.TDSRepo,
database: database,
Expand All @@ -32,7 +35,8 @@ if config_env() == :test do
username: "sa",
password: "StrongPassword!",
pool_size: pool_size,
pool: Ecto.Adapters.SQL.Sandbox
pool: Ecto.Adapters.SQL.Sandbox,
migration_lock: false

config :data_migration, Test.MyXQLRepo,
hostname: "localhost",
Expand All @@ -42,7 +46,8 @@ if config_env() == :test do
password: "mysql",
pool: Ecto.Adapters.SQL.Sandbox,
pool_size: pool_size,
port: 13306
port: 13306,
migration_lock: false

config :data_migration, Test.SQLiteRepo,
pool: Ecto.Adapters.SQL.Sandbox,
Expand Down
156 changes: 155 additions & 1 deletion lib/data_migration.ex
Original file line number Diff line number Diff line change
@@ -1,5 +1,159 @@
defmodule DataMigration do
@moduledoc """
See `DataMigration.LiveDashboard.Page`
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.
"""

import Ecto.Query, only: [from: 2]

defmacro __using__(opts) do
opts = Keyword.validate!(opts, repeatable: false)
repeatable? = Keyword.fetch!(opts, :repeatable)

if not is_boolean(repeatable?) do
raise ArgumentError, ":repeatable must be true or false, got: #{inspect(repeatable?)}"
end

quote do
use Ecto.Migration

@doc false
def __data_migration__, do: [repeatable: unquote(repeatable?)]
end
end

@doc """
Whether the migration `module` was declared with `use DataMigration, repeatable: true`.
"""
def repeatable?(module) when is_atom(module) do
Code.ensure_loaded?(module) and function_exported?(module, :__data_migration__, 0) and
Keyword.get(module.__data_migration__(), :repeatable, false)
end

@doc """
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.
"""
def pending(repo, paths) do
repo
|> Ecto.Migrator.migrations(List.wrap(paths),
skip_table_creation: true,
migration_lock: false
)
|> Enum.flat_map(fn
{:down, version, name} -> [{version, name}]
{:up, _version, _name} -> []
end)
end

@doc """
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`.
"""
def run(repo, version, paths, opts \\ []) when is_integer(version) do
with {:ok, file} <- find_file(paths, version) do
module = migration_module(file)

case up(repo, version, module, opts) do
{:error, :already_applied} = refused -> maybe_rerun(repo, version, module, opts, refused)
:ok -> :ok
end
end
end

defp maybe_rerun(repo, version, module, opts, refused) do
if repeatable?(module) do
forget(repo, version, opts)
up(repo, version, module, opts)
else
refused
end
end

defp up(repo, version, module, opts) do
case Ecto.Migrator.up(repo, version, module, opts) do
:ok -> :ok
:already_up -> {:error, :already_applied}
end
end

defp find_file(paths, version) do
paths
|> List.wrap()
|> Enum.flat_map(&Path.wildcard(Path.join(&1, "#{version}_*.exs")))
|> case do
[file] -> {:ok, file}
[] -> {:error, :not_found}
[_ | _] -> {:error, :duplicate_version}
end
end

# Code.compile_file/1 redefines a module that is already loaded, which is what
# a second run of the same file needs. Its "redefining module" warning is
# expected here, so it is captured rather than printed.
defp migration_module(file) do
{compiled, _diagnostics} = Code.with_diagnostics(fn -> Code.compile_file(file) end)

Enum.find_value(compiled, fn {module, _binary} ->
function_exported?(module, :__migration__, 0) && module
end) ||
raise Ecto.MigrationError, "#{Path.relative_to_cwd(file)} does not define an Ecto.Migration"
end

# The same delete `Ecto.Migrator.down/4` makes, without running `down/0`.
defp forget(repo, version, opts) do
config = repo.config()
migration_repo = Keyword.get(config, :migration_repo, repo)
source = Keyword.get(config, :migration_source, "schema_migrations")

migration_repo.delete_all(
from(m in source, where: m.version == type(^version, :integer)),
prefix: opts[:prefix],
timeout: :infinity,
log: Keyword.get(opts, :log_migrator_sql, false),
schema_migration: true,
ecto_query: :schema_migration,
telemetry_options: [schema_migration: true]
)
end
end
2 changes: 1 addition & 1 deletion mix.exs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
defmodule DataMigration.MixProject do
use Mix.Project
@version "0.1.2"
@version "0.2.0"

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

or 0.1.3?

@source_url "https://github.com/tv-labs/data-migration"
@adapters ~w[pg myxql tds sqlite]

Expand Down
Loading
Loading