How to use Ecto in a mix task within a Phoenix project?

I’d like to write a mix task to export data from my Phoenix project.

Here is the code I use:

defmodule Mix.Tasks.Export do
  @moduledoc "Export all data"
  use Mix.Task
  import Ecto.Query

  alias MyApp.Repo
  alias MyApp.Locations.Location

  @shortdoc "Export all data."
  def run(_) do
    query =
      from(l in Location,
        where: l.is_example == true,
        preload: [:address, :parent_location]
      )

    locations = Repo.all(query)
  end
end

It results in this error:

** (RuntimeError) could not lookup Ecto repo MyApp.Repo because it was not started or it does not exist

How can I fix this and is there a generator for mix tasks which loads the world of the Phoenix project automatically?

@requirements ["app.start"]

See Mix.Task — Mix v1.13.4

2 Likes

I think another alternative would be the use of Application.ensure_all_started/2 function as described on the The application callback module:

{:ok, _} = Application.ensure_all_started(:some_app)