Implement ActiveRecord.disconnect_all! to close all connections

This is basically a multi-db aware version of `ActiveRecord::Base.connection.disconnect!`.
It also avoid connecting to the database if we weren't already.

This can be useful to reset state after `establish_connection` has been used.
This commit is contained in:
Jean Boussier 2023-04-04 15:24:34 +02:00
parent 43fa801967
commit f1b15971a5
3 changed files with 13 additions and 0 deletions

@ -1,3 +1,7 @@
* Add `ActiveRecord.disconnect_all!` method to immediately close all connections from all pools.
*Jean Boussier*
* Discard connections which may have been left in a transaction.
There are cases where, due to an error, `within_new_transaction` may unexpectedly leave a connection in an open transaction. In these cases the connection may be reused, and the following may occur:

@ -457,6 +457,11 @@ def self.eager_load!
ActiveRecord::ConnectionAdapters.eager_load!
ActiveRecord::Encryption.eager_load!
end
# Explicitly closes all database connections in all pools.
def self.disconnect_all!
ConnectionAdapters::PoolConfig.disconnect_all!
end
end
ActiveSupport.on_load(:active_record) do

@ -15,6 +15,10 @@ class << self
def discard_pools!
INSTANCES.each_key(&:discard_pool!)
end
def disconnect_all!
INSTANCES.each_key(&:disconnect!)
end
end
def initialize(connection_class, db_config, role, shard)