Class: Querrel::Querreller

Inherits:
Object
  • Object
show all
Defined in:
lib/querrel/querreller.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(dbs, options = {}) ⇒ Querreller

Returns a new instance of Querreller.



7
8
9
# File 'lib/querrel/querreller.rb', line 7

def initialize(dbs, options = {})
  @connection_resolver = ConnectionResolver.new(dbs, options[:db_names])
end

Instance Attribute Details

#connection_resolverObject

Returns the value of attribute connection_resolver.



5
6
7
# File 'lib/querrel/querreller.rb', line 5

def connection_resolver
  @connection_resolver
end

Instance Method Details

#map(scope, options = {}, &blk) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/querrel/querreller.rb', line 16

def map(scope, options = {}, &blk)
  if options.key?(:on)
    resolver = ConnectionResolver.new(dbs, !!options[:db_names])
    dbs = resolver.configurations.keys
  else
    resolver = @connection_resolver
    dbs = @connection_resolver.configurations.keys
  end

  query_model = scope.model
  results = {}

  threads = []
  dbs.each do |db|
    threads << Thread.new do
      con_spec = retrieve_connection_spec(db, resolver)
      dynamic_class_name = "TempModel#{Thread.current.object_id}"
      dynamic_class = Class.new(query_model)
      dynamic_class.send(:define_singleton_method, :name) { dynamic_class_name }

      begin
        dynamic_class.establish_connection(con_spec.config)
        local_scope = dynamic_class.all.merge(scope)
        results[db] = if block_given?
          res = yield(local_scope)
          res.to_a.each(&:readonly!) if res.is_a?(ActiveRecord::Relation)
          res
        else
          local_scope.to_a.each(&:readonly!)
        end
      ensure
        dynamic_class.connection_pool.release_connection
      end
    end
  end
  threads.each(&:join)

  results
end

#query(scope, options = {}, &blk) ⇒ Object



11
12
13
14
# File 'lib/querrel/querreller.rb', line 11

def query(scope, options = {}, &blk)
  buckets = map(scope, options, &blk)
  reduce(buckets)
end

#reduce(buckets) ⇒ Object



56
57
58
# File 'lib/querrel/querreller.rb', line 56

def reduce(buckets)
  buckets.flat_map{ |db, results| results }
end

#retrieve_connection_spec(db, resolver) ⇒ Object



60
61
62
# File 'lib/querrel/querreller.rb', line 60

def retrieve_connection_spec(db, resolver)
  resolver.spec(db.to_sym)
end

#while_connected_to(db, resolver, &b) ⇒ Object



64
65
66
67
68
69
70
# File 'lib/querrel/querreller.rb', line 64

def while_connected_to(db, resolver, &b)
  conf = resolver.spec(db.to_sym)
  pool = ActiveRecord::ConnectionAdapters::ConnectionPool.new(conf)
  pool.with_connection(&b)
ensure
  pool.disconnect!
end