Class: PostgresUpsert::Writer
- Inherits:
-
Object
- Object
- PostgresUpsert::Writer
- Defined in:
- lib/postgres_upsert/writer.rb
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.
5 6 7 8 9 10 11 12 13 14 15 16 |
# File 'lib/postgres_upsert/writer.rb', line 5 def initialize(klass, source, = {}) @klass = klass = .reverse_merge({ :delimiter => ",", :format => :csv, :header => true, :key_column => @klass.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
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
# File 'lib/postgres_upsert/writer.rb', line 18 def write if @columns_list.empty? raise "Either the :columns option or :header => true are required" end = [:format] == :binary ? "BINARY" : "DELIMITER '#{@options[:delimiter]}' CSV" copy_table = @temp_table_name destination_table = get_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 #{csv_options}} do while line = read_input_line do next if line.strip.size == 0 ActiveRecord::Base.connection.raw_connection.put_copy_data line end end if destination_table upsert_from_temp_table drop_temp_table end end |