class ActiveRecord::ConnectionAdapters::ConnectionHandler

Experimental RBS support (using type sampling data from the type_fusion project).

# sig/active_record/connection_adapters/abstract/connection_handler.rbs

class ActiveRecord::ConnectionAdapters::ConnectionHandler
  def get_pool_manager: (String owner) -> ActiveRecord::ConnectionAdapters::PoolManager
  def retrieve_connection: (String spec_name, role: Symbol, shard: Symbol) -> ActiveRecord::ConnectionAdapters::PostgreSQLAdapter
  def retrieve_connection_pool: (String owner, role: Symbol, shard: Symbol) -> untyped
end

in order to look up the correct connection pool.
about the model. The model needs to pass a connection specification name to the handler,
The ConnectionHandler class is not coupled with the Active models, as it has no knowledge
should use.
All Active Record models use this handler to determine the connection pool that they
ConnectionHandler accessible via ActiveRecord::Base.connection_handler.
The various connection pools are managed by a single instance of
will use the default connection pool to “my_application”.
“library_db” while Author, BankAccount, and any other models you create
Book, ScaryBook, and GoodBook will all use the same connection pool to
(this can even be a database on a different machine).
but the Book model connects to a separate database called “library_db”
Your primary database in the development environment is “my_application”
host: some.library.org
database: library
library_db:
host: localhost
database: my_application
development:
And a database.yml that looked like this:
end
class GoodBook < Book
end
class ScaryBook < Book
end
establish_connection :library_db
class Book < ActiveRecord::Base
end
class BankAccount < ActiveRecord::Base
end
class Author < ActiveRecord::Base
For example, suppose that you have 5 models, with the following hierarchy:
for keeping separate connection pools that connect to different databases.
ConnectionHandler is a collection of ConnectionPool objects. It is used

def active_connections?(role = ActiveRecord::Base.current_role)

pools that the ConnectionHandler is managing.
Returns true if there are any active connections among the connection
def active_connections?(role = ActiveRecord::Base.current_role)
  connection_pool_list(role).any?(&:active_connection?)
end

def all_connection_pools

def all_connection_pools
  owner_to_pool_manager.values.flat_map { |m| m.pool_configs.map(&:pool) }
end

def clear_active_connections!(role = ActiveRecord::Base.current_role)

longer alive.
and also returns connections to the pool cached by threads that are no
Returns any connections in use by the current thread back to the pool,
def clear_active_connections!(role = ActiveRecord::Base.current_role)
  connection_pool_list(role).each(&:release_connection)
end

def clear_all_connections!(role = ActiveRecord::Base.current_role)

def clear_all_connections!(role = ActiveRecord::Base.current_role)
  connection_pool_list(role).each(&:disconnect!)
end

def clear_reloadable_connections!(role = ActiveRecord::Base.current_role)

See ConnectionPool#clear_reloadable_connections! for details.

Clears the cache which maps classes.
def clear_reloadable_connections!(role = ActiveRecord::Base.current_role)
  connection_pool_list(role).each(&:clear_reloadable_connections!)
end

def connected?(spec_name, role: ActiveRecord::Base.current_role, shard: ActiveRecord::Base.current_shard)

already been opened.
Returns true if a connection that's accessible to this class has
def connected?(spec_name, role: ActiveRecord::Base.current_role, shard: ActiveRecord::Base.current_shard)
  pool = retrieve_connection_pool(spec_name, role: role, shard: shard)
  pool && pool.connected?
end

def connection_pool_list(role = ActiveRecord::Base.current_role)

def connection_pool_list(role = ActiveRecord::Base.current_role)
  owner_to_pool_manager.values.flat_map { |m| m.pool_configs(role).map(&:pool) }
end

def connection_pool_names # :nodoc:

:nodoc:
def connection_pool_names # :nodoc:
  owner_to_pool_manager.keys
end

def establish_connection(config, owner_name: Base, role: ActiveRecord::Base.current_role, shard: Base.current_shard)

