Class: PostgresUpsert::Writer
- Inherits:
-
Object
- Object
- PostgresUpsert::Writer
- Defined in:
- lib/postgres_upsert/writer.rb
Direct Known Subclasses
Instance Method Summary collapse
-
#initialize(klass, source, options = {}) ⇒ Writer
constructor
A new instance of Writer.
- #write ⇒ Object
Constructor Details
#initialize(klass, source, options = {}) ⇒ Writer
Returns a new instance of Writer.
4 5 6 7 8 9 10 11 12 13 14 |
# File 'lib/postgres_upsert/writer.rb', line 4 def initialize(klass, source, = {}) @klass = klass @options = .reverse_merge({ :delimiter => ",", :header => true, :key_column => primary_key, :update_only => false}) @source = source.instance_of?(String) ? File.open(source, 'r') : source @columns_list = get_columns generate_temp_table_name end |
Instance Method Details
#write ⇒ Object
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/postgres_upsert/writer.rb', line 16 def write if @columns_list.empty? raise "Either the :columns option or :header => true are required" end = "DELIMITER '#{@options[:delimiter]}' CSV" copy_table = @temp_table_name columns_string = columns_string_for_copy create_temp_table ActiveRecord::Base.connection.raw_connection.copy_data %{COPY #{copy_table} #{columns_string} FROM STDIN #{}} do while line = @source.gets do next if line.strip.size == 0 ActiveRecord::Base.connection.raw_connection.put_copy_data line end end upsert_from_temp_table drop_temp_table PostgresUpsert::Result.new(@insert_result, @update_result) end |