Created
February 2, 2016 08:47
-
-
Save w00lf/1002fac4122dfea7d5e3 to your computer and use it in GitHub Desktop.
This file contains 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 BatchCreatorService < Struct.new(:model, :to_insert_attrs) | |
include Service | |
def call | |
raw_connection = get_raw_connection | |
keys = to_insert_attrs.first.keys | |
@types_hash = Hash[Event.column_types.map{|x,y| [x,y.type.to_s] }] | |
raw_connection.exec("COPY #{model.table_name} (#{keys.join(',')}) FROM STDIN WITH CSV DELIMITER ';'") | |
to_insert_attrs.each do |attrs| | |
values = attrs.map{|key, value| sanitize_attribute(key, value) }.join(';') | |
# Add row to copy data | |
raw_connection.put_copy_data("#{values}\n") | |
end | |
# We are done adding copy data | |
raw_connection.put_copy_end | |
# Display any error messages | |
while res = raw_connection.get_result | |
if e_message = res.error_message | |
# fail(e_message) | |
end | |
end | |
end | |
private | |
def sanitize_attribute(key, value) | |
if @types_hash[key] == 'json' | |
return value.to_json | |
end | |
if value.is_a?(Array) | |
sanitized_array = value.map{|n| sanitize_value(n) }.join(',') | |
return "{ #{sanitized_array} }" | |
end | |
if @types_hash[key] == 'datetime' | |
return sanitize_value(Time.parse(value)) | |
end | |
sanitize_value(value) | |
end | |
def sanitize_value(value) | |
ActiveRecord::Base.sanitize(value).gsub("'", '') | |
end | |
def get_raw_connection | |
ActiveRecord::Base.connection.raw_connection | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment