4

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.

Afshin Moazami
  • 2,092
  • 5
  • 33
  • 55
Jesse Shieh
  • 4,660
  • 5
  • 34
  • 49

1 Answers1

9

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
Dogbert
  • 212,659
  • 41
  • 396
  • 397
  • 2
    Thanks! Is there any danger of relying on implementation details of postgrex this way? – Jesse Shieh Jun 22 '17 at 15:19
  • Based on the doc, it uses a `DBConnection` which itself uses a `GenServer`. So it is safe to say that the doc implies that it uses a `GenServer` and thus renders the usage of the `GenServer.stop/1` call safe. – Ludovic Kuty Apr 15 '21 at 09:54