Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ets.lookup_element(Ecto.Registry, nil, 3) in customized mix task

Created customized task under lib/mix/tasks/load_mnemonics.ex Getting weird error while bulk inserts from CSV file into a DB table. A command to execute a task is

mix data_monitor.load_mnemonics

defmodule Mix.Tasks.DataMonitor.LoadMnemonics do
  use Mix.Task

  alias DataMonitor.Mnemonic
  alias DataMonitor.Repo

  require Logger

  @shortdoc "Loads mnemonics from mnemonics.csv"

  def run(_) do
    mnemonics =
      File.stream!(Path.expand("files/mnemonics.csv"))
      |> CSV.decode!(headers: true)

    insert_rows =
      Enum.reduce(mnemonics, [], fn row, result ->
        result ++
          [
            row
            |> Map.new(fn {k, v} -> {String.to_atom(k), v} end)
            |> Map.put(:inserted_at, Timex.now())
            |> Map.put(:updated_at, Timex.now())
          ]
      end)

    Repo.insert_all(Mnemonic, insert_rows)
  end
end

Error Log :

** (ArgumentError) argument error
    (stdlib) :ets.lookup_element(Ecto.Registry, nil, 3)
    lib/ecto/registry.ex:18: Ecto.Registry.lookup/1
    lib/ecto/adapters/sql.ex:251: Ecto.Adapters.SQL.sql_call/6
    lib/ecto/adapters/sql.ex:198: Ecto.Adapters.SQL.query!/5
    lib/ecto/adapters/postgres.ex:96: Ecto.Adapters.Postgres.insert_all/7
    lib/ecto/repo/schema.ex:52: Ecto.Repo.Schema.do_insert_all/7
    (mix) lib/mix/task.ex:314: Mix.Task.run_task/3
    (mix) lib/mix/cli.ex:80: Mix.CLI.run_task/2
    (elixir) lib/code.ex:677: Code.require_file/2
like image 884
Jagdish Avatar asked Jan 02 '23 07:01

Jagdish


1 Answers

You need to explicitly start your application before running database queries; mix tasks don't do that automatically.

Change:

def run(_) do
  ..
end

To:

def run(_) do
  {:ok, _} = Application.ensure_all_started(:my_app)
  ...
end

(Replace :my_app with your app's name.)

like image 74
Dogbert Avatar answered Jan 04 '23 19:01

Dogbert