How to roll back a specific ecto migration?

What is the equivalent of Phoenix Rails?

rake db:migrate:down VERSION=20100905201547
+4
source share
2 answers

There is currently no way to accomplish this .

We can completely drop it to a specific migration using:

mix ecto.rollback -v 20080906120000

or

mix ecto.rollback --to 20080906120000

But with both syntaxes, all migrations between the current and the specified will be discarded.

A user at the Elixir Forum also noted that creating a new migration that cancels what needs to be undone would be a good way to keep an accessible history.

+7
source

This should do the trick:

def rollback(version) when is_integer(version) do
  re = ~r/^#{version}_.*\.exs/
  path = Application.app_dir(:your_app, Path.join(["priv", "repo", "migrations"]))

  with {:find, "" <> file} <- {:find, Enum.find(File.ls!(path), &String.match?(&1, re))},
        {:compile, [{mod, _} | _]} <- {:compile, Code.compile_file(Path.join(path, file))},
        {:rollback, :ok} <- {:rollback, Ecto.Migrator.down(Repo, version, mod)} do
    {:ok, "Reversed migration: #{file}"}
  else
    {:find, _} -> {:error, "No migration found with version prefix: #{version}"}
    {:compile, e} -> {:error, "Problem compiling migration module: #{inspect(e)}"}
    {:rollback, e} -> {:error, "Problem reversing migration: #{inspect(e)}"}
    e -> {:error, "Something unexpected happened: #{inspect(e)}"}
  end
end
0
source

Source: https://habr.com/ru/post/1666834/


All Articles