Created
March 29, 2011 20:18
-
-
Save vanpelt/893153 to your computer and use it in GitHub Desktop.
Allows us to do bulk inserts with Postgres
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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?