Class: PostgresUpsert::Writer

Inherits:
Object
  • Object
show all
Defined in:
lib/postgres_upsert/writer.rb

Instance Method Summary collapse

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, options = {})
  @klass = klass
  @options = options.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

#writeObject



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

  csv_options = @options[: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