Module: SwitchPoint::Connection

Defined in:
lib/switch_point/connection.rb

Defined Under Namespace

Classes: ReadonlyError

Constant Summary collapse

DESTRUCTIVE_METHODS =

See ActiveRecord::ConnectionAdapters::QueryCache

[:insert, :update, :delete]

Class Method Summary collapse

Class Method Details

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



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

def self.handle_base_connection(conn, parent_method, *args, &block)
  switch_points = conn.pool.instance_variable_get(:@switch_points)
  if switch_points
    switch_points.each do |switch_point|
      proxy = ProxyRepository.find(switch_point[:name])
      if switch_point[:mode] != :writable
        raise RuntimeError.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
  conn.send(parent_method, *args, &block)
end

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



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

def self.handle_generated_connection(conn, parent_method, method_name, *args, &block)
  switch_point = conn.pool.instance_variable_get(:@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)
      conn.send(parent_method, *args, &block)
    else
      raise RuntimeError.new("Unknown mode #{switch_point[:mode]} is given with #{name}")
    end
  else
    conn.send(parent_method, *args, &block)
  end
end

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



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

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



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

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