Commit 1218bc59 authored by Jiahang Chen's avatar Jiahang Chen
Browse files

update sqlite configuration

parent bad2b8f6
......@@ -216,17 +216,16 @@ def to_string(self, root):
class DataBase:
def __init__(self, db, conf):
def __init__(self, db):
self.__db = db
self.__conf = conf
self.__table_conf = {}
self.__conn = None
def connect(self):
self.__conn = sqlite3.connect(self.__db, check_same_thread=False)
APP_LOGGER.info("Connect to the database {}".format(self.__db))
def build_table(self, table):
def build_table(self, table, configuration):
conf_schema = {
"type": "array",
"items": {
......@@ -239,13 +238,13 @@ def build_table(self, table):
}
}
try:
validate(instance=self.__conf, schema=conf_schema)
validate(instance=configuration, schema=conf_schema)
except jsonschema.ValidationError as e:
APP_LOGGER.error("config json error: {}".format(e))
exec_str = "ID INTEGER PRIMARY KEY AUTOINCREMENT, TIMESTAMP REAL NOT NULL"
for i in self.__conf:
for i in configuration:
name = i["var_name"]
type = i["var_type"]
exec_str += ", {} {}".format(name, type)
......@@ -258,13 +257,15 @@ def build_table(self, table):
except sqlite3.OperationalError as e:
APP_LOGGER.warning(e)
self.__table_conf[table] = configuration
def disconnect(self):
self.__conn.close()
def update(self, table, value_dict):
for key in value_dict.keys():
def_var_name = []
for var in self.__conf:
for var in self.__table_conf.get(table, {}):
def_var_name.append(var["var_name"])
if key not in def_var_name:
raise ValueError("{} is not defined variable name".format(key))
......@@ -272,12 +273,12 @@ def update(self, table, value_dict):
timestamp = time.time()
cursor = self.__conn.cursor()
exec_str = "TIMESTAMP"
for i in self.__conf:
for i in self.__table_conf.get(table):
exec_str += ",{}".format(i["var_name"])
exec_str = "INSERT INTO {} ({})".format(table, exec_str)
value_str = "?"
for i in self.__conf:
for i in self.__table_conf.get(table, {}):
if isinstance(value_dict[i["var_name"]], str):
value_str += ", '{}'".format(value_dict[i["var_name"]])
elif isinstance(value_dict[i["var_name"]], (float, int, bool)):
......@@ -285,6 +286,7 @@ def update(self, table, value_dict):
value_str = "VALUES ({})".format(value_str)
exec_str += value_str
print(exec_str)
try:
cursor.execute(exec_str, (timestamp,))
APP_LOGGER.info("Insert new value to table {}".format(table))
......@@ -313,8 +315,8 @@ def search(self, table):
print("------------------")
print("ID = {}".format(row[0]))
print("TIMESTAMP = {}".format(row[1]))
for i in range(len(self.__conf)):
print("{} = {}".format(self.__conf[i]["var_name"].upper(), row[i + 2]))
for i in range(len(self.__table_conf.get(table, {}))):
print("{} = {}".format(self.__table_conf.get(table)[i]["var_name"].upper(), row[i + 2]))
print("------------------\n\n")
def execute(self, exec_str):
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment