Class: OccamsRecord::Batches::OffsetLimit::RawQuery

Inherits:
Object
  • Object
show all
Defined in:
lib/occams-record/batches/offset_limit/raw_query.rb

Overview

Implements batched loading for pure SQL.

Instance Method Summary collapse

Constructor Details

#initialize(conn, sql, binds, use: nil, query_logger: nil, eager_loaders: nil) ⇒ RawQuery

Returns a new instance of RawQuery.



8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/occams-record/batches/offset_limit/raw_query.rb', line 8

def initialize(conn, sql, binds, use: nil, query_logger: nil, eager_loaders: nil)
  @conn, @sql, @binds = conn, sql, binds
  @use, @query_logger, @eager_loaders = use, query_logger, eager_loaders

  unless binds.is_a? Hash
    raise ArgumentError, "When using find_each/find_in_batches with raw SQL, binds MUST be a Hash. SQL statement: #{@sql}"
  end

  unless @sql =~ /LIMIT\s+%\{batch_limit\}/i and @sql =~ /OFFSET\s+%\{batch_offset\}/i
    raise ArgumentError, "When using find_each/find_in_batches with raw SQL, you must specify 'LIMIT %{batch_limit} OFFSET %{batch_offset}'. SQL statement: #{@sql}"
  end
end

Instance Method Details

#enum(batch_size:, use_transaction: true) ⇒ Enumerator

Returns an Enumerator that yields batches of records, of size “of”. The SQL string must include ‘LIMIT %batch_limit OFFSET %batch_offset’. The bind values will be provided by OccamsRecord.

Parameters:

  • batch_size (Integer)

    batch size

  • use_transaction (Boolean) (defaults to: true)

    Ensure it runs inside of a database transaction

Returns:

  • (Enumerator)

    yields batches



30
31
32
33
34
35
36
37
38
39
40
# File 'lib/occams-record/batches/offset_limit/raw_query.rb', line 30

def enum(batch_size:, use_transaction: true)
  Enumerator.new do |y|
    if use_transaction and @conn.open_transactions == 0
      @conn.transaction {
        run_batches y, batch_size
      }
    else
      run_batches y, batch_size
    end
  end
end