Class: Coupler::Models::Import

Inherits:
Sequel::Model
  • Object
show all
Includes:
CommonModel, Jobify
Defined in:
lib/coupler/models/import.rb

Constant Summary collapse

DateMatcher =

NOTE: yoinked from FasterCSV A Regexp used to find and convert some common Date formats.

/ \A(?: (\w+,?\s+)?\w+\s+\d{1,2},?\s+\d{2,4} |
\d{4}-\d{2}-\d{2} )\z /x
DateTimeMatcher =

A Regexp used to find and convert some common DateTime formats.

/ \A(?: (\w+,?\s+)?\w+\s+\d{1,2}\s+\d{1,2}:\d{1,2}:\d{1,2},?\s+\d{2,4} |
\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2} )\z /x

Instance Method Summary collapse

Methods included from Jobify

included

Methods included from CommonModel

#after_destroy, #after_save, #before_create, #before_save, #before_update, included, #save!, #touch!

Instance Method Details

#data=(value) ⇒ Object



22
23
24
25
26
27
# File 'lib/coupler/models/import.rb', line 22

def data=(value)
  result = super
  self.name ||= File.basename(data.file.original_filename).sub(/\.\w+?$/, "").gsub(/[_-]+/, " ").capitalize
  discover_fields
  result
end

#datasetObject



128
129
130
131
132
# File 'lib/coupler/models/import.rb', line 128

def dataset
  project.local_database do |db|
    yield(db[table_name])
  end
end

#import!(&progress) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/coupler/models/import.rb', line 53

def import!(&progress)
  project.local_database do |db|
    column_info = []
    column_names = []
    column_types = []
    field_names.each_with_index do |name, i|
      name_sym = name.to_sym
      column_names << name_sym
      column_types << {
        :name => name_sym,
        :type =>
          case field_types[i]
          when 'integer' then Integer
          when 'string' then String
          end,
        :null => !(name == primary_key_name)
      }
    end
    column_names << :dup_key_count
    column_types << {:name => :dup_key_count, :type => Integer}
    db.create_table!(table_name) do
      columns.push(*column_types)
    end

    ds = db[table_name]
    key_frequencies = Hash.new { |h, k| h[k] = 0 }
    buffer = ImportBuffer.new(column_names, ds)
    skip = has_headers
    primary_key_index = field_names.index(primary_key_name)
    io = File.open(data.file.file, 'rb')
    csv = FasterCSV.new(io)
    csv.each do |row|
      if skip
        # skip header if necessary
        skip = false
        next
      end

      # convert values
      row.each_with_index do |value, i|
        row[i] = coerce(value, field_types[i])
      end

      key = row[primary_key_index]
      num = key_frequencies[key] += 1
      row.push(num > 1 ? num : nil)
      self.has_duplicate_keys = true if num > 1

      buffer.add(row)

      if block_given?
        yield io.pos
      end
    end
    buffer.flush

    primary_key = self.primary_key_sym
    if has_duplicate_keys
      # flag duplicate primary keys
      key_frequencies.each_pair do |key, count|
        next  if count == 1
        ds.filter(primary_key => key, :dup_key_count => nil).update(:dup_key_count => 1)
      end
    else
      # alter table to set primary key
      db.alter_table(table_name) do
        drop_column(:dup_key_count)
        add_primary_key([primary_key])
      end
    end
  end
  update(:occurred_at => Time.now)
  !has_duplicate_keys
end

#previewObject



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/coupler/models/import.rb', line 37

def preview
  if @preview.nil?
    @preview = []
    FasterCSV.open(data.file.file) do |csv|
      csv.rewind
      csv.shift   if self.has_headers
      50.times do |i|
        row = csv.shift
        break if row.nil?
        @preview << row
      end
    end
  end
  @preview
end

#primary_key_symObject



29
30
31
# File 'lib/coupler/models/import.rb', line 29

def primary_key_sym
  primary_key_name.to_sym
end

#repair_duplicate_keys!(rows_to_remove = nil) ⇒ Object



134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# File 'lib/coupler/models/import.rb', line 134

def repair_duplicate_keys!(rows_to_remove = nil)
  pkey = primary_key_sym
  project.local_database do |db|
    ds = db[table_name]
    if rows_to_remove
      filtered_ds = nil
      rows_to_remove.each_pair do |key, dups|
        hsh = {pkey => key, :dup_key_count => dups}
        filtered_ds = filtered_ds ? filtered_ds.or(hsh) : ds.filter(hsh)
      end
      filtered_ds.delete if filtered_ds
    end

    # only reassign keys if there is more than 1 duplicate per key
    keys = ds.group(pkey).having { count(pkey) > 1 }.select_map(pkey)

    current_key = nil
    next_key = ds.order(pkey).last[pkey].next
    ds.filter(pkey => keys).order(:dup_key_count).each do |row|
      # skip the first one, since it'll retain the key
      if current_key != row[pkey]
        current_key = row[pkey]
      else
        ds.filter(pkey => row[pkey], :dup_key_count => row[:dup_key_count]).
          update(pkey => next_key)
        next_key = next_key.next
      end
    end

    db.alter_table(table_name) do
      drop_column(:dup_key_count)
      add_primary_key([pkey])
    end
  end
end

#table_nameObject



33
34
35
# File 'lib/coupler/models/import.rb', line 33

def table_name
  :"import_#{id}"
end