Refactor & more TableModel functions

master
E. Almqvist 3 years ago
parent 6f4008950e
commit 9e1bf5a520
  1. 38
      src/db_models.rb

@ -4,28 +4,42 @@ class TableModel # Base model
@table_name = table_name
end
private def gen_update_query(varhash, values)
qstr = ""
varhash.each do |val, var|
qstr += "#{var} = #{val}, "
end
private def gen_update_query(vars) # generates part of the update query string
vars.join "= ?, "
end
private def gen_insert_query(vars) # generates part of the insert query string
entstr = "(#{vars.join ", "})"
valstr = "(#{(["?"] * vars.length).join ", "})"
return entstr, valstr
end
return qstr
private def query(q, *args) # query table with query string
db_handle.execute( q, *args )
end
private def get(attr, filter="")
db = db_handle # get the db handle
private def get(attr, filter="") # get data from table
query = "SELECT #{attr} FROM #{@table_name} " # create the query string
if filter != "" then query += "WHERE #{filter}" end
db.execute query
self.query query # execute query
end
private def set(attr, filter="")
private def update(attr, data, filter="")
self.query( "UPDATE #{@table_name} SET #{ self.gen_update_query(data.keys) } WHERE #{filter}", *data.values )
end
private def insert(attr, data, filter="")
entstr, valstr = gen_insert_query data.keys
self.query( "INSERT INTO #{@table_name} #{entstr} VALUES #{valstr}", *data.values )
end
private def set(attr, data={}, filter="") # slow, shouldn't really be used
if self.get(attr, filter).length > 0 then
query = "UPDATE #{attr} SET var = ?, var2 = ?"
self.update(attr, data, filter)
else
self.insert(attr, data, filter)
end
end
end

Loading…
Cancel
Save