Class: DbBlaster::FinderSql

Inherits:
Object
  • Object
show all
Defined in:
lib/db_blaster/finder_sql.rb

Overview

Creates the SQL needed to find records for the provided source_table

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(source_table) ⇒ FinderSql

Returns a new instance of FinderSql.



8
9
10
# File 'lib/db_blaster/finder_sql.rb', line 8

def initialize(source_table)
  @source_table = source_table
end

Instance Attribute Details

#source_tableObject (readonly)

Returns the value of attribute source_table.



6
7
8
# File 'lib/db_blaster/finder_sql.rb', line 6

def source_table
  @source_table
end

Class Method Details

.sql_for_source_table(source_table) ⇒ Object



12
13
14
# File 'lib/db_blaster/finder_sql.rb', line 12

def self.sql_for_source_table(source_table)
  new(source_table).select_sql
end

Instance Method Details

#from_updated_atObject



34
35
36
# File 'lib/db_blaster/finder_sql.rb', line 34

def from_updated_at
  @from_updated_at ||= source_table.last_published_updated_at
end

#last_published_idObject



38
39
40
# File 'lib/db_blaster/finder_sql.rb', line 38

def last_published_id
  @last_published_id ||= source_table.last_published_id
end

#select_sqlObject



16
17
18
# File 'lib/db_blaster/finder_sql.rb', line 16

def select_sql
  "SELECT * FROM #{source_table.name} #{where} ORDER BY updated_at ASC LIMIT #{source_table.batch_size}"
end

#whereObject

if we just use updated_at > from_updated_at, it’s possible to miss records that share the same ‘updated_at` if we use updated_at >= from_updated_at, we’ll get redundant records on every run settled on the approach below



24
25
26
27
28
29
30
31
32
# File 'lib/db_blaster/finder_sql.rb', line 24

def where
  return '' unless from_updated_at

  ActiveRecord::Base.sanitize_sql_for_conditions(
    ['WHERE updated_at > :updated_at OR (updated_at = :updated_at AND id <> :updated_id)',
     { updated_at: from_updated_at,
       updated_id: last_published_id }]
  )
end