Class: SqlToCsvStream::CsvEnumerator

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

Constant Summary collapse

PREFIXES_TO_ESCAPE =
%w[= @ + - |].freeze
ESCAPE_CHAR =
"'"
COPY_OPTIONS_DEFAULTS =

Other possible options are

force_quote: '*'
escape: "E'\\\\'"

For details see Postgresqls COPY documentation.

{
  format: 'CSV',
  header: true
}.freeze

Instance Method Summary collapse

Constructor Details

#initialize(object, connection: PostgresqlCopyEnumerator.default_connection, copy_options: {}, sanitize: true, force_quotes: false) ⇒ CsvEnumerator

Returns a new instance of CsvEnumerator.



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/sql_to_csv_stream/csv_enumerator.rb', line 19

def initialize(
  object,
  connection: PostgresqlCopyEnumerator.default_connection,
  copy_options: {},
  sanitize: true,
  force_quotes: false
)
  @sanitize = sanitize
  @force_quotes = force_quotes

  sql = (object.respond_to?(:to_sql) ? object.to_sql : object.to_s).chomp(';')
  copy_options = COPY_OPTIONS_DEFAULTS.merge(copy_options)
  copy_options[:force_quote] = '*' if @force_quotes
  @copy_enum = PostgresqlCopyEnumerator.new(sql, connection: connection, copy_options: copy_options)
end

Instance Method Details

#eachObject



35
36
37
38
39
# File 'lib/sql_to_csv_stream/csv_enumerator.rb', line 35

def each
  @copy_enum.each do |line|
    yield(sanitize(line)) if block_given?
  end
end