Module: SwitchPoint::Connection

Defined in:
lib/switch_point/connection.rb

Constant Summary collapse

DESTRUCTIVE_METHODS =

See ActiveRecord::ConnectionAdapters::QueryCache

%i[insert update delete].freeze

Class Method Summary collapse

Class Method Details

.handle_base_connection(conn) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/switch_point/connection.rb', line 23

def self.handle_base_connection(conn)
  switch_points = conn.pool.spec.config[:switch_points]
  if switch_points
    switch_points.each do |switch_point|
      proxy = ProxyRepository.find(switch_point[:name])
      if switch_point[:mode] != :writable
        raise Error.new("ActiveRecord::Base's switch_points must be writable, but #{switch_point[:name]} is #{switch_point[:mode]}")
      end

      purge_readonly_query_cache(proxy)
    end
  end
end

.handle_generated_connection(conn, parent_method, method_name, *args, &block) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/switch_point/connection.rb', line 37

def self.handle_generated_connection(conn, parent_method, method_name, *args, &block)
  switch_point = conn.pool.spec.config[:switch_point]
  if switch_point
    proxy = ProxyRepository.find(switch_point[:name])
    case switch_point[:mode]
    when :readonly
      if SwitchPoint.config.auto_writable?
        proxy_to_writable(proxy, method_name, *args, &block)
      else
        raise ReadonlyError.new("#{switch_point[:name]} is readonly, but destructive method #{method_name} is called")
      end
    when :writable
      purge_readonly_query_cache(proxy)
      parent_method.call(*args, &block)
    else
      raise Error.new("Unknown mode #{switch_point[:mode]} is given with #{name}")
    end
  else
    parent_method.call(*args, &block)
  end
end

.proxy_to_writable(proxy, method_name, *args, &block) ⇒ Object



59
60
61
62
63
# File 'lib/switch_point/connection.rb', line 59

def self.proxy_to_writable(proxy, method_name, *args, &block)
  proxy.with_writable do
    proxy.connection.send(method_name, *args, &block)
  end
end

.purge_readonly_query_cache(proxy) ⇒ Object



65
66
67
68
69
# File 'lib/switch_point/connection.rb', line 65

def self.purge_readonly_query_cache(proxy)
  proxy.with_readonly do
    proxy.connection.clear_query_cache
  end
end