Class: PostgresUpsert::Writer

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

Direct Known Subclasses

TableWriter

Instance Method Summary collapse

Constructor Details

#initialize(klass, source, options = {}) ⇒ Writer



4
5
6
7
8
9
10
11
12
13
14
15
# File 'lib/postgres_upsert/writer.rb', line 4

def initialize(klass, source, options = {})
  @klass = klass
  @options = options.reverse_merge({
    :delimiter => ",",
    :header => true,
    :unique_key => [primary_key],
    :update_only => false})
  @options[:unique_key] = Array.wrap(@options[:unique_key])
  @source = source.instance_of?(String) ? File.open(source, 'r') : source
  @columns_list = get_columns
  generate_temp_table_name
end

Instance Method Details

#writeObject



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/postgres_upsert/writer.rb', line 17

def write
  if @columns_list.empty?
    raise "Either the :columns option or :header => true are required"
  end

  csv_options = "DELIMITER '#{@options[:delimiter]}' CSV"

  copy_table = @temp_table_name
  columns_string = columns_string_for_copy
  create_temp_table

  @copy_result = database_connection.raw_connection.copy_data %{COPY #{copy_table} #{columns_string} FROM STDIN #{csv_options}} do

    while line = @source.gets do
      next if line.strip.size == 0
      database_connection.raw_connection.put_copy_data line
    end
  end

  upsert_from_temp_table
  drop_temp_table

  summarize_results
end