在lib / mix / tasks / load_mnemonics.ex下创建自定义任务 从CSV文件批量插入数据库表时出现奇怪的错误。 执行任务的命令是
混合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
答案 0 :(得分:6)
您需要在运行数据库查询之前显式启动应用程序;混合任务不会自动执行此操作。
变化:
def run(_) do
..
end
要:
def run(_) do
{:ok, _} = Application.ensure_all_started(:my_app)
...
end
(将:my_app
替换为您应用的名称。)