Class: CsvQuery::Database

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

Overview

Wraps a SQLite in-memory database with a single table named csv.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(csv) ⇒ Database

Returns a new instance of Database.



8
9
10
11
12
# File 'lib/csv_query/database.rb', line 8

def initialize(csv)
  @database = SQLite3::Database.new(':memory:')
  @columns = csv.headers
  create_table(@columns)
end

Instance Attribute Details

#databaseObject (readonly)

Returns the value of attribute database.



6
7
8
# File 'lib/csv_query/database.rb', line 6

def database
  @database
end

Instance Method Details

#import_data_from_csv(csv) ⇒ Object



14
15
16
17
18
19
20
21
22
23
# File 'lib/csv_query/database.rb', line 14

def import_data_from_csv(csv)
  columns = csv.headers

  sql = "INSERT INTO csv VALUES (#{(['?'] * columns.size).join(',')})"
  statement = database.prepare(sql)

  csv.each do |row|
    statement.execute(row.fields)
  end
end

#query(sql) ⇒ Object

Returns the results of sql. First row of the resultset contains the column names



26
27
28
# File 'lib/csv_query/database.rb', line 26

def query(sql)
  database.execute2(sql)
end