Class: Txdb::Iterators::AutoIncrementIterator

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/txdb/iterators/auto_increment_iterator.rb

Direct Known Subclasses

GlobalizeIterator

Constant Summary collapse

DEFAULT_BATCH_SIZE =
50
DEFAULT_COLUMN =
:id

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(table, options = {}) ⇒ AutoIncrementIterator

Returns a new instance of AutoIncrementIterator.



11
12
13
14
15
# File 'lib/txdb/iterators/auto_increment_iterator.rb', line 11

def initialize(table, options = {})
  @table = table
  @batch_size = options.fetch(:batch_size, DEFAULT_BATCH_SIZE)
  @column = options.fetch(:column, DEFAULT_COLUMN)
end

Instance Attribute Details

#batch_sizeObject (readonly)

Returns the value of attribute batch_size.



9
10
11
# File 'lib/txdb/iterators/auto_increment_iterator.rb', line 9

def batch_size
  @batch_size
end

#columnObject (readonly)

Returns the value of attribute column.



9
10
11
# File 'lib/txdb/iterators/auto_increment_iterator.rb', line 9

def column
  @column
end

#tableObject (readonly)

Returns the value of attribute table.



9
10
11
# File 'lib/txdb/iterators/auto_increment_iterator.rb', line 9

def table
  @table
end

Instance Method Details

#compact_mapObject



44
45
46
47
48
49
50
51
52
# File 'lib/txdb/iterators/auto_increment_iterator.rb', line 44

def compact_map
  return to_enum(__method__) unless block_given?

  each_with_object([]) do |elem, ret|
    if val = yield(elem)
      ret << val
    end
  end
end

#eachObject Also known as: each_record



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/txdb/iterators/auto_increment_iterator.rb', line 17

def each
  return to_enum(__method__) unless block_given?

  counter = 0
  last_value = nil
  sql_column = Sequel.expr(column)

  loop do
    records = table.connection
      .from(table_name)
      .where { sql_column >= counter }
      .order(column)
      .limit(batch_size)

    break if records.count == 0

    records.each do |record|
      yield record
      last_value = record[column]
    end

    counter = last_value + 1
  end
end