Class: ActiveRecord::ConnectionAdapters::ConnectionHandler

Inherits:
Object
  • Object
show all
Defined in:
lib/active_record/connection_adapters/abstract/connection_pool.rb

Overview

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 connection specification name to the handler, in order to look up the correct connection pool.

Instance Method Summary collapse

Constructor Details

#initializeConnectionHandler

Returns a new instance of ConnectionHandler.



992
993
994
995
996
997
998
# File 'lib/active_record/connection_adapters/abstract/connection_pool.rb', line 992

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

Instance Method Details

#active_connections?(role = ActiveRecord::Base.current_role) ⇒ Boolean

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

Returns:

  • (Boolean)


1078
1079
1080
# File 'lib/active_record/connection_adapters/abstract/connection_pool.rb', line 1078

def active_connections?(role = ActiveRecord::Base.current_role)
  connection_pool_list(role).any?(&:active_connection?)
end

#all_connection_poolsObject



1034
1035
1036
# File 'lib/active_record/connection_adapters/abstract/connection_pool.rb', line 1034

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

#clear_active_connections!(role = ActiveRecord::Base.current_role) ⇒ Object

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.



1085
1086
1087
# File 'lib/active_record/connection_adapters/abstract/connection_pool.rb', line 1085

def clear_active_connections!(role = ActiveRecord::Base.current_role)
  connection_pool_list(role).each(&:release_connection)
end

#clear_all_connections!(role = ActiveRecord::Base.current_role) ⇒ Object



1096
1097
1098
# File 'lib/active_record/connection_adapters/abstract/connection_pool.rb', line 1096

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

#clear_reloadable_connections!(role = ActiveRecord::Base.current_role) ⇒ Object

Clears the cache which maps classes.

See ConnectionPool#clear_reloadable_connections! for details.



1092
1093
1094
# File 'lib/active_record/connection_adapters/abstract/connection_pool.rb', line 1092

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

#connected?(spec_name, role: ActiveRecord::Base.current_role, shard: ActiveRecord::Base.current_shard) ⇒ Boolean

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

Returns:

  • (Boolean)


1133
1134
1135
1136
# File 'lib/active_record/connection_adapters/abstract/connection_pool.rb', line 1133

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

#connection_pool_list(role = ActiveRecord::Base.current_role) ⇒ Object Also known as: connection_pools



1038
1039
1040
# File 'lib/active_record/connection_adapters/abstract/connection_pool.rb', line 1038

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

#connection_pool_namesObject

:nodoc:



1030
1031
1032
# File 'lib/active_record/connection_adapters/abstract/connection_pool.rb', line 1030

def connection_pool_names # :nodoc:
  owner_to_pool_manager.keys
end

#establish_connection(config, owner_name: Base, role: ActiveRecord::Base.current_role, shard: Base.current_shard) ⇒ Object



1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
# File 'lib/active_record/connection_adapters/abstract/connection_pool.rb', line 1043

def establish_connection(config, owner_name: Base, role: ActiveRecord::Base.current_role, shard: Base.current_shard)
  owner_name = config.to_s if config.is_a?(Symbol)

  pool_config = resolve_pool_config(config, owner_name)
  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::Base.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

#flush_idle_connections!(role = ActiveRecord::Base.current_role) ⇒ Object

Disconnects all currently idle connections.

See ConnectionPool#flush! for details.



1103
1104
1105
# File 'lib/active_record/connection_adapters/abstract/connection_pool.rb', line 1103

def flush_idle_connections!(role = ActiveRecord::Base.current_role)
  connection_pool_list(role).each(&:flush!)
end

#prevent_writesObject

:nodoc:



1000
1001
1002
# File 'lib/active_record/connection_adapters/abstract/connection_pool.rb', line 1000

def prevent_writes # :nodoc:
  Thread.current[:prevent_writes]
end

#prevent_writes=(prevent_writes) ⇒ Object

:nodoc:



1004
1005
1006
# File 'lib/active_record/connection_adapters/abstract/connection_pool.rb', line 1004

def prevent_writes=(prevent_writes) # :nodoc:
  Thread.current[:prevent_writes] = prevent_writes
end

#remove_connection(owner, role: ActiveRecord::Base.current_role, shard: ActiveRecord::Base.current_shard) ⇒ Object

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.



1142
1143
1144
# File 'lib/active_record/connection_adapters/abstract/connection_pool.rb', line 1142

def remove_connection(owner, role: ActiveRecord::Base.current_role, shard: ActiveRecord::Base.current_shard)
  remove_connection_pool(owner, role: role, shard: shard)&.configuration_hash
end

#remove_connection_pool(owner, role: ActiveRecord::Base.current_role, shard: ActiveRecord::Base.current_shard) ⇒ Object



1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
# File 'lib/active_record/connection_adapters/abstract/connection_pool.rb', line 1147

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

#retrieve_connection(spec_name, role: ActiveRecord::Base.current_role, shard: ActiveRecord::Base.current_shard) ⇒ Object

Locate the connection of the nearest super class. This can be an active or defined connection: if it is the latter, it will be opened and set as the active connection for the class it was defined for (not necessarily the current class).



1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
# File 'lib/active_record/connection_adapters/abstract/connection_pool.rb', line 1111

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

#retrieve_connection_pool(owner, role: ActiveRecord::Base.current_role, shard: ActiveRecord::Base.current_shard) ⇒ Object

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



1161
1162
1163
1164
# File 'lib/active_record/connection_adapters/abstract/connection_pool.rb', line 1161

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

#while_preventing_writes(enabled = true) ⇒ Object

Prevent writing to the database regardless of role.

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

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

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



1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
# File 'lib/active_record/connection_adapters/abstract/connection_pool.rb', line 1019

def while_preventing_writes(enabled = true)
  unless ActiveRecord::Base.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