2022-02-19 10:18:05 +01:00
|
|
|
defmodule HAHandler.PGSQL.Watcher do
|
2022-02-23 17:53:00 +01:00
|
|
|
use GenServer
|
|
|
|
require Logger
|
2022-02-19 10:18:05 +01:00
|
|
|
|
2022-02-23 17:53:00 +01:00
|
|
|
def start_link(opts) do
|
|
|
|
GenServer.start_link(__MODULE__, opts)
|
|
|
|
end
|
2022-02-19 10:18:05 +01:00
|
|
|
|
2022-02-23 17:53:00 +01:00
|
|
|
@impl true
|
|
|
|
def init(opts) do
|
|
|
|
# Starts a Postgrex child but does not means the connection was
|
|
|
|
# successful.
|
|
|
|
# TODO: set dbconnections backoff and connect hooks
|
|
|
|
# See https://github.com/elixir-ecto/db_connection/blob/master/lib/db_connection.ex#L343
|
2022-06-13 18:49:55 +02:00
|
|
|
case Postgrex.start_link(opts) do
|
|
|
|
{:ok, pid} ->
|
|
|
|
state = %{
|
|
|
|
backend: pid,
|
|
|
|
hostname: Keyword.get(opts, :hostname)
|
|
|
|
}
|
2022-02-19 10:18:05 +01:00
|
|
|
|
2022-06-13 18:49:55 +02:00
|
|
|
{:ok, state}
|
|
|
|
{:error, err} ->
|
|
|
|
# Will be catched by the supervisor if anything happen. It should not
|
|
|
|
# be triggered even if a PGSQL node down, since Postgrex has its own
|
|
|
|
# surpervision tree.
|
|
|
|
{:error, err}
|
2022-06-13 21:08:20 +02:00
|
|
|
end
|
2022-02-23 17:53:00 +01:00
|
|
|
end
|
2022-02-19 10:18:05 +01:00
|
|
|
|
2022-02-23 17:53:00 +01:00
|
|
|
@impl true
|
|
|
|
def handle_call({:execute, query, params}, _from, %{backend: backend} = state) do
|
|
|
|
{:reply, Postgrex.query(backend, query, params), state}
|
|
|
|
end
|
2022-02-19 10:18:05 +01:00
|
|
|
end
|