Class: InCSV::Database

Inherits:
Object
  • Object
show all
Defined in:
lib/incsv/database.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(csv) ⇒ Database

Returns a new instance of Database.



7
8
9
10
11
12
13
# File 'lib/incsv/database.rb', line 7

def initialize(csv)
  @csv = csv

  @db = Sequel.sqlite(db_path)
  # require "logger"
  # @db.loggers << Logger.new($stdout)
end

Instance Attribute Details

#dbObject (readonly)

Returns the value of attribute db.



15
16
17
# File 'lib/incsv/database.rb', line 15

def db
  @db
end

Instance Method Details

#create_tableObject



40
41
42
43
44
45
46
47
48
49
50
# File 'lib/incsv/database.rb', line 40

def create_table
  @db.create_table!(table_name) do
    primary_key :_incsv_id
  end

  schema.columns.each do |c|
    @db.alter_table(table_name) do
      add_column c.name, c.type.for_database
    end
  end
end

#db_pathObject



29
30
31
32
# File 'lib/incsv/database.rb', line 29

def db_path
  path = Pathname(csv)
  (path.dirname + (path.basename(".csv").to_s + ".db")).to_s
end

#exists?Boolean

Returns:

  • (Boolean)


25
26
27
# File 'lib/incsv/database.rb', line 25

def exists?
  File.exist?(db_path)
end

#importObject



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/incsv/database.rb', line 52

def import
  return if imported?

  create_table unless table_created?

  columns      = schema.columns
  column_names = columns.map(&:name)

  chunks(200) do |chunk|
    rows = chunk.map do |row|
      row.to_hash.values.each_with_index.map do |column, n|
        columns[n].type.clean_value(column)
      end
    end

    @db[table_name].import(column_names, rows)
  end
end

#imported?Boolean

Returns:

  • (Boolean)


21
22
23
# File 'lib/incsv/database.rb', line 21

def imported?
   table_created? && @db[table_name].count > 0
end

#table_created?Boolean

Returns:

  • (Boolean)


17
18
19
# File 'lib/incsv/database.rb', line 17

def table_created?
  @db.table_exists?(table_name)
end

#table_nameObject



34
35
36
37
38
# File 'lib/incsv/database.rb', line 34

def table_name
  @table_name ||= begin
    File.basename(csv, ".csv").downcase.gsub(/[^a-z_]/, "").to_sym
  end
end