Class: TypeInferrer

Inherits:
Object
  • Object
show all
Defined in:
lib/sqlite2mysql/services/type_inferrer.rb

Instance Method Summary collapse

Constructor Details

#initialize(samples, bound_finder) ⇒ TypeInferrer

Returns a new instance of TypeInferrer.



2
3
4
5
# File 'lib/sqlite2mysql/services/type_inferrer.rb', line 2

def initialize(samples, bound_finder)
  @samples = samples
  @bound_finder = bound_finder
end

Instance Method Details

#get_integer_typeObject



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/sqlite2mysql/services/type_inferrer.rb', line 50

def get_integer_type
  max = @bound_finder.max.to_i
  min = @bound_finder.min.to_i
  if min > -128 && max < 127
    'TINYINT'
  elsif min > -32768 && max < 32767
    'SMALLINT'
  elsif min > -8388608 && max < 8388607
    'MEDIUMINT'
  elsif min > -2147483648 && max < 2147483647
    'INT'
  else
    'BIGINT'
  end
end

#get_varchar_typeObject



66
67
68
69
70
71
72
73
# File 'lib/sqlite2mysql/services/type_inferrer.rb', line 66

def get_varchar_type
  max_length = @bound_finder.max_length
  max_length = 1 if max_length == 0 || max_length.nil?

  return 'TEXT' if max_length > 255

  "VARCHAR(#{max_length})"
end

#make_inferenceObject



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/sqlite2mysql/services/type_inferrer.rb', line 7

def make_inference
  possibilities = weigh_possibilities

  case possibilities.max_by(&:last).first
  when :int
    return get_integer_type
  when :float
    return 'FLOAT'
  when :date
    return 'DATE'
  when :datetime
    return 'DATETIME'
  when :string
    return get_varchar_type
  end
end

#weigh_possibilitiesObject



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/sqlite2mysql/services/type_inferrer.rb', line 24

def weigh_possibilities
  {
    float: 0,
    int: 0,
    date: 0,
    datetime: 0,
    string: 0
  }.tap do |possibilities|
    @samples.each do |sample|
      if date_or_time?(sample)
        if sample.is_a?(Date) || Date.parse(sample).to_time == Time.parse(sample)
          possibilities[:date] += 1
        else
          possibilities[:datetime] += 1
        end
      elsif sample.is_a?(Float) || sample.to_i > 0 && sample.to_f != sample.to_i.to_f
        possibilities[:float] += 1
      elsif sample.is_a?(Integer) || sample.to_i > 0 || sample == '0'
        possibilities[:int] += 1
      else
        possibilities[:string] += 1
      end
    end
  end
end