Postgrex in genserver

Hi there!

I created a genserver that will run scheduled queries in postgrex. I need to use postgrex instead of because I’m using an older version of postgres 8. I started the postgrex in init of my genserver. it looks odd so thought if there is a better way of doing it. :confused:

  # called by genserver start link
  def init(_state) do
    schedule_work() # Schedule work to be performed on start
    Postgrex.start_link(...) # returns :ok, pid? instead of {:ok, state}


Is it normal to pass the pid in the genserver state?

If the operating state of your GenServer depends on Postgrex running then its appropriate to start it in init. I’d probably make a couple of small changes, vis:

  # Pass the Postgrex config options in via GenServer.start_link
  def init(postgrex_config) do
    case Postgrex.start_link(postgrex_config) do
      {:ok, pid} -> 
        # Give the state some shape for easier pattern matching later on
        {:ok, %{postgrex: pid}}
      {:error, reason} ->
        # Don't continue with the GenServer because Postgrex couldn't be started
        # Of course that might not be your preferred intent if you're
        # depending on a Supervisor to restart
        {:stop, reason}

Thanks! :slight_smile: I wasnt sure if I should use that or start the process in the supervisor then use Process.whereis() to look it up from the genserver.

Thanks so much =)