petspanda D
petspanda D

Reputation: 171

Connect to multiple database elixir

In Rails , we can connect to multiple database on fly as,

ActiveRecord::Base.establish_connection(
  database: "db_name", username: "postgres")

But in Elixir - Phoenix framework, how to do the same process.

Upvotes: 1

Views: 1493

Answers (2)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

For the raw connection one needs to use the lower abstraction level than Ecto provides on top. Ecto code is the good source to take an inspiration from. Basically, for MySQL database something like this should do:

with {:ok, conn} <- Mariaex.start_link(opts) do
  value = Ecto.Adapters.MySQL.Connection.execute(conn, sql, [], opts)
  GenServer.stop(conn)
  value
end

where opts is a keyword list with database, username etc keys. The example of how to maintain a connection pool might be stolen from one of Ecto adapters source code as well.

Upvotes: 0

Zubair Nabi
Zubair Nabi

Reputation: 1046

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 Supervise the Repos.

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

and finally 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

example

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

Upvotes: 1

Related Questions