Using mysql in addition of postgres

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 ?


1 Like

It is quite straight-forward if you just want a connection.

  1. Add MyXQL to your 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

In lib/yourapp/application.ex: Add YourApp.OtherRepo to the supervisor children:

children = [
   # Start the Ecto repository
   # Start MySQL repo

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: 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.


I will try that :slight_smile:

1 Like

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.

Here is the line in question where the config is used (it’s a helper file which gets imported by the aforementioned tasks).