def establish_connection(config, owner_name: Base, role: ActiveRecord::Base.current_role, shard: Base.current_shard)
  owner_name = StringConnectionOwner.new(config.to_s) if config.is_a?(Symbol)
  pool_config = resolve_pool_config(config, owner_name, role, shard)
  db_config = pool_config.db_config
  # Protects the connection named `ActiveRecord::Base` from being removed
  # if the user calls `establish_connection :primary`.
  if owner_to_pool_manager.key?(pool_config.connection_specification_name)
    remove_connection_pool(pool_config.connection_specification_name, role: role, shard: shard)
  end
  message_bus = ActiveSupport::Notifications.instrumenter
  payload = {}
  if pool_config
    payload[:spec_name] = pool_config.connection_specification_name
    payload[:shard] = shard
    payload[:config] = db_config.configuration_hash
  end
  if ActiveRecord.legacy_connection_handling
    owner_to_pool_manager[pool_config.connection_specification_name] ||= LegacyPoolManager.new
  else
    owner_to_pool_manager[pool_config.connection_specification_name] ||= PoolManager.new
  end
  pool_manager = get_pool_manager(pool_config.connection_specification_name)
  pool_manager.set_pool_config(role, shard, pool_config)
  message_bus.instrument("!connection.active_record", payload) do
    pool_config.pool
  end
end

def flush_idle_connections!(role = ActiveRecord::Base.current_role)

See ConnectionPool#flush! for details.

Disconnects all currently idle connections.
def flush_idle_connections!(role = ActiveRecord::Base.current_role)
  connection_pool_list(role).each(&:flush!)
end

def get_pool_manager(owner)

Experimental RBS support (using type sampling data from the type_fusion project).

def get_pool_manager: (String owner) -> ActiveRecord::ConnectionAdapters::PoolManager

This signature was generated using 4 samples from 1 application.

Returns the pool manager for an owner.
def get_pool_manager(owner)
  owner_to_pool_manager[owner]
end

def initialize

def initialize
  # These caches are keyed by pool_config.connection_specification_name (PoolConfig#connection_specification_name).
  @owner_to_pool_manager = Concurrent::Map.new(initial_capacity: 2)
  # Backup finalizer: if the forked child skipped Kernel#fork the early discard has not occurred
  ObjectSpace.define_finalizer self, FINALIZER
end

def prevent_writes # :nodoc:

:nodoc:
def prevent_writes # :nodoc:
  ActiveSupport::IsolatedExecutionState[:active_record_prevent_writes]
end

def prevent_writes=(prevent_writes) # :nodoc:

:nodoc:
def prevent_writes=(prevent_writes) # :nodoc:
  ActiveSupport::IsolatedExecutionState[:active_record_prevent_writes] = prevent_writes
end

def remove_connection_pool(owner, role: ActiveRecord::Base.current_role, shard: ActiveRecord::Base.current_shard)

def remove_connection_pool(owner, role: ActiveRecord::Base.current_role, shard: ActiveRecord::Base.current_shard)
  if pool_manager = get_pool_manager(owner)
    pool_config = pool_manager.remove_pool_config(role, shard)
    if pool_config
      pool_config.disconnect!
      pool_config.db_config
    end
  end
end

def resolve_pool_config(config, owner_name, role, shard)


# => { host: "localhost", database: "foo", adapter: "sqlite3" }
pool_config.db_config.configuration_hash
pool_config = Base.configurations.resolve_pool_config(:production)
config = { "production" => { "host" => "localhost", "database" => "foo", "adapter" => "sqlite3" } }

== Example

