Class: SqliteClient

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

Instance Method Summary collapse

Constructor Details

#initialize(filename, infer_column_types: false) ⇒ SqliteClient

Returns a new instance of SqliteClient.



5
6
7
8
# File 'lib/sqlite2mysql/services/sqlite.rb', line 5

def initialize(filename, infer_column_types: false)
  @db = SQLite3::Database.new(filename)
  @infer = infer_column_types
end

Instance Method Details

#build_schemaObject



10
11
12
13
14
15
16
17
18
19
# File 'lib/sqlite2mysql/services/sqlite.rb', line 10

def build_schema
  schema = {}
  tables = @db.execute 'SELECT name FROM sqlite_master WHERE type="table"'

  tables.flatten.each do |t|
    schema[t] = column_formatter(t)
  end

  schema
end

#column_formatter(table) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/sqlite2mysql/services/sqlite.rb', line 25

def column_formatter(table)
  columns = @db.execute("pragma table_info(#{table})")

  formatted_columns = []
  columns.each do |col|
    formatted_columns << { name:    col[1],
                           type:    type_getter(col[2], table, col[1]),
                           notnull: col[3],
                           default: col[4] }
  end
  formatted_columns
end

#get_data(table) ⇒ Object



21
22
23
# File 'lib/sqlite2mysql/services/sqlite.rb', line 21

def get_data(table)
  @db.execute("select * from #{table}")
end

#select(column, table) ⇒ Object



55
56
57
# File 'lib/sqlite2mysql/services/sqlite.rb', line 55

def select(column, table)
  @db.execute("SELECT #{column} FROM #{table}").flatten.first
end

#type_getter(type, table, column) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/sqlite2mysql/services/sqlite.rb', line 38

def type_getter(type, table, column)
  if @infer
    samples = @db.execute("SELECT #{column} FROM #{table} WHERE #{column} IS NOT NULL AND #{column} != '' ORDER BY RANDOM() LIMIT 100").flatten
    type = TypeInferrer.new(samples, BoundFinder.new(self, table, column)).make_inference
    puts "Inferring type of #{column} as #{type}"
    return type
  else
    if type == '' || type.nil?
      return 'varchar(255)'
    elsif type.start_with?('float')
      return 'float'
    else
      return type
    end
  end
end