Class: CSVLite

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(db = nil) ⇒ CSVLite

Returns a new instance of CSVLite.



19
20
21
22
23
24
25
26
# File 'lib/csvlite.rb', line 19

def initialize(db = nil)
  if db.nil?
    @db = SQLite3::Database.new(':memory:')
  else
    raise "Not SQLite 3 DB" unless db.is_a? SQLite3::Database
    @db = db
  end
end

Instance Attribute Details

#dbObject (readonly)

Returns the value of attribute db.



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

def db
  @db
end

Class Method Details

.query_files(csv_files, query) ⇒ Object



58
59
60
61
62
# File 'lib/csvlite.rb', line 58

def self.query_files(csv_files, query)
  lite = CSVLite.new
  lite.load_multiple(csv_files)
  lite.query(query)
end

Instance Method Details

#load_from_csv_file(csv_file, table_name = nil) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/csvlite.rb', line 28

def load_from_csv_file(csv_file, table_name = nil)
  if table_name.nil?
    extn = File.extname  csv_file
    name = File.basename csv_file, extn
    table_name = name
  end

  table_name = table_name.underscore

  rows = CSV.read(csv_file)
  header = rows.shift
  create_statement = _build_table_schema(table_name, header, rows)
  @db.execute create_statement
  _bulk_insert(table_name, header, rows)

  @db
end

#load_multiple(csv_files) ⇒ Object



46
47
48
49
50
51
52
# File 'lib/csvlite.rb', line 46

def load_multiple(csv_files)
  [csv_files].flatten.each do |file|
    self.load_from_csv_file(file)
  end

  @db
end

#query(query) ⇒ Object



54
55
56
# File 'lib/csvlite.rb', line 54

def query(query)
  @db.execute query
end