From 7f8e8d5a9fb10666215c9fc6060215a58f9f8105 Mon Sep 17 00:00:00 2001 From: Pierre-Antoine Rouby <pierre-antoine.rouby@inrae.fr> Date: Wed, 22 Nov 2023 14:58:03 +0100 Subject: [PATCH] SQL: Minor change and add exception handler. --- src/Model/Study.py | 7 +++++++ src/tools.py | 22 ++++++++++++++++------ 2 files changed, 23 insertions(+), 6 deletions(-) diff --git a/src/Model/Study.py b/src/Model/Study.py index 331a32c2..e9ccdb41 100644 --- a/src/Model/Study.py +++ b/src/Model/Study.py @@ -177,6 +177,13 @@ class Study(SQLModel): # SQL # ####### + def _db_insert_into_info(self, key, value, commit=False): + self.execute( + "INSERT INTO info VALUES " + + f"('{key}', '{self._db_format(value)}')", + commit=commit + ) + def _create(self): # Info (metadata) self.execute( diff --git a/src/tools.py b/src/tools.py index d3c2ddcc..1b778439 100644 --- a/src/tools.py +++ b/src/tools.py @@ -312,20 +312,30 @@ class SQL(object): def _db_format(self, value): # Replace ''' by ''' to preserve SQL injection - if value is str: + if type(value) is str: value = value.replace("'", "'") return value @timer def execute(self, cmd, fetch_one=True, commit=False): logger.debug(f"SQL - {cmd}") - res = self._cur.execute(cmd) - if commit: - self._db.commit() + value = None + try: + res = self._cur.execute(cmd) - value = self._fetch(res, fetch_one) - return value + if commit: + self._db.commit() + + value = self._fetch(res, fetch_one) + except Exception as e: + logger.error( + f"[{Fore.RED}ERROR{Style.RESET_ALL}] " + + f"{Fore.RED}{e}{Style.RESET_ALL}" + ) + traceback.print_exc() + finally: + return value def _create(self): logger.warning("TODO: Create") -- GitLab