Accepts a hash one layer deep that contains all connection information.
Returns an instance of PoolConfig for a given adapter.
def resolve_pool_config(config, owner_name, role, shard)
  db_config = Base.configurations.resolve(config)
  raise(AdapterNotSpecified, "database configuration does not specify adapter") unless db_config.adapter
  # Require the adapter itself and give useful feedback about
  #   1. Missing adapter gems and
  #   2. Adapter gems' missing dependencies.
  path_to_adapter = "active_record/connection_adapters/#{db_config.adapter}_adapter"
  begin
    require path_to_adapter
  rescue LoadError => e
    # We couldn't require the adapter itself. Raise an exception that
    # points out config typos and missing gems.
    if e.path == path_to_adapter
      # We can assume that a non-builtin adapter was specified, so it's
      # either misspelled or missing from Gemfile.
      raise LoadError, "Could not load the '#{db_config.adapter}' Active Record adapter. Ensure that the adapter is spelled correctly in config/database.yml and that you've added the necessary adapter gem to your Gemfile.", e.backtrace
      # Bubbled up from the adapter require. Prefix the exception message
      # with some guidance about how to address it and reraise.
    else
      raise LoadError, "Error loading the '#{db_config.adapter}' Active Record adapter. Missing a gem it depends on? #{e.message}", e.backtrace
    end
  end
  unless ActiveRecord::Base.respond_to?(db_config.adapter_method)
    raise AdapterNotFound, "database configuration specifies nonexistent #{db_config.adapter} adapter"
  end
  ConnectionAdapters::PoolConfig.new(owner_name, db_config, role, shard)
end

def retrieve_connection(spec_name, role: ActiveRecord::Base.current_role, shard: ActiveRecord::Base.current_shard) # :nodoc:

Experimental RBS support (using type sampling data from the type_fusion project).

def retrieve_connection: (String spec_name, role: Symbol, shard: Symbol) -> ActiveRecord::ConnectionAdapters::PostgreSQLAdapter

This signature was generated using 9 samples from 1 application.

:nodoc:
for (not necessarily the current class).
opened and set as the active connection for the class it was defined
active or defined connection: if it is the latter, it will be
Locate the connection of the nearest super class. This can be an
def retrieve_connection(spec_name, role: ActiveRecord::Base.current_role, shard: ActiveRecord::Base.current_shard) # :nodoc:
  pool = retrieve_connection_pool(spec_name, role: role, shard: shard)
  unless pool
    if shard != ActiveRecord::Base.default_shard
      message = "No connection pool for '#{spec_name}' found for the '#{shard}' shard."
    elsif ActiveRecord::Base.connection_handler != ActiveRecord::Base.default_connection_handler
      message = "No connection pool for '#{spec_name}' found for the '#{ActiveRecord::Base.current_role}' role."
    elsif role != ActiveRecord::Base.default_role
      message = "No connection pool for '#{spec_name}' found for the '#{role}' role."
    else
      message = "No connection pool for '#{spec_name}' found."
    end
    raise ConnectionNotEstablished, message
  end
  pool.connection
end

def retrieve_connection_pool(owner, role: ActiveRecord::Base.current_role, shard: ActiveRecord::Base.current_shard)

Experimental RBS support (using type sampling data from the type_fusion project).

def retrieve_connection_pool: (String owner, role: Symbol, shard: Symbol) -> untyped

This signature was generated using 3 samples from 1 application.

When a connection is established or removed, we invalidate the cache.
This makes retrieving the connection pool O(1) once the process is warm.
Retrieving the connection pool happens a lot, so we cache it in @owner_to_pool_manager.
def retrieve_connection_pool(owner, role: ActiveRecord::Base.current_role, shard: ActiveRecord::Base.current_shard)
  pool_config = get_pool_manager(owner)&.get_pool_config(role, shard)
  pool_config&.pool
end

def while_preventing_writes(enabled = true)

method.
See +READ_QUERY+ for the queries that are blocked by this

user and is meant to be a safeguard against accidental writes.
This method does not provide the same protection as a readonly

will prevent writes to the database for the duration of the block.
even if you are on a database that can write. +while_preventing_writes+
In some cases you may want to prevent writes to the database

Prevent writing to the database regardless of role.
def while_preventing_writes(enabled = true)
  unless ActiveRecord.legacy_connection_handling
    raise NotImplementedError, "`while_preventing_writes` is only available on the connection_handler with legacy_connection_handling"
  end
  original, self.prevent_writes = self.prevent_writes, enabled
  yield
ensure
  self.prevent_writes = original
end