ets.lookup_element(Ecto.Registry, nil, 3) 在自定义混合任务中

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

在 lib/mix/tasks/load_mnemonics.ex 下创建了自定义任务 从 CSV 文件批量插入数据库时​​出现奇怪的错误 table。 执行任务的命令是

混合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

错误日志:

** (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

您需要在 运行 数据库查询之前显式启动您的应用程序;混合任务不会自动执行。

变化:

def run(_) do
  ..
end

收件人:

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

(将 :my_app 替换为您的应用名称。)