Sha256: 2ae5f2380a0927d2e0c3028953a145912526c2e926519aacec1136d3aed9adca

Contents?: true

Size: 950 Bytes

Versions: 4

Compression:

Stored size: 950 Bytes

Contents

# frozen_string_literal: true

module SqlToCsvStream
  class PostgresqlCopyEnumerator
    COPY_OPTIONS_DEFAULTS = {
      encoding: 'utf8'
    }.freeze

    def self.default_connection
      raise 'PostgreSQL database connection required' unless defined?(ActiveRecord)

      ActiveRecord::Base.connection.raw_connection
    end

    def initialize(sql, connection: self.class.default_connection, copy_options: {})
      @sql = sql.chomp(';')
      @connection = connection
      @copy_options = COPY_OPTIONS_DEFAULTS.merge(copy_options)
    end

    def each
      @connection.copy_data(copy_sql) do
        while (row = @connection.get_copy_data)
          yield(row) if block_given?
        end
      end
    end

    private

    def copy_sql
      "COPY (#{@sql}) TO STDOUT WITH (#{joined_copy_options})"
    end

    def joined_copy_options
      @copy_options.map { |k, v| "#{k.upcase} #{v}" }
                   .join(', ')
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
sql_to_csv_stream-0.3.0 lib/sql_to_csv_stream/postgresql_copy_enumerator.rb
sql_to_csv_stream-0.2.2 lib/sql_to_csv_stream/postgresql_copy_enumerator.rb
sql_to_csv_stream-0.2.1 lib/sql_to_csv_stream/postgresql_copy_enumerator.rb
sql_to_csv_stream-0.2.0 lib/sql_to_csv_stream/postgresql_copy_enumerator.rb