Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement ActiveRecord.disconnect_all! to close all connections #47856

Merged
merged 1 commit into from
May 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 4 additions & 0 deletions activerecord/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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:
Expand Down
5 changes: 5 additions & 0 deletions activerecord/lib/active_record.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My concern with this being ActiveRecord.disconnect! defined at the top level is the API is confusing. Disconnect what? Whereas ActiveRecord.connection.disconnect! is clearly disconnecting the connection. I think this should be in the connection handler like: ActiveRecord::Base.connection_handler.disconnect!. What do you think?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Whereas ActiveRecord.connection.disconnect! is clearly disconnecting the connection.

Yeah, but it's also connecting first if you weren't already, which is annoyinh.

What do you think?

What about disconnect_all!? The usage is really to ask AR to close all its connections ActiveRecord::Base.connection_handler.disconnect! is much less clear whether it will close other pools etc.

end

ActiveSupport.on_load(:active_record) do
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down