gpt4 book ai didi

elixir - 如何在自定义混合任务中从 Ecto 获取数据

转载 作者:行者123 更新时间:2023-12-04 01:34:38 24 4
gpt4 key购买 nike

我想在自定义混合任务中通过 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

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

最佳答案

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(...) 运行 repo。

Ecto 2.x:

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

实际上有一个辅助模块 Mix.Ecto ( https://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/1ensure_repo/2ensure_started/1parse_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 任务是如何实现的

关于elixir - 如何在自定义混合任务中从 Ecto 获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38225406/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com