diff --git a/src/backend/database.py b/src/backend/database.py index a7c9b33..5aa7561 100644 --- a/src/backend/database.py +++ b/src/backend/database.py @@ -27,6 +27,8 @@ from src.logic.constants import SEMAP_MEDIA_ACCOUNTS from src.logic.dataclass import ApparatData, BookData from src.logic.log import MyLogger from src.utils import create_blob, dump_pickle, load_pickle +from src.backend.semester import generateSemesterByDate +from icecream import ic config = OmegaConf.load("config.yaml") ascii_lowercase = "abcdefghijklmnopqrstuvwxyz0123456789)" @@ -63,11 +65,11 @@ class Database: def checkDatabaseStatus(self): path = config.database.path path = path.replace("~", str(Path.home())) - print(path) + # print(path) path = os.path.abspath(path) if not os.path.exists(path): # create path - print(path) + # print(path) os.makedirs(path) if self.get_db_contents() == []: self.logger.log_critical("Database does not exist, creating tables") @@ -193,11 +195,14 @@ class Database: # log_message = f"Querying database with query {query}" self.logger.log_info(log_message) - - cursor.execute(query, args) - rv = cursor.fetchall() - conn.commit() - self.close_connection(conn) + try: + cursor.execute(query, args) + rv = cursor.fetchall() + conn.commit() + self.close_connection(conn) + except sql.OperationalError as e: + self.logger.log_error(f"Error in query: {e}") + return None return (rv[0] if rv else None) if one else rv # Books @@ -217,11 +222,12 @@ class Database: t_query = ( f"SELECT bookdata FROM media WHERE app_id={app_id} AND prof_id={prof_id}" ) - # print(t_query) + self.logger.log_info(t_query) + # # print(t_query) result = cursor.execute(t_query).fetchall() result = [load_pickle(i[0]) for i in result] if bookdata in result: - print("Bookdata already in database") + # print("Bookdata already in database") # check if the book was deleted in the apparat query = ( "SELECT deleted FROM media WHERE app_id=? AND prof_id=? AND bookdata=?" @@ -229,7 +235,7 @@ class Database: params = (app_id, prof_id, dump_pickle(bookdata)) result = cursor.execute(query, params).fetchone() if result[0] == 1: - print("Book was deleted, updating bookdata") + # print("Book was deleted, updating bookdata") query = "UPDATE media SET deleted=0 WHERE app_id=? AND prof_id=? AND bookdata=?" params = (app_id, prof_id, dump_pickle(bookdata)) cursor.execute(query, params) @@ -242,6 +248,8 @@ class Database: converted = dump_pickle(bookdata) params = (converted, app_id, prof_id, 0) cursor.execute(query, params) + logMessage = f"Added book with signature {bookdata.signature} to database, data: {converted}" + self.logger.log_info(logMessage) conn.commit() self.close_connection(conn) @@ -406,6 +414,8 @@ class Database: f"SELECT id,bookdata,available FROM media WHERE (app_id={app_id} AND prof_id={prof_id}) AND (deleted={deleted if deleted == 0 else '1 OR deleted=0'})" ) ret_result = [] + if qdata is None: + return [] for result_a in qdata: data = {"id": int, "bookdata": BookData, "available": int} data["id"] = result_a[0] @@ -422,9 +432,9 @@ class Database: book_id (str): The id of the book bookdata (BookData): The new metadata of the book """ - self.query_db( - "UPDATE media SET bookdata=? WHERE id=?", (dump_pickle(bookdata), book_id) - ) + query = "UPDATE media SET bookdata= ? WHERE id=?" + book = dump_pickle(bookdata) + self.query_db(query, (book, book_id)) def deleteBook(self, book_id): """ @@ -497,7 +507,7 @@ class Database: delete=False, dir=tempdir_path, mode="wb", suffix=f".{filetype}" ) file.write(blob) - print("file created") + # print("file created") return file.name def getFiles(self, app_id: Union[str, int], prof_id: int) -> list[tuple]: @@ -525,7 +535,7 @@ class Database: return [i[0] for i in data] def insertSubjects(self): - print("Inserting subjects") + # print("Inserting subjects") subjects = [ "Biologie", "Chemie", @@ -677,42 +687,9 @@ class Database: )[0] return f"{title} " if title is not None else "" - def getProfByName(self, prof_name: str) -> tuple: - """get all the data of a professor based on the name - - Args: - prof_name (str): the name of the professor - - Returns: - tuple: the data of the professor - """ - return self.query_db( - "SELECT * FROM prof WHERE fullname=?", (prof_name,), one=True - ) - - def getProfId(self, prof_name: str) -> Optional[int]: - """Get the id of a professor based on the name - - Args: - prof_name (str): the name of the professor - - Returns: - Optional[int]: the id of the professor, if the professor is not found, None is returned - """ - # get list of all current profs - profs = self.getProfs() - if profs == []: - return 1 - data = self.getProfByName(prof_name.replace(",", "")) - if data is None: - # get last used id and return id + 1 - profno = self.query_db("SELECT id FROM prof ORDER BY id DESC", one=True)[0] - return profno + 1 - - # return None - else: - return data[0] + + def getSpecificProfData(self, prof_id: Union[str, int], fields: List[str]) -> tuple: """A customisable function to get specific data of a professor based on the id @@ -746,30 +723,7 @@ class Database: ) return data - def createProf(self, prof_details: dict): - """Create a professor in the database - - Args: - prof_details (dict): a dictionary containing the details of the professor - """ - prof_title = prof_details["prof_title"] - prof_fname = prof_details["profname"].split(",")[1] - prof_fname = prof_fname.strip() - prof_lname = prof_details["profname"].split(",")[0] - prof_lname = prof_lname.strip() - prof_fullname = prof_details["profname"].replace(",", "") - prof_mail = prof_details["prof_mail"] - prof_tel = prof_details["prof_tel"] - params = ( - prof_title, - prof_fname, - prof_lname, - prof_mail, - prof_tel, - prof_fullname, - ) - query = "INSERT OR IGNORE INTO prof (titel, fname, lname, mail, telnr, fullname) VALUES (?, ?, ?, ?, ?, ?)" - self.insertInto(query=query, params=params) + def getProfs(self) -> list[tuple]: """Return all the professors in the database @@ -855,7 +809,7 @@ class Database: if dauerapp: self.query_db( - "UPDATE semesterapparat SET verlängerung_bis=?, dauerapp=? WHERE appnr=?", + "UPDATE semesterapparat SET verlängerung_bis=?, dauer=? WHERE appnr=?", (newDate, dauerapp, app_id), ) else: @@ -893,15 +847,18 @@ class Database: Returns: Optional[int]: the id of the apparat """ - - prof_id = self.getProfId(apparat.profname) + ic(apparat) + prof_id = self.getProfByName(apparat.get_prof_details()["fullname"]) + ic(prof_id, apparat.profname) + if prof_id: + prof_id = prof_id[0] app_id = self.getApparatId(apparat.appname) if app_id: return AppPresentError(app_id) - - self.createProf(apparat.get_prof_details()) - prof_id = self.getProfId(apparat.profname) - # ic(prof_id) + if not prof_id: + prof_id = self.createProf(apparat.get_prof_details()) + # self.getProfId(apparat.profname) + ic(prof_id) query = f"INSERT OR IGNORE INTO semesterapparat (appnr, name, erstellsemester, dauer, prof_id, fach,deletion_status,konto) VALUES ('{apparat.appnr}', '{apparat.appname}', '{apparat.semester}', '{apparat.dauerapp}', {prof_id}, '{apparat.app_fach}', '{0}', '{SEMAP_MEDIA_ACCOUNTS[apparat.appnr]}')" self.logger.log_info(query) self.query_db(query) @@ -1100,6 +1057,7 @@ class Database: Returns: list: the result of the query """ + ic(query) conn = self.connect() cursor = conn.cursor() result = cursor.execute(query).fetchall() @@ -1116,15 +1074,20 @@ class Database: return result if "deletable" in kwargs.keys(): - query = f"SELECT * FROM semesterapparat WHERE deletion_status=0 AND dauer=0 AND (erstellsemester!='{kwargs['deletesemester']}' OR verlängerung_bis!='{kwargs['deletesemester']}')" + query = f"""SELECT * FROM semesterapparat + WHERE deletion_status=0 AND dauer=0 AND + ( + (erstellsemester!='{kwargs['deletesemester']}' AND verlängerung_bis IS NULL) OR + (erstellsemester!='{kwargs['deletesemester']}' AND verlängerung_bis!='{kwargs['deletesemester']}' AND verlängerung_bis!='{generateSemesterByDate(True)}') + )""" return __query(query) if "dauer" in kwargs.keys(): kwargs["dauer"] = kwargs["dauer"].replace("Ja", "1").replace("Nein", "0") query = "SELECT * FROM semesterapparat WHERE " for key, value in kwargs.items() if kwargs.items() is not None else {}: - print(key, value) + # print(key, value) query += f"{key}='{value}' AND " - print(query) + # print(query) # remove deletesemester part from normal query, as this will be added to the database upon deleting the apparat if "deletesemester" in kwargs.keys(): query = query.replace( @@ -1140,7 +1103,7 @@ class Database: query = query.replace( f"endsemester='{kwargs['endsemester']}' AND ", "xyz" ) - print("replaced") + # print("replaced") query = query.replace( "xyz", f"(erstellsemester='{kwargs['endsemester']}' OR verlängerung_bis='{kwargs['endsemester']}') AND ", @@ -1153,9 +1116,9 @@ class Database: query = query[:-1] query = query.strip() - print(query) + # print(query) res = __query(query) - print(res) + # print(res) return res # Admin data @@ -1438,7 +1401,7 @@ class Database: blob = self.query_db( "SELECT fileblob FROM elsa_files WHERE filename=?", (filename,), one=True )[0] - print(blob) + # print(blob) tempdir = config.database.tempdir tempdir = tempdir.replace("~", str(Path.home())) tempdir_path = Path(tempdir) @@ -1448,7 +1411,7 @@ class Database: delete=False, dir=tempdir_path, mode="wb", suffix=f".{filetype}" ) file.write(blob) - print("file created") + # print("file created") return file.name def getElsaApparats(self): @@ -1491,3 +1454,61 @@ class Database: return self.query_db( "SELECT filename, filetyp FROM elsa_files WHERE elsa_id=?", (elsa_id,) ) +### + + + + def createProf(self, profdata): + conn = self.connect() + cursor = conn.cursor() + fname = profdata["profname"].split(", ")[1].strip() + lname = profdata["profname"].split(", ")[0].strip() + fullname = f"{lname} {fname}" + mail = profdata["prof_mail"] + telnr = profdata["prof_tel"] + title = profdata["title"] + + query = f"INSERT INTO prof (fname, lname, fullname, mail, telnr,titel) VALUES ('{fname}','{lname}','{fullname}','{mail}','{telnr}','{title}')" + self.logger.log_info(query) + cursor.execute(query) + + conn.commit() + conn.close() + return self.getProfId(profdata) + + def getProfId(self, profdata): + conn = self.connect() + cursor = conn.cursor() + fname = profdata["profname"].split(", ")[1].strip() + lname = profdata["profname"].split(", ")[0].strip() + fullname = f"{lname} {fname}" + query = f"SELECT id FROM prof WHERE fullname = '{fullname}'" + self.logger.log_info(query) + + cursor.execute(query) + result = cursor.fetchone() + if result: + return result[0] + else: return None + + def getProfByName(self, fullname): + '''Get all Data of the prof based on fullname + + Args: + fullname (str): The full name of the prof + ''' + conn = self.connect() + cursor = conn.cursor() + query = f"SELECT * FROM prof WHERE fullname = '{fullname}'" + self.logger.log_info(query) + + result = cursor.execute(query).fetchone() + if result: + return result + else: return None + def getProfNameByApparat(self, apprarat_id): + query = f"SELECT prof_id from semesterapparat WHERE appnr = '{apprarat_id}'" + data = self.query_db(query) + if data: + return data[0][0] + else: return None \ No newline at end of file diff --git a/src/logic/dataclass.py b/src/logic/dataclass.py index 65801e7..0f4bfaa 100644 --- a/src/logic/dataclass.py +++ b/src/logic/dataclass.py @@ -25,9 +25,11 @@ class ApparatData: "profname": self.profname, "prof_mail": self.prof_mail, "prof_tel": self.prof_tel, - "fullname": self.profname, + "fullname": f"{self.profname.split(',')[0].strip()} {self.profname.split(',')[1].strip()}", } - + def translateToFullname(self): + + return f"{self.profname.split(',')[0].strip()} {self.profname.split(',')[1].strip()}" @dataclass class BookData: