Class: Nquery::CsvImporter

Inherits:
Object
  • Object
show all
Defined in:
lib/nquery/csv_importer.rb

Defined Under Namespace

Classes: Error

Instance Method Summary collapse

Constructor Details

#initialize(file:, name:, creator:, column_mapping: {}) ⇒ CsvImporter

Returns a new instance of CsvImporter.



9
10
11
12
13
14
# File 'lib/nquery/csv_importer.rb', line 9

def initialize(file:, name:, creator:, column_mapping: {})
  @file = file
  @name = name.presence || "Import #{Time.current.to_fs(:short)}"
  @creator = creator
  @column_mapping = column_mapping
end

Instance Method Details

#importObject



16
17
18
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
# File 'lib/nquery/csv_importer.rb', line 16

def import
  raise Error, "No file provided" unless @file

  upload = CsvUpload.create!(
    name: @name,
    creator: @creator,
    status: "processing",
    column_mapping: @column_mapping
  )

  rows = CSV.read(@file.path, headers: true)
  table_name = "nquery_import_#{upload.id}"

  connection = ActiveRecord::Base.connection
  columns = infer_columns(rows.headers)
  create_import_table(connection, table_name, columns)
  insert_rows(connection, table_name, rows, columns)

  data_source = DataSource.create!(
    name: @name,
    adapter: connection.adapter_name.downcase.include?("postgres") ? "postgresql" : "rails",
    connection_config: { import_table: table_name }.to_json
  )

  upload.update!(status: "completed", column_mapping: columns)
  upload
rescue StandardError => e
  upload&.update!(status: "failed")
  raise Error, e.message
end