11

我想在自定义混合任务中通过 Ecto 显示我的数据库中的数据。如何在我的任务中获取 Ecto 存储库(或启动它)?

我尝试了这样的事情,但没有奏效:

defmodule Mix.Tasks.Users.List do


use Mix.Task
  use Mix.Config
  use Ecto.Repo, otp_app: :app

  @shortdoc "List active users"
  @moduledoc """
    List active users
  """
  def run(_) do
    import Ecto.Query, only: [from: 1]

    Mix.shell.info "=== Active users ==="
    query = from u in "users"
    sync = all(query)
    Enum.each(users, fn(s) -> IO.puts(u.name) end)
  end

end

当我启动 mix users.list 时,这将为我提供以下输出:

** (ArgumentError) repo Mix.Tasks.Users.List is not started, please ensure it is part of your supervision tree
    lib/ecto/query/planner.ex:64: Ecto.Query.Planner.query_lookup/5
    lib/ecto/query/planner.ex:48: Ecto.Query.Planner.query_with_cache/6
    lib/ecto/repo/queryable.ex:119: Ecto.Repo.Queryable.execute/5

任何想法或其他方法来解决这个问题?

4

4 回答 4

14

Ecto 3.x:

ensure_started此后已从 Ecto 中删除。围绕这个话题有很多困惑。有关更多信息,请参见此处https://github.com/elixir-ecto/ecto/pull/2829#issuecomment-456313417。José 建议使用 启动应用程序Mix.Task.run "app.start"或使用MyApp.Repo.start_link(...).

Ecto 2.x:

这曾经在 2.x 中工作,但显然Mix.Ecto不被视为公共 API 的一部分。

实际上有一个帮助模块Mix.Ectohttps://github.com/elixir-ecto/ecto/blob/master/lib/mix/ecto.ex)可以更轻松地编写使用 ecto 的混合任务:

defmodule Mix.Tasks.Users.List do
  use Mix.Task
  import Mix.Ecto

  def run(args) do
    repos = parse_repo(args)

    Enum.each repos, fn repo ->
      Mix.shell.info "=== Active users ==="

      ensure_repo(repo, args)
      ensure_started(repo, [])
      users = repo.all(Ectotask.User)

      Enum.each(users, fn(s) -> IO.puts(s.name) end)
    end
  end
end

此帮助程序使您可以访问parse_repo/1, ensure_repo/2, ensure_started/1. parse_repo会让您的任务与其他 ecto mix 任务很好地配合,例如,它会让您通过 -r 来指定不同的 repo。

➤ mix users.list
=== Active users ===
Adam
➤ mix users.list -r Ectotask.Repo22
=== Active users ===
** (Mix) could not load Ectotask.Repo22, error: :nofile. Please pass a repo with the -r option.

ensure_started确保你缺少的 repo 正在运行。

如需指导和启发,您可以在https://github.com/elixir-ecto/ecto/tree/master/lib/mix/tasks查看其他 ecto mix 任务是如何实现的

于 2016-07-06T14:24:11.957 回答
9

除了Jason Harrelson的回答:还需要启动PostgrexEcto

[:postgrex, :ecto]
|> Enum.each(&Application.ensure_all_started/1)

MyApp.Repo.start_link

更新:

另一种方法是使用混合任务启动应用程序:

Mix.Task.run "app.start", []
于 2016-11-11T06:51:11.740 回答
2

您需要确保在使用之前启动 repo

MyApp.Repo.start_link
于 2016-07-06T14:05:03.767 回答
0

与 Phoenix 合作时,我还找到了另一个解决方案。我在其中创建了一个新文件priv/repo

defmodule Users.List do
  def run() do
    Mix.shell.info "=== Active users ==="

    users = App.Repo.all(App.User)
    Enum.each(users, fn(s) ->
      Mix.shell.info("#{s.name}")
    end)
  end
end
Users.List.run

mix run priv/repo/users.list.exs然后我从我的项目根目录运行它。

于 2016-07-06T15:18:05.333 回答