I have a Rake task in a Rails 4.2 project that uses fork
. My problem is that after the forked process has finished (i.e. after Process.wait
) I get the following Postgres error when I try to access the database again:
PG::ConnectionBad: PQconsumeInput() server closed the connection unexpectedly
At first I suspected ActiveRecord to automatically close the connection once the forked process finishes. But after reading the code of AR's connection_pool.rb
it seems that forked processes should use their own connections:
A connection was established in an ancestor process that must have subsequently forked. We can't reuse the connection, but we can copy the specification and establish a new connection with it.
(from ActiveRecord::ConnectionAdapters::ConnectionHandler#pool_for_owner
)
Nevertheless, forking renders the connection useless.
I tried to prevent the forked process from accessing the database at all and verified that the old connections cannot be reused with the following code after forking:
ActiveRecord::Base.default_connection_handler = nil
ActiveRecord::Base.connection_handler = nil
Any suggestions on how to solve this?