Module: ActiveRecordBatchUpdate::ClassMethods

Defined in:
lib/activerecord_batch_update.rb

Overview

Given an array of records with changes, perform the minimal amount of queries to update all the records without including unchanged attributes in the UPDATE statement.

Do this without INSERT … ON DUPLICATE KEY UPDATE which will re-insert the objects if they were deleted in another thread

Instance Method Summary collapse

Instance Method Details

#batch_update(entries, columns:, batch_size: 100, validate: true) ⇒ Object



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/activerecord_batch_update.rb', line 17

def batch_update(entries, columns:, batch_size: 100, validate: true)
  columns = column_names if columns == :all
  columns = (Array.wrap(columns).map(&:to_s) + %w[updated_at]).uniq

  entries = entries.select { columns.intersect?(_1.changed) }
  entries.each { _1.updated_at = Time.current } if has_attribute?('updated_at')
  entries.each(&:validate!) if validate

  primary_keys = Array.wrap(primary_key).map(&:to_s)

  updated_count = batch_update_statements(
    entries.map do |entry|
      (primary_keys + (entry.changed & columns)).to_h { [_1, entry.read_attribute(_1)] }
    end,
    update_on: primary_keys,
    batch_size: batch_size
  ).sum do |sql|
    connection.exec_update(sql)
  end

  connection.clear_query_cache if connection.query_cache_enabled

  updated_count
end

#batch_update_statements(entries, update_on: :id, batch_size: 100) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/activerecord_batch_update.rb', line 42

def batch_update_statements(entries, update_on: :id, batch_size: 100)
  update_on = Array.wrap(update_on).map(&:to_s)

  entries.map(&:stringify_keys).group_by { _1.keys.sort! }.sort.flat_map do |(keys, items)|
    next [] if keys.empty?

    where_clause = where_statement(update_on)
    update_clause = update_statement(keys - update_on)

    items.each_slice(batch_size).map do |slice|
      [
        "WITH \"#{cte_table.name}\" (#{keys.join(', ')})",
        "AS ( #{values_statement(slice, keys)} )",
        update_clause,
        "FROM \"#{cte_table.name}\"",
        "WHERE #{where_clause}"
      ].join(' ')
    end
  end
end