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.
6 7 8 9 10 11 12 13 14 15 16 17 |
# File 'lib/postgres_upsert/writer.rb', line 6 def initialize(klass, source, = {}) @klass = klass @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
#write ⇒ Object
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 44 45 46 47 48 |
# File 'lib/postgres_upsert/writer.rb', line 19 def write import org.postgresql.copy.CopyManager if @columns_list.empty? raise "Either the :columns option or :header => true are required" end = @options[:format] == :binary ? "BINARY" : "DELIMITER '#{@options[:delimiter]}' CSV" copy_table = @temp_table_name columns_string = columns_string_for_copy ActiveRecord::Base.connection_pool.with_connection do |conn| create_temp_table(conn) copy_manager = CopyManager.new(conn.raw_connection.connection) stream = copy_manager.copy_in("COPY #{copy_table} #{columns_string} FROM STDIN WITH #{}") while line = read_input_line do next if line.strip.size == 0 line = line.to_java_bytes stream.write_to_copy(line, 0, line.length) end stream.end_copy upsert_from_temp_table(conn) drop_temp_table(conn) end end |