diff --git a/AGENTS.md b/AGENTS.md index 2ecd541..29b77af 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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 diff --git a/CHANGELOG.md b/CHANGELOG.md index c038ae0..afa650a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/README.md b/README.md index 55377de..8384c5e 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/config/config.exs b/config/config.exs index 17ca7c0..f2c1963 100644 --- a/config/config.exs +++ b/config/config.exs @@ -16,6 +16,8 @@ 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", @@ -23,7 +25,8 @@ if config_env() == :test do 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, @@ -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", @@ -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, diff --git a/lib/data_migration.ex b/lib/data_migration.ex index 2ef02f0..73a9c94 100644 --- a/lib/data_migration.ex +++ b/lib/data_migration.ex @@ -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 diff --git a/mix.exs b/mix.exs index bd79b5f..28e21af 100644 --- a/mix.exs +++ b/mix.exs @@ -1,6 +1,6 @@ defmodule DataMigration.MixProject do use Mix.Project - @version "0.1.2" + @version "0.2.0" @source_url "https://github.com/tv-labs/data-migration" @adapters ~w[pg myxql tds sqlite] diff --git a/test/data_migration_test.exs b/test/data_migration_test.exs new file mode 100644 index 0000000..25d2fb4 --- /dev/null +++ b/test/data_migration_test.exs @@ -0,0 +1,173 @@ +defmodule DataMigrationTest do + # Not async: the migrator runs `up/0` in a process of its own, which the + # sandbox's shared mode hands the test's connection. SQLite also takes one + # writer at a time, and every test here writes `schema_migrations`. + use DataMigration.ConnCase, async: false + + # `skip_table_creation`: the migrator otherwise runs CREATE TABLE IF NOT EXISTS + # on `schema_migrations`, and MySQL commits the open transaction on any DDL, + # ending the test's sandbox. test_helper.exs creates the table up front. + @opts [log: false, skip_table_creation: true] + + setup do + listener = :"data_migration_test_#{System.unique_integer([:positive])}" + Process.register(self(), listener) + {:ok, listener: listener} + end + + describe "pending/2" do + @tag :tmp_dir + test "lists the data migrations that have not run, oldest first", ctx do + write_migration(ctx, 1_001, "newer") + write_migration(ctx, 1_000, "older") + write_migration(ctx, 1_002, "ran") + + assert DataMigration.run(ctx.repo, 1_002, ctx.tmp_dir, @opts) == :ok + + assert DataMigration.pending(ctx.repo, ctx.tmp_dir) == [{1_000, "older"}, {1_001, "newer"}] + end + + @tag :tmp_dir + test "does not list a repeatable data migration once it has run", ctx do + write_migration(ctx, 1_000, "repeatable", "use DataMigration, repeatable: true") + + assert DataMigration.pending(ctx.repo, ctx.tmp_dir) == [{1_000, "repeatable"}] + assert DataMigration.run(ctx.repo, 1_000, ctx.tmp_dir, @opts) == :ok + assert DataMigration.pending(ctx.repo, ctx.tmp_dir) == [] + end + end + + describe "run/4" do + @tag :tmp_dir + test "runs the data migration with the version given and no other", ctx do + write_migration(ctx, 1_000, "older") + write_migration(ctx, 1_001, "target") + + assert DataMigration.run(ctx.repo, 1_001, ctx.tmp_dir, @opts) == :ok + + assert_received {:ran, 1_001} + refute_received {:ran, 1_000} + assert DataMigration.pending(ctx.repo, ctx.tmp_dir) == [{1_000, "older"}] + end + + @tag :tmp_dir + test "runs nothing for a version no file has", ctx do + write_migration(ctx, 1_000, "other") + + assert DataMigration.run(ctx.repo, 1_001, ctx.tmp_dir, @opts) == {:error, :not_found} + + refute_received {:ran, _version} + end + + @tag :tmp_dir + test "runs nothing for a version two files share", ctx do + write_migration(ctx, 1_000, "first") + write_migration(ctx, 1_000, "second") + + assert DataMigration.run(ctx.repo, 1_000, ctx.tmp_dir, @opts) == + {:error, :duplicate_version} + + refute_received {:ran, _version} + end + + @tag :tmp_dir + test "refuses to run a one-shot data migration a second time", ctx do + write_migration(ctx, 1_000, "ecto_migration", "use Ecto.Migration") + write_migration(ctx, 1_001, "data_migration", "use DataMigration") + + for version <- [1_000, 1_001] do + assert DataMigration.run(ctx.repo, version, ctx.tmp_dir, @opts) == :ok + + assert DataMigration.run(ctx.repo, version, ctx.tmp_dir, @opts) == + {:error, :already_applied} + + assert_received {:ran, ^version} + refute_received {:ran, ^version} + end + end + + @tag :tmp_dir + test "runs a repeatable data migration again", ctx do + write_migration(ctx, 1_000, "repeatable", "use DataMigration, repeatable: true") + + assert DataMigration.run(ctx.repo, 1_000, ctx.tmp_dir, @opts) == :ok + assert DataMigration.run(ctx.repo, 1_000, ctx.tmp_dir, @opts) == :ok + + assert_received {:ran, 1_000} + assert_received {:ran, 1_000} + assert DataMigration.pending(ctx.repo, ctx.tmp_dir) == [] + end + + @tag :tmp_dir + test "leaves a repeatable data migration pending when running it again raises", ctx do + fail_flag = Path.join(ctx.tmp_dir, "fail") + + write_migration(ctx, 1_000, "repeatable", "use DataMigration, repeatable: true", """ + if File.exists?(#{inspect(fail_flag)}), do: raise("failed on purpose") + """) + + assert DataMigration.run(ctx.repo, 1_000, ctx.tmp_dir, @opts) == :ok + File.write!(fail_flag, "") + + assert_raise RuntimeError, "failed on purpose", fn -> + DataMigration.run(ctx.repo, 1_000, ctx.tmp_dir, @opts) + end + + assert DataMigration.pending(ctx.repo, ctx.tmp_dir) == [{1_000, "repeatable"}] + end + end + + describe "repeatable?/1" do + test "is true only for a migration declared repeatable" do + [{ecto_migration, _}] = compile_module("use Ecto.Migration") + [{one_shot, _}] = compile_module("use DataMigration") + [{repeatable, _}] = compile_module("use DataMigration, repeatable: true") + + refute DataMigration.repeatable?(ecto_migration) + refute DataMigration.repeatable?(one_shot) + assert DataMigration.repeatable?(repeatable) + refute DataMigration.repeatable?(Enum) + end + + test "use DataMigration rejects an option it does not know" do + assert_raise ArgumentError, ~r/:repeatable must be true or false/, fn -> + compile_module("use DataMigration, repeatable: :yes") + end + + assert_raise ArgumentError, ~r/unknown keys \[:one_shot\]/, fn -> + compile_module("use DataMigration, one_shot: true") + end + end + end + + defp write_migration(ctx, version, name, use_line \\ "use Ecto.Migration", before_send \\ "") do + module = Module.concat([__MODULE__, "M#{:erlang.phash2({ctx.test, version, name})}"]) + + File.write!(Path.join(ctx.tmp_dir, "#{version}_#{name}.exs"), """ + defmodule #{inspect(module)} do + #{use_line} + + def up do + #{before_send} + send(#{inspect(ctx.listener)}, {:ran, #{version}}) + :ok + end + + def down, do: :ok + end + """) + end + + defp compile_module(use_line) do + module = Module.concat([__MODULE__, "Compiled#{System.unique_integer([:positive])}"]) + + Code.compile_string(""" + defmodule #{inspect(module)} do + #{use_line} + + def up, do: :ok + def down, do: :ok + end + """) + end +end diff --git a/test/support/conn_case.ex b/test/support/conn_case.ex index a38ba8e..69944e0 100644 --- a/test/support/conn_case.ex +++ b/test/support/conn_case.ex @@ -38,7 +38,8 @@ defmodule DataMigration.ConnCase do setup tags do test_repo = Application.get_env(:data_migration, :test_repo) route = Application.get_env(:data_migration, :mounted_at) - _pid = Sandbox.start_owner!(test_repo, shared: not tags[:async]) + pid = Sandbox.start_owner!(test_repo, shared: not tags[:async]) + on_exit(fn -> Sandbox.stop_owner(pid) end) conn = Phoenix.ConnTest.init_test_session(build_conn(), %{}) locations = %{test_repo => [route]} diff --git a/test/test_helper.exs b/test/test_helper.exs index ee30562..8abb350 100644 --- a/test/test_helper.exs +++ b/test/test_helper.exs @@ -42,4 +42,9 @@ Supervisor.start_link( Ecto.Migration.SchemaMigration.ensure_schema_migrations_table!(repo, repo.config(), []) +# Manual mode, so a process a test starts (a LiveView, the migrator's task) finds +# the test's sandboxed connection through `$callers` instead of checking out one +# of its own, whose writes would outlive the test. +Ecto.Adapters.SQL.Sandbox.mode(repo, :manual) + ExUnit.start()