postgresqlelixirphoenix-frameworkectopostgrex

How to disconnect Postgrex connection?


I'm trying to figure out how to connect to a postgres database, run a query, and then disconnect.

Looking at Postgrex, I establish a connection using

{:ok, pid} = Postgrex.start_link(hostname: "localhost", username: "postgres", password: "postgres", database: "postgres")

Then I execute my query using

Postgrex.query!(pid, "SELECT user_id, text FROM comments", [])

But then, how do I disconnect?

I'd like to disconnect because I am looping through N databases and running the same query on all of them.

I tried exiting the Process e.g. Process.exit(pid, :bye), but it kills the spawning process also because it's started with start_link/3. I can't find a start/3 function in Postgrex.


Solution

  • As the pid returned by Postgrex.start_link is a GenServer, you can use GenServer.stop/1:

    iex(1)> {:ok, pid} = Postgrex.start_link(hostname: "localhost", username: "postgres", password: "postgres", database: "postgres")
    {:ok, #PID<0.277.0>}
    iex(2)> GenServer.stop(pid)                                                                                                 
    :ok
    iex(3)> GenServer.stop(pid)
    ** (exit) no process: the process is not alive or there's no process currently associated with the given name, possibly because its application isn't started
        (stdlib) proc_lib.erl:797: :proc_lib.stop/3