Class: Kj::Db

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

Class Method Summary collapse

Class Method Details

.dbObject



7
8
9
10
11
12
# File 'lib/kj/db.rb', line 7

def self.db
  @db ||= begin
    path = Pathname(File.absolute_path(__FILE__))
    SQLite3::Database.new(File.join(path.parent.parent.parent.to_s, 'db/kjb.db'))
  end
end

.query(sql, values = [], return_first_record = false) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/kj/db.rb', line 19

def self.query(sql, values=[], return_first_record=false)
  db.results_as_hash = true
  sql.gsub!(/^.{6}/, 'SELECT')
  if return_first_record
    result = db.get_first_row(sql, values)
    result.nil? ? raise(Iniquity, "Not found") : result
  else
    db.execute(sql, values)
  end
  rescue SQLite3::RangeException
    raise Iniquity, "Query out of range"
end

.select(params = {table_name: nil, fields: [], conditions: {}, return_first_record: false, operator: 'AND'}) ⇒ Object



14
15
16
17
# File 'lib/kj/db.rb', line 14

def self.select(params={table_name: nil, fields: [], conditions: {}, return_first_record: false, operator: 'AND'})
  sql = "SELECT %s FROM %s WHERE %s" % [params[:fields].join(','), params[:table_name], params[:conditions].keys.map{|key| "#{key} = ?"}.join(" #{params[:operator]} ")]
  query(sql, params[:conditions].values, params[:limit] == 1)
end