Class: Insight::Database::Table

Inherits:
Object
  • Object
show all
Includes:
Logging
Defined in:
lib/insight/database.rb

Direct Known Subclasses

DataTable, RequestTable

Instance Method Summary collapse

Methods included from Logging

logger

Constructor Details

#initialize(table_name, *keys) ⇒ Table

Returns a new instance of Table.



97
98
99
100
101
102
103
104
# File 'lib/insight/database.rb', line 97

def initialize(table_name, *keys)
  @table_name = table_name
  @keys = keys
  if(execute("select * from sqlite_master where name = ?", table_name).empty?)
    logger.warn{ "Initializing a table called #{table_name}" }
    execute(create_sql)
  end
end

Instance Method Details

#create_keys_clauseObject



84
85
86
# File 'lib/insight/database.rb', line 84

def create_keys_clause
  "#{@keys.map{|key| "#{key} varchar"}.join(", ")}"
end

#create_sqlObject



88
89
90
# File 'lib/insight/database.rb', line 88

def create_sql
  "create table #@table_name ( id integer primary key, #{create_keys_clause} )"
end

#dbObject



80
81
82
# File 'lib/insight/database.rb', line 80

def db
  Insight::Database.db
end

#execute(*args) ⇒ Object



92
93
94
95
# File 'lib/insight/database.rb', line 92

def execute(*args)
  logger.info{ ins_args = args.inspect; "(#{[ins_args.length,120].min}/#{ins_args.length})" + ins_args[0..120] }
  db.execute(*args)
end

#fields_sqlObject



110
111
112
# File 'lib/insight/database.rb', line 110

def fields_sql
  "#{@keys.join(",")}"
end

#insert(values_sql) ⇒ Object



114
115
116
# File 'lib/insight/database.rb', line 114

def insert(values_sql)
  execute("insert into #@table_name(#{fields_sql}) values (#{values_sql})")
end

#keys(name) ⇒ Object



118
119
120
# File 'lib/insight/database.rb', line 118

def keys(name)
  execute("select #{name} from #@table_name").flatten
end

#length(where = "1 = 1") ⇒ Object



122
123
124
# File 'lib/insight/database.rb', line 122

def length(where = "1 = 1")
  execute("select count(1) from #@table_name where #{where}").first.first
end

#select(which_sql, condition_sql) ⇒ Object



106
107
108
# File 'lib/insight/database.rb', line 106

def select(which_sql, condition_sql)
  execute("select #{which_sql} from #@table_name where #{condition_sql}")
end

#to_aObject



126
127
128
# File 'lib/insight/database.rb', line 126

def to_a
  execute("select * from #@table_name")
end