Class: ActiveRecord::Pool

Inherits:
Object
  • Object
show all
Defined in:
lib/active_record/pool.rb,
lib/active_record/pool/version.rb

Constant Summary collapse

DEFAULT_SIZE =
24
DEFAULT_SERIALIZER =
::JSON
EMPTY_HASH =
{}
VERSION =
"1.0.1"

Instance Method Summary collapse

Constructor Details

#initialize(query:, columns:, table:, size:, serializer:, model:, &transaction) ⇒ Pool

query is either an ActiveRecord query object or arel columns is a list of columns you want to have during the transaction table is the table you want to talk to size is the maximum number of running iterations in the pool, default: 24 serializer is the #dump duck for Array & Hash values, default: JSON model is an ActiveRecord model transaction is the process you want to run against your database



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
55
56
57
58
59
60
61
62
63
64
# File 'lib/active_record/pool.rb', line 18

def initialize(query:, columns:, table:, size:, serializer:, model:, &transaction)
  @query = query
  @serializer = serializer
  @table = Arel::Table.new(table)
  qutex = Mutex.new

  queue = case
  when activerecord?
    @query.pluck(*@columns)
  when arel?
    ActiveRecord::Base.connection.execute(@query.to_sql).map(&:values)
  when tuple?
    @query.map { |result| result.slice(*columns).values }
  when twodimensional?
    @query
  else
    raise ArgumentError, 'query wasn\'t recognizable, please use some that looks like a: ActiveRecord::Base, Arel::SelectManager, Array[Hash], Array[Array]'
  end

  puts "Migrating #{queue.count} #{table} records"

  # Spin up a number of threads based on the `maximum` given
  1.upto(size).map do
    Thread.new do
      loop do
        # Try to get a new queue item
        item = qutex.synchronize { queue.shift }

        if item.nil?
          # There is no more work
          break
        else
          # Wait for a free connection
          model.connection_pool.with_connection do
            model.transaction do
              # Execute each statement coming back
              Array[instance_exec(*item, &transaction)].each do |instruction|
                next if instruction.nil?
                model.connection.execute(instruction.to_sql)
              end
            end
          end
        end
      end
    end
  end.map(&:join)
end