Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres disconnect when running query inside spawned process?

Tags:

elixir

ecto

I have a function that spawns a process, which performs a query like so:

  def trigger_schedule(u = %User{}) do
    spawn(fn ->
      (Repo.preload(p, :tasks)).tasks
      |> Enum.map(fn ts -> trigger_schedule(ts) end)
    end)
    u
  end

This code is triggered by certain actions, and is simply meant to run in the background. However, when I run tests, I start seeing this:

00:37:33.324 [error] Postgrex.Protocol (#PID<0.789.0>) disconnected: ** (DBConnection.ConnectionError) owner #PID<0.1531.0> exited while client #PID<0.1533.0> is still running with: shutdown

Is performing queries inside of a spaned function not proper, or is there a way to get around this error? I assume this has something to do with the PG connection pool...

like image 249
o_o_o-- Avatar asked Nov 09 '22 06:11

o_o_o--


1 Answers

You're getting this error because of the Ecto 2.0 Connection Ownership feature. The problem is that the process owning the connection (that is the test process) exits before the process running the query (in spawn).

I guess you're running your tests asynchronously. If you're using Phoenix and ModelCase you probably have :ok = Ecto.Adapters.SQL.Sandbox.checkout(YourApp.Repo). The simplest solution is not to use async: true in your tests.

You could also try to manually allow another process to access the db with Ecto.Adapters.SQL.Sandbox.allow(Repo, self(), process_pid) but you have to know the pid of the process, which I'm not sure is possible since your trigger_schedule function returns the user, not the pid.

like image 146
Maciej Kaszubowski Avatar answered Nov 15 '22 09:11

Maciej Kaszubowski