在Rails中,我们可以在飞行中连接到多个数据库,
ActiveRecord::Base.establish_connection(
database: "db_name", username: "postgres")
但是在Elixir - Phoenix框架中,如何做同样的过程。
答案 0 :(得分:1)
use Mix.Config
config :my_app, MyApp.OneRepo,
adapter: Ecto.Adapters.MySQL,
database: "legacy_db",
username: "username",
password: "password",
hostname: "something.com"
config :my_app, MyApp.TwoRepo,
adapter: Ecto.Adapters.Postgres,
username: "username",
password: "password",
database: "some_db_two",
hostname: "example.com"
config :my_app, ecto_repos: [MyApp.OneRepo, MyApp.TwoRepo]
LIB / my_app.ex 监督回购。
defmodule Databases do
use Application
def start(_type, _args) do
import Supervisor.Spec, warn: false
children = [
supervisor(MyApp.OneRepo, []), # <-- our addition
supervisor(MyApp.TwoRepo, []) # <-- our addition
]
opts = [strategy: :one_for_one, name: MyApp.Supervisor]
Supervisor.start_link(children, opts)
end
end
最后 LIB / repos.ex
defmodule MyApp.OneRepo do
use Ecto.Repo, otp_app: :my_app
end
defmodule MyApp.TwoRepo do
use Ecto.Repo, otp_app: :my_app
end
例如
iex> import Ecto.Query
iex> some_table= MyApp.OneRepo.get_by(SomeTable, %{username: "Alpha"})
iex> other_table= MyApp.TwoRepo.all from ot in OtherTable,
where: ot.user_id == ^user.id
答案 1 :(得分:0)
对于原始连接,需要使用比Ecto
提供的更低的抽象级别。 Ecto
代码是good source to take an inspiration from。基本上,对于MySQL
数据库,应该这样做:
with {:ok, conn} <- Mariaex.start_link(opts) do
value = Ecto.Adapters.MySQL.Connection.execute(conn, sql, [], opts)
GenServer.stop(conn)
value
end
其中opts
是包含database
,username
等密钥的关键字列表。如何维护连接池的示例也可能从Ecto
适配器源代码中被盗。