Module: SwitchPoint::Connection

Defined in:
lib/switch_point/connection.rb

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



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

def self.handle_base_connection(conn, parent_method, *args, &block)
  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
  conn.send(parent_method, *args, &block)
end

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



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

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)
      conn.send(parent_method, *args, &block)
    else
      raise Error.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



56
57
58
59
60
# File 'lib/switch_point/connection.rb', line 56

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



62
63
64
65
66
# File 'lib/switch_point/connection.rb', line 62

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