I am using Elixir for my application and I need to read data from external mysql database.
I still need my postgres database as my main DB
How do I open a new connection to mysql db ?
Thanks
I am using Elixir for my application and I need to read data from external mysql database.
I still need my postgres database as my main DB
How do I open a new connection to mysql db ?
Thanks
It is quite straight-forward if you just want a connection.
mix.exs
defp deps do
[
...
{:myxql, ">= 0.0.0"}
]
...
In lib/yourapp/repo.ex
add another module:
defmodule YourApp.OtherRepo do
use Ecto.Repo,
otp_app: :yourapp,
adapter: Ecto.Adapters.MyXQL
end
In lib/yourapp/application.ex
: Add YourApp.OtherRepo to the supervisor children:
children = [
# Start the Ecto repository
YourApp.Repo,
# Start MySQL repo
YourApp.OtherRepo
...
]
And finally in your config files add your MySQL configuration. For example in config/dev.exs
config :yourapp, YourApp.OtherRepo,
username: "...",
password: "...",
hostname: "...",
database: "...",
pool_size: 10
Now you should be able to access MySQL through your repo:
$> iex -S mix
iex(1)> YourApp.OtherRepo.query("SELECT count(*) FROM sometable")
I think they also need to add this in config/config.exs
:
config :yourapp,
ecto_repos: [YourApp.Repo, YourApp.OtherRepo]
Documented inside this sub-section: https://hexdocs.pm/ecto/getting-started.html#adding-ecto-to-an-application. But I was never sure if that was mandatory and the docs don’t really explain if it’s necessary if you have several repos.
Thanks.
I will try that
Yeah, that is the way to go.
I’ve checked the ecto codebase because I was curious and the config:
config :yourapp,
ecto_repos: [YourApp.Repo, YourApp.OtherRepo]
Is exclusively used by the ecto mix tasks - such as mix ecto.create
or mix ecto.drop
- to get the repositories on which they should operate on.