Class: InCSV::Database
- Inherits:
-
Object
- Object
- InCSV::Database
- Defined in:
- lib/incsv/database.rb
Instance Attribute Summary collapse
-
#db ⇒ Object
readonly
Returns the value of attribute db.
Instance Method Summary collapse
- #create_table ⇒ Object
- #db_path ⇒ Object
- #exists? ⇒ Boolean
- #import ⇒ Object
- #imported? ⇒ Boolean
-
#initialize(csv) ⇒ Database
constructor
A new instance of Database.
- #table_created? ⇒ Boolean
- #table_name ⇒ Object
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
#db ⇒ Object (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_table ⇒ Object
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_path ⇒ Object
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
25 26 27 |
# File 'lib/incsv/database.rb', line 25 def exists? File.exist?(db_path) end |
#import ⇒ Object
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
21 22 23 |
# File 'lib/incsv/database.rb', line 21 def imported? table_created? && @db[table_name].count > 0 end |
#table_created? ⇒ Boolean
17 18 19 |
# File 'lib/incsv/database.rb', line 17 def table_created? @db.table_exists?(table_name) end |
#table_name ⇒ Object
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 |