Module: OceanDynamo::Queries

Included in:
Table
Defined in:
lib/ocean-dynamo/queries.rb

Instance Method Summary collapse

Instance Method Details

#all(consistent: false, **options) ⇒ Object

Returns all records in the table.



43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/ocean-dynamo/queries.rb', line 43

def all(consistent: false, **options)
  _late_connect?
  result = []
  if consistent
    dynamo_items.each(options) do |item|
      result << new._setup_from_dynamo(item, consistent: consistent)
    end
  else
    dynamo_items.select(options) do |item_data| 
      result << new._setup_from_dynamo(item_data)
    end
  end
  result
end

#count(**options) ⇒ Object

The number of records in the table.



34
35
36
37
# File 'lib/ocean-dynamo/queries.rb', line 34

def count(**options)
  _late_connect?
  dynamo_items.count(options)
end

#find(hash, range = nil, consistent: false) ⇒ Object


Class methods



10
11
12
13
14
15
16
17
18
19
20
# File 'lib/ocean-dynamo/queries.rb', line 10

def find(hash, range=nil, consistent: false)
  return hash.collect {|elem| find elem, range, consistent: consistent } if hash.is_a?(Array)
  _late_connect?
  hash = hash.id if hash.kind_of?(Table)    # TODO: We have (innocuous) leakage, fix!
  range = range.to_i if range.is_a?(Time)
  item = dynamo_items[hash, range]
  unless item.exists?
    raise RecordNotFound, "can't find a #{self} with primary key ['#{hash}', #{range.inspect}]" 
  end
  new._setup_from_dynamo(item, consistent: consistent)
end

#find_by_key(*args) ⇒ Object Also known as: find_by_id



23
24
25
26
27
# File 'lib/ocean-dynamo/queries.rb', line 23

def find_by_key(*args)
  find(*args)
rescue RecordNotFound
  nil
end

#find_each(limit: nil, batch_size: 1000, consistent: false) ⇒ Object

Looping through a collection of records from the database (using the all method, for example) is very inefficient since it will try to instantiate all the objects at once.

In that case, batch processing methods allow you to work with the records in batches, thereby greatly reducing memory consumption.



66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/ocean-dynamo/queries.rb', line 66

def find_each(limit: nil, batch_size: 1000, consistent: false)
  if consistent
    dynamo_items.each(limit: limit, batch_size: batch_size) do |item|
      yield new._setup_from_dynamo(item, consistent: consistent)
    end
  else
    dynamo_items.select(limit: limit, batch_size: batch_size) do |item_data|
      yield new._setup_from_dynamo(item_data)
    end
  end
  true
end