Skip to content

Commit

Permalink
INSERT all columns
Browse files Browse the repository at this point in the history
  • Loading branch information
sergeykish committed Apr 27, 2017
1 parent 1cb4fb7 commit 78cd0c1
Showing 1 changed file with 6 additions and 14 deletions.
20 changes: 6 additions & 14 deletions lib/active_record_bulk_insert.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,41 +14,33 @@ def self.bulk_insert_in_batches(attrs, options = {})
def self.bulk_insert(attrs, options = {})
return [] if attrs.empty?

use_provided_primary_key = options.fetch(:use_provided_primary_key, false)
attributes = _resolve_record(attrs.first, options).keys.join(", ")
to_import = columns.reject { |column| column.name == primary_key } unless options.fetch(:use_provided_primary_key, false)

invalid = []
if options.fetch(:validate, false)
attrs, invalid = attrs.partition { |record| _validate(record) }
end

values_sql = attrs.map do |record|
quoted = _resolve_record(record, options).map {|k, v|
column = try(:column_for_attribute, k)
v = connection.type_cast_from_column(column, v) if column
quoted = to_import.map { |column|
k = column.name
v = record[k] || record[k.to_sym]
v = connection.type_cast_from_column(column, v)
connection.quote(v)
}
"(#{quoted.join(', ')})"
end.join(",")

sql = <<-SQL
INSERT INTO #{quoted_table_name}
(#{attributes})
(#{to_import.map(&:name).join(", ")})
VALUES
#{values_sql}
SQL
connection.execute(sql) unless attrs.empty?
invalid
end

def self._resolve_record(record, options)
time = ActiveRecord::Base.default_timezone == :utc ? Time.now.utc : Time.now
_record = record.is_a?(ActiveRecord::Base) ? record.attributes : record
_record.merge!("created_at" => time, "updated_at" => time) unless options.fetch(:disable_timestamps, false)
_record = _record.except(primary_key).except(primary_key.to_sym) unless options.fetch(:use_provided_primary_key, false)
_record
end

def self._validate(record)
if record.is_a?(Hash)
new(record).valid?
Expand Down

0 comments on commit 78cd0c1

Please sign in to comment.