Class: ActiveRecord::ConnectionAdapters::ConnectionHandler

Inherits:
Object
  • Object
show all
Defined in:
activerecord/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.


1005
1006
1007
1008
1009
1010
1011
# File 'activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb', line 1005

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?Boolean

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

Returns:

  • (Boolean)

1072
1073
1074
# File 'activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb', line 1072

def active_connections?
  connection_pool_list.any?(&:active_connection?)
end

#clear_active_connections!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.


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

def clear_active_connections!
  connection_pool_list.each(&:release_connection)
end

#clear_all_connections!Object


1090
1091
1092
# File 'activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb', line 1090

def clear_all_connections!
  connection_pool_list.each(&:disconnect!)
end

#clear_reloadable_connections!Object

Clears the cache which maps classes.

See ConnectionPool#clear_reloadable_connections! for details.


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

def clear_reloadable_connections!
  connection_pool_list.each(&:clear_reloadable_connections!)
end

#connected?(spec_name, pool_key = ActiveRecord::Base.default_pool_key) ⇒ Boolean

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

Returns:

  • (Boolean)

1125
1126
1127
1128
# File 'activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb', line 1125

def connected?(spec_name, pool_key = ActiveRecord::Base.default_pool_key)
  pool = retrieve_connection_pool(spec_name, pool_key)
  pool && pool.connected?
end

#connection_pool_listObject Also known as: connection_pools


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

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

#connection_pool_namesObject

:nodoc:


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

def connection_pool_names # :nodoc:
  owner_to_pool_manager.keys
end

#establish_connection(config, pool_key = Base.default_pool_key, owner_name = Base.name) ⇒ Object


1042
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
# File 'activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb', line 1042

def establish_connection(config, pool_key = Base.default_pool_key, owner_name = Base.name)
  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, pool_key)
  end

  message_bus = ActiveSupport::Notifications.instrumenter
  payload = {}
  if pool_config
    payload[:spec_name] = pool_config.connection_specification_name
    payload[:config] = db_config.configuration_hash
  end

  owner_to_pool_manager[pool_config.connection_specification_name] ||= PoolManager.new
  pool_manager = get_pool_manager(pool_config.connection_specification_name)
  pool_manager.set_pool_config(pool_key, pool_config)

  message_bus.instrument("!connection.active_record", payload) do
    pool_config.pool
  end
end

#flush_idle_connections!Object

Disconnects all currently idle connections.

See ConnectionPool#flush! for details.


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

def flush_idle_connections!
  connection_pool_list.each(&:flush!)
end

#prevent_writesObject

:nodoc:


1013
1014
1015
# File 'activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb', line 1013

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

#prevent_writes=(prevent_writes) ⇒ Object

:nodoc:


1017
1018
1019
# File 'activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb', line 1017

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

#remove_connection(owner, pool_key = ActiveRecord::Base.default_pool_key) ⇒ 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.


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

def remove_connection(owner, pool_key = ActiveRecord::Base.default_pool_key)
  remove_connection_pool(owner, pool_key)&.configuration_hash
end

#remove_connection_pool(owner, pool_key = ActiveRecord::Base.default_pool_key) ⇒ Object


1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
# File 'activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb', line 1139

def remove_connection_pool(owner, pool_key = ActiveRecord::Base.default_pool_key)
  if pool_manager = get_pool_manager(owner)
    pool_config = pool_manager.remove_pool_config(pool_key)

    if pool_config
      pool_config.disconnect!
      pool_config.db_config
    end
  end
end

#retrieve_connection(spec_name, pool_key = ActiveRecord::Base.default_pool_key) ⇒ 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).


1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
# File 'activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb', line 1105

def retrieve_connection(spec_name, pool_key = ActiveRecord::Base.default_pool_key) # :nodoc:
  pool = retrieve_connection_pool(spec_name, pool_key)

  unless pool
    if pool_key != ActiveRecord::Base.default_pool_key
      message = "No connection pool for '#{spec_name}' found for the '#{pool_key}' 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."
    else
      message = "No connection pool for '#{spec_name}' found."
    end

    raise ConnectionNotEstablished, message
  end

  pool.connection
end

#retrieve_connection_pool(owner, pool_key = ActiveRecord::Base.default_pool_key) ⇒ 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.


1153
1154
1155
1156
# File 'activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb', line 1153

def retrieve_connection_pool(owner, pool_key = ActiveRecord::Base.default_pool_key)
  pool_config = get_pool_manager(owner)&.get_pool_config(pool_key)
  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.


1026
1027
1028
1029
1030
1031
# File 'activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb', line 1026

def while_preventing_writes(enabled = true)
  original, self.prevent_writes = self.prevent_writes, enabled
  yield
ensure
  self.prevent_writes = original
end