How to ensure unicorn disconnects ALL DB connections in rails 6.1?

205 views Asked by At

In unicorn.rb it's common to have clauses like this:

before_fork do |server, worker|
  # Disconnect since the database connection will not carry over
  if defined? ActiveRecord::Base
    ActiveRecord::Base.clear_all_connections!
  end
end

To ensure db connections are closed when reloading the app. Since the introduction of "roles" and "shards" in Rails I am unsure how I would make sure that ALL connections/pools are disconnected, not only the "current role" one?

1

There are 1 answers

0
Niels Kristian On BEST ANSWER

Ok, so I think I found it...

before_fork do |server, worker|
  # Disconnect since the database connection will not carry over
  if defined? ActiveRecord::Base
    ActiveRecord::Base.connection_handlers.each do |role, handler|
      Rails.logger.info("Clearing/closing all connections for #{role} role...")
      handler.clear_all_connections!
    end
  end
end