ConnectionHandler is a collection of ConnectionPool objects. It is used for keeping separate connection pools that connect to different databases.

For example, suppose that you have 5 models, with the following hierarchy:

class Author < ActiveRecord::Base
end

class BankAccount < ActiveRecord::Base
end

class Book < ActiveRecord::Base
  establish_connection :library_db
end

class ScaryBook < Book
end

class GoodBook < Book
end

And a database.yml that looked like this:

development:
  database: my_application
  host: localhost

library_db:
  database: library
  host: some.library.org

Your primary database in the development environment is “my_application” but the Book model connects to a separate database called “library_db” (this can even be a database on a different machine).

Book, ScaryBook and GoodBook will all use the same connection pool to “library_db” while Author, BankAccount, and any other models you create will use the default connection pool to “my_application”.

The various connection pools are managed by a single instance of ConnectionHandler accessible via ActiveRecord::Base.connection_handler. All Active Record models use this handler to determine the connection pool that they should use.

The ConnectionHandler class is not coupled with the Active models, as it has no knowledge about the model. The model needs to pass a specification name to the handler, in order to look up the correct connection pool.

Methods

Class Public methods

new()

📝 Source code
# File activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb, line 959
      def initialize
        # These caches are keyed by spec.name (ConnectionSpecification#name).
        @owner_to_pool = ConnectionHandler.create_owner_to_pool

        # Backup finalizer: if the forked child never needed a pool, the above
        # early discard has not occurred
        ObjectSpace.define_finalizer self, ConnectionHandler.unowned_pool_finalizer(@owner_to_pool)
      end
🔎 See on GitHub

Instance Public methods

active_connections?()

Returns true if there are any active connections among the connection pools that the ConnectionHandler is managing.

📝 Source code
# File activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb, line 997
      def active_connections?
        connection_pool_list.any?(&:active_connection?)
      end
🔎 See on GitHub

clear_active_connections!()

Returns any connections in use by the current thread back to the pool, and also returns connections to the pool cached by threads that are no longer alive.

📝 Source code
# File activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb, line 1004
      def clear_active_connections!
        connection_pool_list.each(&:release_connection)
      end
🔎 See on GitHub

clear_all_connections!()

📝 Source code
# File activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb, line 1015
      def clear_all_connections!
        connection_pool_list.each(&:disconnect!)
      end
🔎 See on GitHub

clear_reloadable_connections!()

Clears the cache which maps classes.

See ConnectionPool#clear_reloadable_connections! for details.

📝 Source code
# File activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb, line 1011
      def clear_reloadable_connections!
        connection_pool_list.each(&:clear_reloadable_connections!)
      end
🔎 See on GitHub

connected?(spec_name)

Returns true if a connection that's accessible to this class has already been opened.

📝 Source code
# File activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb, line 1038
      def connected?(spec_name)
        conn = retrieve_connection_pool(spec_name)
        conn && conn.connected?
      end
🔎 See on GitHub

connection_pool_list()

Also aliased as: connection_pools
📝 Source code
# File activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb, line 968
      def connection_pool_list
        owner_to_pool.values.compact
      end
🔎 See on GitHub

connection_pools()

establish_connection(config)

📝 Source code
# File activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb, line 973
      def establish_connection(config)
        resolver = ConnectionSpecification::Resolver.new(Base.configurations)
        spec = resolver.spec(config)

        remove_connection(spec.name)

        message_bus = ActiveSupport::Notifications.instrumenter
        payload = {
          connection_id: object_id
        }
        if spec
          payload[:spec_name] = spec.name
          payload[:config] = spec.config
        end

        message_bus.instrument("!connection.active_record", payload) do
          owner_to_pool[spec.name] = ConnectionAdapters::ConnectionPool.new(spec)
        end

        owner_to_pool[spec.name]
      end
🔎 See on GitHub

flush_idle_connections!()

Disconnects all currently idle connections.

See ConnectionPool#flush! for details.

📝 Source code
# File activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb, line 1022
      def flush_idle_connections!
        connection_pool_list.each(&:flush!)
      end
🔎 See on GitHub

remove_connection(spec_name)

Remove the connection for this class. This will close the active connection and the defined connection (if they exist). The result can be used as an argument for establish_connection, for easily re-establishing the connection.

📝 Source code
# File activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb, line 1047
      def remove_connection(spec_name)
        if pool = owner_to_pool.delete(spec_name)
          pool.automatic_reconnect = false
          pool.disconnect!
          pool.spec.config
        end
      end
🔎 See on GitHub

retrieve_connection_pool(spec_name)

Retrieving the connection pool happens a lot, so we cache it in @owner_to_pool. This makes retrieving the connection pool O(1) once the process is warm. When a connection is established or removed, we invalidate the cache.

📝 Source code
# File activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb, line 1058
      def retrieve_connection_pool(spec_name)
        owner_to_pool.fetch(spec_name) do
          # Check if a connection was previously established in an ancestor process,
          # which may have been forked.
          if ancestor_pool = pool_from_any_process_for(spec_name)
            # 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.
            establish_connection(ancestor_pool.spec.to_hash).tap do |pool|
              pool.schema_cache = ancestor_pool.schema_cache if ancestor_pool.schema_cache
            end
          else
            owner_to_pool[spec_name] = nil
          end
        end
      end
🔎 See on GitHub