Today I Learned

A Hashrocket project

Mix tasks accessing the db with `Mix.Ecto`

When running reports or one-off data operations it might be necessary to create a mix task that can access the database. Ecto provides convenience functions in the Mix.Ecto module to help facilitate setting up and starting the Ecto repos.

The function parse_repo(args) will process the arguments used when calling the mix task. It looks specifically for -r MyApp.Repo but if you don’t pass anything it will return all the repos from the configuration.

The function ensure_started(repo) takes the repo as an argument ensures that the Repo application has been started. Without calling this function the Repo will throw an error when used.

Put it all together:

defmodule Mix.Tasks.MyApp.SayHi do
  use Mix.Task
  import Mix.Ecto

  def run(args) do
    repo = parse_repo(args) |> hd

    ensure_started(repo)

    result = repo.query("select 'hi!';")

    result.rows
    |> hd
    |> hd
    |> IO.puts
  end
end
Looking for help? Elixir is quickly gaining momentum for web applications that need concurrency, performance, and the ability to connect to many different clients. The developers at Hashrocket are learning along with the rest of the development community that Elixir and Phoenix are viable Rails alternatives for the right application. Check out the source code for Today I Learned, written in Elixir, and contact us if you need help with your Elixir project.