Class: SqlToCsvStream::PostgresqlCopyEnumerator

Inherits:
Object
  • Object
show all
Defined in:
lib/sql_to_csv_stream/postgresql_copy_enumerator.rb

Constant Summary collapse

COPY_OPTIONS_DEFAULTS =
{
  encoding: 'utf8'
}.freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(sql, connection: self.class.default_connection, copy_options: {}) ⇒ PostgresqlCopyEnumerator



15
16
17
18
19
# File 'lib/sql_to_csv_stream/postgresql_copy_enumerator.rb', line 15

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

Class Method Details

.default_connectionObject



9
10
11
12
13
# File 'lib/sql_to_csv_stream/postgresql_copy_enumerator.rb', line 9

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

  ActiveRecord::Base.connection.raw_connection
end

Instance Method Details

#eachObject



21
22
23
24
25
26
27
# File 'lib/sql_to_csv_stream/postgresql_copy_enumerator.rb', line 21

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