What causes ActiveRecord to break Postgres connection after forking?

I have a Rake task in a Rails 4.2 project that uses fork . My problem is that after the split process is complete (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 that ActiveRecord automatically closes the connection after the forked process completes. But after reading the AR connection_pool.rb code, it seems like forked processes should use their own connections:

The connection was established in the process of the ancestor, which should subsequently be bifurcated. We cannot reuse the connection, but we can copy the specifications and establish a new connection to it.

(from ActiveRecord::ConnectionAdapters::ConnectionHandler#pool_for_owner )

However, forking makes the connection useless.

I tried to prevent the forked database access process and make sure that 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?

+6
source share
1 answer

After completing the child processes, you can reconnect to the database using ActiveRecord::Base.establish_connection . Subsequently, your Rake process should have access to the database, as usual.

+1
source

Source: https://habr.com/ru/post/980846/


All Articles