module Switchman::ActiveRecord::StatementCache

Public Class Methods

new(arel, bind_map, klass = nil) click to toggle source
# File lib/switchman/active_record/statement_cache.rb, line 16
def initialize(arel, bind_map, klass = nil)
  @arel = arel
  @bind_map = bind_map
  @klass = klass
  @qualified_query_builders = {}
end

Public Instance Methods

execute(*args) click to toggle source

since the StatememtCache is only implemented for basic relations in AR::Base#find, AR::Base#find_by and AR::Association#get_records, we can make some assumptions about the shard source (e.g. infer from the primary key or use the current shard)

# File lib/switchman/active_record/statement_cache.rb, line 28
def execute(*args)
  params, connection = args
  klass = @klass
  target_shard = nil
  if (primary_index = bind_map.primary_value_index)
    primary_value = params[primary_index]
    target_shard = Shard.local_id_for(primary_value)[1]
  end
  current_shard = Shard.current(klass.connection_classes)
  target_shard ||= current_shard

  bind_values = bind_map.bind(params, current_shard, target_shard)

  target_shard.activate(klass.connection_classes) do
    sql = qualified_query_builder(target_shard, klass).sql_for(bind_values, connection)
    klass.find_by_sql(sql, bind_values)
  end
end
qualified_query_builder(shard, klass) click to toggle source
# File lib/switchman/active_record/statement_cache.rb, line 47
def qualified_query_builder(shard, klass)
  @qualified_query_builders[shard.id] ||= klass.connection.cacheable_query(self.class, @arel).first
end