Skip to content

Instantly share code, notes, and snippets.

@hipertracker
Last active January 17, 2023 04:01
Show Gist options
  • Save hipertracker/a2ae2c7adf1fdd78b45712abeade7fe3 to your computer and use it in GitHub Desktop.
Save hipertracker/a2ae2c7adf1fdd78b45712abeade7fe3 to your computer and use it in GitHub Desktop.
Phoenix: how to run Ecto in Mix custom task?
defmodule Mix.Tasks.MyTask do
use Mix.Task
import Ecto.Query
alias MyApp.Repo
@start_apps [
:postgrex,
:ecto,
:ecto_sql
]
@repos Application.get_env(:my_app, :ecto_repos, [])
def run(args) do
start_services()
# Run Ecto...
stop_services()
end
defp start_services do
Enum.each(@start_apps, &Application.ensure_all_started/1)
Enum.each(@repos, & &1.start_link(pool_size: 2))
end
defp stop_services do
:init.stop()
end
end
@hipertracker
Copy link
Author

Or just use this:

defmodule Mix.Tasks.MyTask do
  use Mix.Task
  import Ecto.Query
  alias MyApp.Repo

  def run(args) do
    Mix.Task.run("app.start")
    # Run Ecto...
  end
end

@mingyar
Copy link

mingyar commented Jan 17, 2023

Helped a lot!

Thanks @hipertracker!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment