Class: CsvFastImporter::Import

Inherits:
Object
  • Object
show all
Defined in:
lib/csv_fast_importer/import.rb

Overview

Responsible for the main process

Instance Method Summary collapse

Constructor Details

#initialize(configuration) ⇒ Import

Returns a new instance of Import.



8
9
10
# File 'lib/csv_fast_importer/import.rb', line 8

def initialize(configuration)
  @configuration = configuration
end

Instance Method Details

#db_columns(configuration) ⇒ Object



37
38
39
40
41
42
43
44
45
# File 'lib/csv_fast_importer/import.rb', line 37

def db_columns(configuration)
  file_columns = configuration.file
                              .gets
                              .split(configuration.column_separator)
                              .map(&:strip)
  db_columns = file_columns.map(&:downcase)
                           .map { |column| configuration.mapping[column] || column }
  db_columns
end

#runObject



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/csv_fast_importer/import.rb', line 12

def run
  @db = CsvFastImporter::DatabaseFactory.build
  @db.verify_compatibility @configuration

  row_index = 0
  within_transaction_if(@configuration.transactional?) do
    table = @configuration.destination_table
    columns = db_columns(@configuration)
    if @configuration.deletion?
      if @configuration.truncate?
        @db.truncate table
      else
        @db.delete_all table
      end
    end
    row_index = @db.bulk_import(@configuration.file,
                                table,
                                columns,
                                row_index_column: @configuration.row_index_column,
                                column_separator: @configuration.column_separator,
                                encoding:         @configuration.encoding)
  end
  row_index
end

#within_transaction_if(transactional) ⇒ Object



47
48
49
50
51
52
53
54
55
# File 'lib/csv_fast_importer/import.rb', line 47

def within_transaction_if(transactional)
  if transactional
    @db.transaction do
      yield
    end
  else
    yield
  end
end