Skip to content

Instantly share code, notes, and snippets.

@kandadaboggu
Created March 20, 2015 18:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kandadaboggu/4ea259523898a17f7cb3 to your computer and use it in GitHub Desktop.
Save kandadaboggu/4ea259523898a17f7cb3 to your computer and use it in GitHub Desktop.
module BulkInsertHelper
extend ActiveSupport::Concern
def insert_sql
fill_time_stamps
self.class.arel_table.
create_insert.tap do |im|
im.insert(
self.send(
:arel_attributes_with_values_for_create,
self.attribute_names
)
)
end.to_sql
end
def fill_time_stamps
columns, time_now = self.class.columns_hash, Time.now
%w(created_at updated_at).each do |attr|
# if time stamp field is present and not set
if columns.key?(attr) && send("#{attr}?")
send("#{attr}=", time_now)
end
end
end
class_methods do
def bulk_insert(rows, batch_size=1000)
transaction do
rows.lazy.each_slice(batch_size) do |batch|
batch_sql = batch.lazy.map do |row|
new(row).insert_sql
end.to_a.join(", ")
connection.insert_sql(batch_sql)
end
end
end
end
end
ActiveRecord::Base.send(:include, BulkInsertHelper)
# rows = (1..15).map{|i| {name: "name-#{i}", code: "code-#{i}"}}
# Invitation.bulk_insert(rows)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment