Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What causes ActiveRecord breaking Postgres connection after forking?

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?

like image 753
Koraktor Avatar asked Jan 11 '15 22:01

Koraktor


1 Answers

After the child processes finish their work you can re-establish a connection to the DB with ActiveRecord::Base.establish_connection. Afterwards your Rake process should be able to access the DB as usual.

like image 116
Chris Avatar answered Nov 19 '22 00:11

Chris