Module: DeleteInBatches

Defined in:
lib/delete_in_batches.rb,
lib/delete_in_batches/version.rb

Constant Summary collapse

VERSION =
"0.1.0"

Instance Method Summary collapse

Instance Method Details

#delete_in_batches(options = {}) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/delete_in_batches.rb', line 5

def delete_in_batches(options = {})
  batch_size = options[:batch_size] || 10000

  pk       = "#{quoted_table_name}.#{quoted_primary_key}"
  sql_proc = proc { select(pk).limit(batch_size).to_sql }
  sql      = connection.try(:unprepared_statement, &sql_proc) || sql_proc.call

  if %w(MySQL Mysql2 Mysql2Spatial).include?(connection.adapter_name)
    sql = "SELECT * FROM (#{sql}) AS t"
  end

  while connection.delete("DELETE FROM #{quoted_table_name} WHERE #{pk} IN (#{sql})") == batch_size
    yield if block_given?
  end
end