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...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With