Using Ecto in a Mix.Task

Im trying to run ecto.create & ecto.migrate --all from a custom mix task. If I try to import ecto at all it says the module cannot be found.

Has anyone solved this problem? If so, how?

Code below. Im creating the migration dirs myself because the tables are created outside of elixir and this keeps ecto happy

defmodule Mix.Tasks.Init do
  use Mix.Task

  import Macro, only: [underscore: 1]

  @impl Mix.Task
  def run(_) do
    Mix.Tasks.Deps.Get.run([])

    repos = Config.Reader.read!("./config/config.exs")[:Metrics][:ecto_repos]

    Enum.each(repos, fn repo ->
      name = List.last(String.split(underscore(repo), "/", trim: true))
      Mix.Tasks.Cmd.run(["mkdir", "-p", "priv/#{name}/migrations/"])
    end)

    Mix.Task.run("app.start")

    # Mix.Ecto.Create.run([])

    # Mix.Ecto.Migrate.run(["--all"])
  end
end

My simple solution…

Mix.Tasks.Cmd.run(["mix", "ecto.create"])

Mix.Tasks.Cmd.run(["mix", "ecto.migrate --all"])
1 Like