Skip to content

Instantly share code, notes, and snippets.

@vanpelt
Created March 29, 2011 20:18
Show Gist options
  • Save vanpelt/893153 to your computer and use it in GitHub Desktop.
Save vanpelt/893153 to your computer and use it in GitHub Desktop.
Allows us to do bulk inserts with Postgres
class BulkInsert
class InvalidModel < Exception; end
def initialize(model)
@model = model
@records = []
end
def add_record(record)
raise InvalidModel.new("#{record.class} must be a #{@model}") unless record.is_a?(@model)
unless record.valid?
raise InvalidModel.new(record.errors.map {|e| e }.join(", "))
end
@records << record
end
def prepare
@properties = []
@values = []
@records.each do |record|
record.dirty_attributes.each do |da, v|
@properties << da.name unless @properties.include?(da.name)
end
end
@records.each do |record|
@properties.map do |p|
@values << record.dirty_attributes.detect do |k,v|
k.name == p
end[1]
end
end
end
def statement
<<-SQL.compress_lines
INSERT INTO #{quote_name(@model.storage_name)}
(#{@properties.map {|p| quote_name(p)}.join(", ")})
VALUES
#{@records.map {|r| "("+(["?"] * @properties.size).join(", ")+")"}.join(", ")}
SQL
end
def execute!
prepare
@model.repository.adapter.execute(statement, *@values)
end
protected
def quote_name(name)
"\"#{name.to_s[0, 128].gsub('"', '""')}\""
end
end
@syrnick
Copy link

syrnick commented Mar 29, 2011

ok, it might work. You still want to get the ids back to fill in missed_judgments on job_stats and put them into assignments, right?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment