Module: ActiveVersion::Audits::SQLBuilder::ClassMethods

Defined in:
lib/active_version/audits/sql_builder.rb

Defined Under Namespace

Classes: BatchCollector

Instance Method Summary collapse

Instance Method Details

#batch_insert(records = nil, options = {}, &block) ⇒ Integer

Execute batch insert SQL for audits. Supports the same arguments and block semantics as batch_insert_sql.

Returns:

  • (Integer)

    0 when nothing to insert, otherwise adapter execute result



85
86
87
88
89
90
# File 'lib/active_version/audits/sql_builder.rb', line 85

def batch_insert(records = nil, options = {}, &block)
  sql = batch_insert_sql(records, options, &block)
  return 0 if sql.empty?

  connection.execute(sql)
end

#batch_insert_sql(records = nil, options = {}, &block) ⇒ String

Generate SQL for batch insert of audits

Parameters:

  • records (Array) (defaults to: nil)

    Array of ActiveRecord instances to audit

  • options (Hash) (defaults to: {})

    Options for batch generation

Options Hash (options):

  • :combine (Boolean) — default: true

    Combine into single INSERT statement

  • :context (Hash)

    Additional context to merge with each audit

Returns:

  • (String)

    SQL statement(s) for batch insert



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/active_version/audits/sql_builder.rb', line 36

def batch_insert_sql(records = nil, options = {}, &block)
  records, options = normalize_batch_arguments(records, options)
  captured_values = []

  if block_given? && block.arity == 0 && Array(records).flatten.compact.empty?
    captured_values = capture_audit_values(options) { yield }
  end

  if captured_values.any?
    if options[:combine] != false
      return build_combined_insert_sql(self, captured_values)
    end

    return captured_values.map { |values| build_single_insert_sql(self, values) }.join(";\n")
  end

  records = resolve_batch_records(records, &block)
  return "" if records.empty?

  # Get audit class from first record
  first_record = records.first
  return "" unless first_record

  audit_class = first_record.class.audit_class
  return "" unless audit_class

  version_tracker = {}

  # Build values for each record
  values_list = records.map do |record|
    build_batch_audit_values(record, audit_class, options, version_tracker)
  end.compact

  return "" if values_list.empty?

  # Combine into single INSERT with multiple VALUES
  if options[:combine] != false
    build_combined_insert_sql(audit_class, values_list)
  else
    # Return separate INSERT statements
    values_list.map do |values|
      build_single_insert_sql(audit_class, values)
    end.join(";\n")
  end
end