Class: Knockoff::ReplicaConnectionPool

Inherits:
Object
  • Object
show all
Defined in:
lib/knockoff/replica_connection_pool.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config_keys) ⇒ ReplicaConnectionPool

Returns a new instance of ReplicaConnectionPool.



5
6
7
8
9
10
11
# File 'lib/knockoff/replica_connection_pool.rb', line 5

def initialize(config_keys)
  @pool = Concurrent::Hash.new

  config_keys.each do |config_key|
    @pool[config_key] = connection_class(config_key)
  end
end

Instance Attribute Details

#poolObject (readonly)

Returns the value of attribute pool.



3
4
5
# File 'lib/knockoff/replica_connection_pool.rb', line 3

def pool
  @pool
end

Instance Method Details

#clear_all_active_connections!Object



13
14
15
16
17
# File 'lib/knockoff/replica_connection_pool.rb', line 13

def clear_all_active_connections!
  @pool.each do |_name, klass|
    klass.clear_active_connections!
  end
end

#connection_class(config_key) ⇒ Object

Based off of code from replica_pools gem generates a unique ActiveRecord::Base subclass for a single replica



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/knockoff/replica_connection_pool.rb', line 45

def connection_class(config_key)
  # Config key is of schema 'knockoff_replica_n'
  class_name = "KnockoffReplica#{config_key.split('_').last}"

  # TODO: Hardcoding the uri string feels meh. Either set the database config
  # or reference ENV instead
  Knockoff.module_eval %Q{
    class #{class_name} < ActiveRecord::Base
      self.abstract_class = true
      establish_connection :#{config_key}
      def self.connection_config
        configurations[#{config_key.to_s.inspect}]
      end
    end
  }, __FILE__, __LINE__

  Knockoff.const_get(class_name)
end

#disconnect_all_replicas!Object



19
20
21
22
23
# File 'lib/knockoff/replica_connection_pool.rb', line 19

def disconnect_all_replicas!
  @pool.each do |_name, klass|
    klass.connection.disconnect!
  end
end

#random_replica_connectionObject



39
40
41
# File 'lib/knockoff/replica_connection_pool.rb', line 39

def random_replica_connection
  @pool[@pool.keys.sample]
end

#reconnect_all_replicas!Object

Assumes that the config has been updated to something new, and simply reconnects with the config.



27
28
29
30
31
# File 'lib/knockoff/replica_connection_pool.rb', line 27

def reconnect_all_replicas!
  @pool.each do |database_key, klass|
    klass.establish_connection database_key.to_sym
  end
end

#set_schema_cache(cache) ⇒ Object



33
34
35
36
37
# File 'lib/knockoff/replica_connection_pool.rb', line 33

def set_schema_cache(cache)
  @pool.each do |_name, klass|
    klass.connection_pool.schema_cache = cache
  end
end