【问题标题】:Migrate data from another Repo in Ecto migration在 Ecto 迁移中从另一个 Repo 迁移数据
【发布时间】:2021-06-10 09:26:05
【问题描述】:

与这个问题类似:Using a Repo in an Ecto migration,我有一个 Ecto 迁移,我想在其中创建一些新表,但也从 不同的 存储库迁移一些数据。例如:

defmodule MyApp.Repo.Migrations.CreateFoo do
  use Ecto.Migration
  import Ecto.Query

  def change do
    create table(:foo) do
      add(:status, :text)
    end

    flush()
    execute &import_from_AnotherApp/0
  end

  defp import_from_AnotherApp()
    foos = from(f in AnotherApp.Foo, where: ...)
           |> AnotherApp.Repo.all

    Enum.each(foos, fn(foo) ->
      # Insert data from AnotherApp into MyApp foo table
    end)

  end
end

问题是在运行 mix ecto.migrate 时我得到了

** (RuntimeError) could not lookup Ecto repo AnotherApp.Repo because it was not started or it does not exist

我尝试在mix.exs 中添加AnotherApp 作为MyApp 的依赖项,但我仍然遇到同样的错误。

这个可以吗?

【问题讨论】:

  • 您是否尝试过在执行查询之前手动启动AnotherApp.Repo? ecto 迁移混合任务未启动您的完整应用程序。
  • @joshnuss 是的。我确实喜欢 Everett 的回答,而且效果很好

标签: elixir database-migration ecto


【解决方案1】:

当您运行混合任务时,它们会在自己的进程中运行,因此其他应用程序(包括承载该任务的主应用程序)可能无法启动。

有时您必须将这样的行放入自定义混合任务中,我怀疑您可以将它们放入迁移中:

{:ok, _} = Application.ensure_all_started(:my_app)
{:ok, _} = Application.ensure_all_started(:another_app)

但是,有时仅确保它们已启动是不够的:有时您必须明确启动该过程。在您的情况下,您必须启动其他应用程序的Ecto.Repo。通常,您 start your Ecto repos 通过在 application.ex 内的应用程序主管中列出它们,例如

def start(_type, _args) do
  children = [
    {MyApp.Repo, []},
    {AnotherApp.Repo, []},
  ]

  opts = [strategy: :one_for_one, name: MyApp.Supervisor]
  Supervisor.start_link(children, opts)
end

但是,如果您的应用程序的常规功能不需要启动其他应用程序,那么您可以通过运行 MyApp.Repo.start_link([]) 手动启动该进程。 -- 你可以把它放到你的迁移中,看看它是否出现:

x = MyApp.Repo.start_link([])
IO.inspect(x)

如果运气好的话,你会得到一个 :ok 和一个进程 ID,但如果没有,你应该会得到一些有用的调试信息。

希望对您有所帮助。

【讨论】:

    【解决方案2】:

    也许with_repo(repo, fun, opts \\ []) 应该为你做这件事 https://hexdocs.pm/ecto_sql/Ecto.Migrator.html#with_repo/3

    【讨论】:

      猜你喜欢
      • 2020-03-16
      • 1970-01-01
      • 2017-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-21
      相关资源
      最近更新 更多