Dynamic database connections with Phoenix?

I’m not sure about Ecto, but it’s pretty straightforward to access Postgres directly using Postgrex:

    opts = [hostname: "blah", database: "blah_db", username: "postgres" password: "secure_az"]
    with {:ok, conn} <- Postgrex.start_link(opts),
        {:ok, result} <- Postgrex.query(conn, sql, [])
    do
      IO.inspect "Got #{inspect(result.num_rows)} rows from #{inspect(sql)}"
      IO.inspect result.columns
      IO.inspect result.rows

      GenServer.stop(conn)

      rows
    else
      {:error, err} ->
        IO.inspect err, label: ~s|Reading from db with sql #{inspect(sql)}|
        []
    end

Of course, if you’re hitting up the database directly, you have to worry about escaping etc.

There’s a thread here that may help harness Ecto: Concurrent access to several Ecto Dynamic Repositories

1 Like