Method: ActiveRecord::Import::MysqlAdapter#insert_many

Defined in:
lib/activerecord-import/adapters/mysql_adapter.rb

#insert_many(sql, values, options = {}, *args) ⇒ Object

sql can be a single string or an array. If it is an array all elements that are in position >= 1 will be appended to the final SQL.



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/activerecord-import/adapters/mysql_adapter.rb', line 12

def insert_many( sql, values, options = {}, *args ) # :nodoc:
  # the number of inserts default
  number_of_inserts = 0

  base_sql, post_sql = case sql
                       when String
                         [sql, '']
                       when Array
                         [sql.shift, sql.join( ' ' )]
  end

  sql_size = QUERY_OVERHEAD + base_sql.bytesize + post_sql.bytesize

  # the number of bytes the requested insert statement values will take up
  values_in_bytes = values.sum(&:bytesize)

  # the number of bytes (commas) it will take to comma separate our values
  comma_separated_bytes = values.size - 1

  # the total number of bytes required if this statement is one statement
  total_bytes = sql_size + values_in_bytes + comma_separated_bytes

  max = max_allowed_packet

  # if we can insert it all as one statement
  if max == NO_MAX_PACKET || total_bytes <= max || options[:force_single_insert]
    number_of_inserts += 1
    sql2insert = base_sql + values.join( ',' ) + post_sql
    insert( sql2insert, *args )
  else
    value_sets = ::ActiveRecord::Import::ValueSetsBytesParser.parse(values,
      reserved_bytes: sql_size,
      max_bytes: max)

    transaction(requires_new: true) do
      value_sets.each do |value_set|
        number_of_inserts += 1
        sql2insert = base_sql + value_set.join( ',' ) + post_sql
        insert( sql2insert, *args )
      end
    end
  end

  ActiveRecord::Import::Result.new([], number_of_inserts, [], [])
end