proper formatting

This commit is contained in:
WorldTeacher
2024-02-22 21:31:54 +01:00
parent 16430705cb
commit 67d782e1b3

View File

@@ -3,16 +3,28 @@ import os
import re
import sqlite3 as sql
import tempfile
from src.logic.log import MyLogger
from icecream import ic
from typing import List, Tuple, Dict, Any, Optional, Union
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple, Union
from icecream import ic
from omegaconf import OmegaConf
from src.backend.db import CREATE_TABLE_APPARAT, CREATE_TABLE_MESSAGES, CREATE_TABLE_MEDIA, CREATE_TABLE_APPKONTOS, CREATE_TABLE_FILES, CREATE_TABLE_PROF, CREATE_TABLE_USER, CREATE_TABLE_SUBJECTS
from src.backend.db import (
CREATE_TABLE_APPARAT,
CREATE_TABLE_APPKONTOS,
CREATE_TABLE_FILES,
CREATE_TABLE_MEDIA,
CREATE_TABLE_MESSAGES,
CREATE_TABLE_PROF,
CREATE_TABLE_SUBJECTS,
CREATE_TABLE_USER,
)
from src.errors import AppPresentError, NoResultError
from src.logic.constants import SEMAP_MEDIA_ACCOUNTS
from src.logic.dataclass import ApparatData, BookData
from src.errors import NoResultError, AppPresentError
from src.utils import load_pickle, dump_pickle,create_blob
from src.logic.log import MyLogger
from src.utils import create_blob, dump_pickle, load_pickle
config = OmegaConf.load("config.yaml")
logger = MyLogger(__name__)
@@ -21,7 +33,8 @@ class Database:
"""
Initialize the database and create the tables if they do not exist.
"""
def __init__(self, db_path: str = None):
def __init__(self, db_path: str = "sap.db"):
"""
Default constructor for the database class
@@ -36,6 +49,7 @@ class Database:
if self.get_db_contents() is None:
logger.log_critical("Database does not exist, creating tables")
self.create_tables()
def get_db_contents(self) -> Union[List[Tuple], None]:
"""
Get the contents of the
@@ -50,6 +64,7 @@ class Database:
return cursor.fetchall()
except sql.OperationalError:
return None
def connect(self) -> sql.Connection:
"""
Connect to the database
@@ -57,7 +72,9 @@ class Database:
Returns:
sql.Connection: The active connection to the database
"""
print(self.db_path)
return sql.connect(self.db_path)
def close_connection(self, conn: sql.Connection):
"""
closes the connection to the database
@@ -67,6 +84,7 @@ class Database:
- conn (sql.Connection): the connection to be closed
"""
conn.close()
def create_tables(self):
"""
Create the tables in the database
@@ -83,6 +101,7 @@ class Database:
cursor.execute(CREATE_TABLE_SUBJECTS)
conn.commit()
self.close_connection(conn)
def insertInto(self, query: str, params: Tuple) -> None:
"""
Insert sent data into the database
@@ -97,7 +116,10 @@ class Database:
cursor.execute(query, params)
conn.commit()
self.close_connection(conn)
def query_db(self, query: str, args: Tuple = (), one: bool = False)->Union[Tuple, List[Tuple]]:
def query_db(
self, query: str, args: Tuple = (), one: bool = False
) -> Union[Tuple, List[Tuple]]:
"""
Query the Database for the sent query.
@@ -119,7 +141,9 @@ class Database:
return (rv[0] if rv else None) if one else rv
# Books
def addBookToDatabase(self, bookdata:BookData,app_id:Union[str,int], prof_id:Union[str,int]):
def addBookToDatabase(
self, bookdata: BookData, app_id: Union[str, int], prof_id: Union[str, int]
):
"""
Add books to the database. Both app_id and prof_id are required to add the book to the database, as the app_id and prof_id are used to select the books later on.
@@ -160,7 +184,10 @@ class Database:
cursor.execute(query, params)
conn.commit()
self.close_connection(conn)
def getBookIdBasedOnSignature(self, app_id:Union[str,int], prof_id:Union[str,int],signature:str)->int:
def getBookIdBasedOnSignature(
self, app_id: Union[str, int], prof_id: Union[str, int], signature: str
) -> int:
"""
Get a book id based on the signature of the book.
@@ -172,11 +199,17 @@ class Database:
Returns:
int: The id of the book
"""
result = self.query_db("SELECT bookdata, id FROM media WHERE app_id=? AND prof_id=?", (app_id,prof_id))
result = self.query_db(
"SELECT bookdata, id FROM media WHERE app_id=? AND prof_id=?",
(app_id, prof_id),
)
books = [(load_pickle(i[0]), i[1]) for i in result]
book = [i for i in books if i[0].signature == signature][0][1]
return book
def getBookBasedOnSignature(self, app_id:Union[str,int], prof_id:Union[str,int],signature:str)->BookData:
def getBookBasedOnSignature(
self, app_id: Union[str, int], prof_id: Union[str, int], signature: str
) -> BookData:
"""
Get the book based on the signature of the book.
@@ -188,10 +221,13 @@ class Database:
Returns:
BookData: The total metadata of the book wrapped in a BookData object
"""
result = self.query_db("SELECT bookdata FROM media WHERE app_id=? AND prof_id=?", (app_id,prof_id))
result = self.query_db(
"SELECT bookdata FROM media WHERE app_id=? AND prof_id=?", (app_id, prof_id)
)
books = [load_pickle(i[0]) for i in result]
book = [i for i in books if i.signature == signature][0]
return book
def getLastBookId(self) -> int:
"""
Get the last book id in the database
@@ -200,6 +236,7 @@ class Database:
int: ID of the last book in the database
"""
return self.query_db("SELECT id FROM media ORDER BY id DESC", one=True)[0]
def searchBook(self, data: dict[str, str]) -> list[tuple[BookData, int]]:
"""
Search a book in the database based on the sent data.
@@ -236,10 +273,14 @@ class Database:
if data["title"] in bookdata.title:
ret.append((bookdata, app_id, prof_id))
elif mode == 3:
if data["signature"] in bookdata.signature and data["title"] in bookdata.title:
if (
data["signature"] in bookdata.signature
and data["title"] in bookdata.title
):
ret.append((bookdata, app_id, prof_id))
ic(ret)
return ret
def setAvailability(self, book_id: str, available: str):
"""
Set the availability of a book in the database
@@ -249,7 +290,10 @@ class Database:
available (str): The availability of the book
"""
self.query_db("UPDATE media SET available=? WHERE id=?", (available, book_id))
def getBookId(self, bookdata:BookData, app_id:Union[str,int], prof_id:Union[str,int])->int:
def getBookId(
self, bookdata: BookData, app_id: Union[str, int], prof_id: Union[str, int]
) -> int:
"""
Get the id of a book based on the metadata of the book
@@ -261,8 +305,13 @@ class Database:
Returns:
int: ID of the book
"""
result = self.query_db("SELECT id FROM media WHERE bookdata=? AND app_id=? AND prof_id=?", (dump_pickle(bookdata),app_id,prof_id), one=True)
result = self.query_db(
"SELECT id FROM media WHERE bookdata=? AND app_id=? AND prof_id=?",
(dump_pickle(bookdata), app_id, prof_id),
one=True,
)
return result[0]
def getBook(self, book_id: int) -> BookData:
"""
Get the book based on the id in the database
@@ -273,8 +322,15 @@ class Database:
Returns:
BookData: The metadata of the book wrapped in a BookData object
"""
return load_pickle(self.query_db("SELECT bookdata FROM media WHERE id=?", (book_id,), one=True)[0])
def getBooks(self, app_id:Union[str,int], prof_id:Union[str,int], deleted=0)->list[dict[int, BookData, int]]:
return load_pickle(
self.query_db(
"SELECT bookdata FROM media WHERE id=?", (book_id,), one=True
)[0]
)
def getBooks(
self, app_id: Union[str, int], prof_id: Union[str, int], deleted=0
) -> list[dict[int, BookData, int]]:
"""
Get the Books based on the apparat id and the professor id
@@ -286,7 +342,9 @@ class Database:
Returns:
list[dict[int, BookData, int]]: A list of dictionaries containing the id, the metadata of the book and the availability of the book
"""
qdata = self.query_db(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'})")
qdata = self.query_db(
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 = []
for result_a in qdata:
data = {"id": int, "bookdata": BookData, "available": int}
@@ -295,6 +353,7 @@ class Database:
data["available"] = result_a[2]
ret_result.append(data)
return ret_result
def updateBookdata(self, book_id, bookdata: BookData):
"""
Update the bookdata in the database
@@ -303,7 +362,10 @@ 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))
self.query_db(
"UPDATE media SET bookdata=? WHERE id=?", (dump_pickle(bookdata), book_id)
)
def deleteBook(self, book_id):
"""
Delete a book from the database
@@ -325,8 +387,15 @@ class Database:
Returns:
bytes: The file stored in
"""
return self.query_db("SELECT fileblob FROM files WHERE filename=? AND app_id=?", (filename,app_id), one=True)[0]
def insertFile(self, file: list[dict], app_id:Union[str,int], prof_id:Union[str,int]):
return self.query_db(
"SELECT fileblob FROM files WHERE filename=? AND app_id=?",
(filename, app_id),
one=True,
)[0]
def insertFile(
self, file: list[dict], app_id: Union[str, int], prof_id: Union[str, int]
):
"""Instert a list of files into the database
Args:
@@ -344,7 +413,10 @@ class Database:
blob = create_blob(path)
query = "INSERT OR IGNORE INTO files (filename, fileblob, app_id, filetyp,prof_id) VALUES (?, ?, ?, ?,?)"
self.query_db(query, (filename, blob, app_id, filetyp, prof_id))
def recreateFile(self, filename:str, app_id:Union[str,int],filetype:str)->str:
def recreateFile(
self, filename: str, app_id: Union[str, int], filetype: str
) -> str:
"""Recreate a file from the database
Args:
@@ -367,6 +439,7 @@ class Database:
file.write(blob)
print("file created")
return file.name
def getFiles(self, app_id: Union[str, int], prof_id: int) -> list[tuple]:
"""Get all the files associated with the apparat and the professor
@@ -377,7 +450,10 @@ class Database:
Returns:
list[tuple]: a list of tuples containing the filename and the filetype for the corresponding apparat and professor
"""
return self.query_db("SELECT filename, filetyp FROM files WHERE app_id=? AND prof_id=?", (app_id,prof_id))
return self.query_db(
"SELECT filename, filetyp FROM files WHERE app_id=? AND prof_id=?",
(app_id, prof_id),
)
def getSemersters(self) -> list[str]:
"""Return all the unique semesters in the database
@@ -405,10 +481,18 @@ class Database:
user (str): the user who added the message
app_id (Union[str,int]): the id of the apparat
"""
def __getUserId(user):
return self.query_db("SELECT id FROM user WHERE username=?", (user,), one=True)[0]
return self.query_db(
"SELECT id FROM user WHERE username=?", (user,), one=True
)[0]
user_id = __getUserId(user)
self.query_db("INSERT INTO messages (message, user_id, remind_at,appnr) VALUES (?,?,?,?)", (message["message"],user_id,message["remind_at"],app_id))
self.query_db(
"INSERT INTO messages (message, user_id, remind_at,appnr) VALUES (?,?,?,?)",
(message["message"], user_id, message["remind_at"], app_id),
)
def getMessages(self, date: str) -> list[dict[str, str, str, str]]:
"""Get all the messages for a specific date
@@ -418,19 +502,19 @@ class Database:
Returns:
list[dict[str, str, str, str]]: a list of dictionaries containing the message, the user who added the message, the apparat id and the id of the message
"""
def __get_user_name(user_id):
return self.query_db("SELECT username FROM user WHERE id=?", (user_id,), one=True)[0]
return self.query_db(
"SELECT username FROM user WHERE id=?", (user_id,), one=True
)[0]
messages = self.query_db("SELECT * FROM messages WHERE remind_at=?", (date,))
ret = [
{
"message": i[2],
"user": __get_user_name(i[4]),
"appnr": i[5],
"id": i[0]
}
{"message": i[2], "user": __get_user_name(i[4]), "appnr": i[5], "id": i[0]}
for i in messages
]
return ret
def deleteMessage(self, message_id):
"""Delete a message from the database
@@ -450,11 +534,14 @@ class Database:
Returns:
str: The name of the professor
"""
prof = self.query_db("SELECT fullname FROM prof WHERE id=?", (prof_id,), one=True)
prof = self.query_db(
"SELECT fullname FROM prof WHERE id=?", (prof_id,), one=True
)
if add_title:
return f"{self.getTitleById(prof_id)}{prof[0]}"
else:
return prof[0]
def getTitleById(self, prof_id: Union[str, int]) -> str:
"""get the title of a professor based on the id
@@ -464,8 +551,11 @@ class Database:
Returns:
str: the title of the professor, with an added whitespace at the end, if no title is present, an empty string is returned
"""
title = self.query_db("SELECT titel FROM prof WHERE id=?", (prof_id,), one=True)[0]
title = self.query_db(
"SELECT titel FROM prof WHERE id=?", (prof_id,), one=True
)[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
@@ -475,7 +565,10 @@ class Database:
Returns:
tuple: the data of the professor
"""
return self.query_db("SELECT * FROM prof WHERE fullname=?", (prof_name,), one=True)
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
@@ -491,6 +584,7 @@ class Database:
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
@@ -507,6 +601,7 @@ class Database:
query = query[:-1]
query += " FROM prof WHERE id=?"
return self.query_db(query, (prof_id,), one=True)[0]
def getProfData(self, profname: str):
"""Get mail, telephone number and title of a professor based on the name
@@ -516,8 +611,13 @@ class Database:
Returns:
tuple: the mail, telephone number and title of the professor
"""
data = self.query_db("SELECT mail, telnr, titel FROM prof WHERE fullname=?", (profname.replace(",",""),), one=True)
data = self.query_db(
"SELECT mail, telnr, titel FROM prof WHERE fullname=?",
(profname.replace(",", ""),),
one=True,
)
return data
def createProf(self, prof_details: dict):
"""Create a professor in the database
@@ -532,9 +632,17 @@ class Database:
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)
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
@@ -553,7 +661,10 @@ class Database:
Returns:
list[tuple]: a list of tuples containing the apparats
"""
return self.query_db("SELECT * FROM semesterapparat WHERE deletion_status=?", (deleted,))
return self.query_db(
"SELECT * FROM semesterapparat WHERE deletion_status=?", (deleted,)
)
def getApparatData(self, appnr, appname) -> ApparatData:
"""Get the Apparat data based on the apparat number and the name
@@ -567,7 +678,11 @@ class Database:
Returns:
ApparatData: the appended data of the apparat wrapped in an ApparatData object
"""
result = self.query_db("SELECT * FROM semesterapparat WHERE appnr=? AND name=?", (appnr,appname), one=True)
result = self.query_db(
"SELECT * FROM semesterapparat WHERE appnr=? AND name=?",
(appnr, appname),
one=True,
)
if result is None:
raise NoResultError("No result found")
apparat = ApparatData()
@@ -586,16 +701,20 @@ class Database:
apparat.apparat_adis_id = result[11]
apparat.prof_adis_id = result[12]
return apparat
def getUnavailableApparatNumbers(self) -> List[int]:
"""Get a list of all the apparat numbers in the database that are currently in use
Returns:
List[int]: the list of used apparat numbers
"""
numbers = self.query_db("SELECT appnr FROM semesterapparat WHERE deletion_status=0")
numbers = self.query_db(
"SELECT appnr FROM semesterapparat WHERE deletion_status=0"
)
numbers = [i[0] for i in numbers]
logger.log_info(f"Currently used apparat numbers: {numbers}")
return numbers
def setNewSemesterDate(self, app_id: Union[str, int], newDate, dauerapp=False):
"""Set the new semester date for an apparat
@@ -606,9 +725,15 @@ class Database:
"""
date = datetime.datetime.strptime(newDate, "%d.%m.%Y").strftime("%Y-%m-%d")
if dauerapp:
self.query_db("UPDATE semesterapparat SET verlängerung_bis=?, dauerapp=? WHERE appnr=?", (date,dauerapp,app_id))
self.query_db(
"UPDATE semesterapparat SET verlängerung_bis=?, dauerapp=? WHERE appnr=?",
(date, dauerapp, app_id),
)
else:
self.query_db("UPDATE semesterapparat SET endsemester=? WHERE appnr=?", (date,app_id))
self.query_db(
"UPDATE semesterapparat SET endsemester=? WHERE appnr=?", (date, app_id)
)
def getApparatId(self, apparat_name) -> Optional[int]:
"""get the id of an apparat based on the name
@@ -618,11 +743,14 @@ class Database:
Returns:
Optional[int]: the id of the apparat, if the apparat is not found, None is returned
"""
data = self.query_db("SELECT appnr FROM semesterapparat WHERE name=?", (apparat_name,), one=True)
data = self.query_db(
"SELECT appnr FROM semesterapparat WHERE name=?", (apparat_name,), one=True
)
if data is None:
return None
else:
return data[0]
def createApparat(self, apparat: ApparatData) -> int:
"""create the apparat in the database
@@ -648,6 +776,7 @@ class Database:
logger.log_info(query)
self.query_db(query)
return self.getApparatId(apparat.appname)
def getApparatsByProf(self, prof_id: Union[str, int]) -> list[tuple]:
"""Get all apparats based on the professor id
@@ -657,7 +786,10 @@ class Database:
Returns:
list[tuple]: a list of tuples containing the apparats
"""
return self.query_db("SELECT * FROM semesterapparat WHERE prof_id=?", (prof_id,))
return self.query_db(
"SELECT * FROM semesterapparat WHERE prof_id=?", (prof_id,)
)
def getApparatsBySemester(self, semester: str) -> dict[list]:
"""get all apparats based on the semester
@@ -667,7 +799,10 @@ class Database:
Returns:
dict[list]: a list off all created and deleted apparats for the selected semester
"""
data = self.query_db("SELECT name, prof_id FROM semesterapparat WHERE erstellsemester=?", (semester,))
data = self.query_db(
"SELECT name, prof_id FROM semesterapparat WHERE erstellsemester=?",
(semester,),
)
conn = self.connect()
cursor = conn.cursor()
c_tmp = []
@@ -695,6 +830,7 @@ class Database:
d_ret[i[1]].append(i[0])
self.close_connection(conn)
return {"created": c_ret, "deleted": d_ret}
def getApparatCountBySemester(self) -> tuple[list[str], list[int]]:
"""get a list of all apparats created and deleted by semester
@@ -725,6 +861,7 @@ class Database:
ret.append(e_tuple)
self.close_connection(conn)
return ret
def deleteApparat(self, app_id: Union[str, int], semester: str):
"""Delete an apparat from the database
@@ -732,7 +869,11 @@ class Database:
app_id (Union[str, int]): the id of the apparat
semester (str): the semester the apparat should be deleted from
"""
self.query_db("UPDATE semesterapparat SET deletion_status=1, deleted_date=? WHERE appnr=?", (semester,app_id))
self.query_db(
"UPDATE semesterapparat SET deletion_status=1, deleted_date=? WHERE appnr=?",
(semester, app_id),
)
def isEternal(self, id):
"""check if the apparat is eternal (dauerapparat)
@@ -742,7 +883,10 @@ class Database:
Returns:
int: the state of the apparat
"""
return self.query_db("SELECT dauer FROM semesterapparat WHERE appnr=?", (id,), one=True)
return self.query_db(
"SELECT dauer FROM semesterapparat WHERE appnr=?", (id,), one=True
)
def getApparatName(self, app_id: Union[str, int], prof_id: Union[str, int]):
"""get the name of the apparat based on the id
@@ -753,7 +897,12 @@ class Database:
Returns:
str: the name of the apparat
"""
return self.query_db("SELECT name FROM semesterapparat WHERE appnr=? AND prof_id=?", (app_id,prof_id), one=True)[0]
return self.query_db(
"SELECT name FROM semesterapparat WHERE appnr=? AND prof_id=?",
(app_id, prof_id),
one=True,
)[0]
def updateApparat(self, apparat_data: ApparatData):
"""Update an apparat in the database
@@ -769,6 +918,7 @@ class Database:
apparat_data.appnr,
)
self.query_db(query, params)
def checkApparatExists(self, apparat_name: str):
"""check if the apparat is already present in the database based on the name
@@ -778,7 +928,16 @@ class Database:
Returns:
bool: True if the apparat is present, False if not
"""
return True if self.query_db("SELECT appnr FROM semesterapparat WHERE name=?", (apparat_name,), one=True) else False
return (
True
if self.query_db(
"SELECT appnr FROM semesterapparat WHERE name=?",
(apparat_name,),
one=True,
)
else False
)
def checkApparatExistsById(self, app_id: Union[str, int]) -> bool:
"""a check to see if the apparat is already present in the database, based on the id
@@ -788,11 +947,18 @@ class Database:
Returns:
bool: True if the apparat is present, False if not
"""
return True if self.query_db("SELECT appnr FROM semesterapparat WHERE appnr=?", (app_id,), one=True) else False
return (
True
if self.query_db(
"SELECT appnr FROM semesterapparat WHERE appnr=?", (app_id,), one=True
)
else False
)
# Statistics
def statistic_request(self, **kwargs: Any):
"""Take n amount of kwargs and return the result of the query
"""
"""Take n amount of kwargs and return the result of the query"""
def __query(query):
"""execute the query and return the result
@@ -815,6 +981,7 @@ class Database:
result[result.index(orig_value)] = result_a
self.close_connection(conn)
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']}')"
return __query(query)
@@ -854,6 +1021,7 @@ class Database:
def getUser(self):
"""Get a single user from the database"""
return self.query_db("SELECT * FROM user", one=True)
def getUsers(self) -> list[tuple]:
"""Return a list of tuples of all the users in the database"""
return self.query_db("SELECT * FROM user")
@@ -869,15 +1037,20 @@ class Database:
Returns:
bool: True if the login was successful, False if not
"""
salt = self.query_db("SELECT salt FROM user WHERE username=?", (user,), one=True)[0]
salt = self.query_db(
"SELECT salt FROM user WHERE username=?", (user,), one=True
)[0]
if salt is None:
return False
hashed_password = salt + hashed_password
password = self.query_db("SELECT password FROM user WHERE username=?", (user,), one=True)[0]
password = self.query_db(
"SELECT password FROM user WHERE username=?", (user,), one=True
)[0]
if password == hashed_password:
return True
else:
return False
def changePassword(self, user, new_password):
"""change the password of a user.
The password will be added with the salt and then committed to the database
@@ -886,9 +1059,14 @@ class Database:
user (str): username
new_password (str): the hashed password
"""
salt = self.query_db("SELECT salt FROM user WHERE username=?", (user,), one=True)[0]
salt = self.query_db(
"SELECT salt FROM user WHERE username=?", (user,), one=True
)[0]
new_password = salt + new_password
self.query_db("UPDATE user SET password=? WHERE username=?", (new_password,user))
self.query_db(
"UPDATE user SET password=? WHERE username=?", (new_password, user)
)
def getRole(self, user):
"""get the role of the user
@@ -898,7 +1076,10 @@ class Database:
Returns:
str: the name of the role
"""
return self.query_db("SELECT role FROM user WHERE username=?", (user,), one=True)[0]
return self.query_db(
"SELECT role FROM user WHERE username=?", (user,), one=True
)[0]
def getRoles(self) -> list[tuple]:
"""get all the roles in the database
@@ -906,6 +1087,7 @@ class Database:
list[str]: a list of all the roles
"""
return self.query_db("SELECT role FROM user")
def checkUsername(self, user) -> bool:
"""a check to see if the username is already present in the database
@@ -915,8 +1097,11 @@ class Database:
Returns:
bool: True if the username is present, False if not
"""
data = self.query_db("SELECT username FROM user WHERE username=?", (user,), one=True)
data = self.query_db(
"SELECT username FROM user WHERE username=?", (user,), one=True
)
return True if data is not None else False
def createUser(self, user, password, role, salt):
"""create an user from the AdminCommands class.
@@ -926,7 +1111,11 @@ class Database:
role (str): the role of the user
salt (str): a salt for the password
"""
self.query_db("INSERT OR IGNORE INTO user (username, password, role, salt) VALUES (?,?,?,?)", (user,password,role,salt))
self.query_db(
"INSERT OR IGNORE INTO user (username, password, role, salt) VALUES (?,?,?,?)",
(user, password, role, salt),
)
def deleteUser(self, user):
"""delete an unser
@@ -934,6 +1123,7 @@ class Database:
user (str): username of the user
"""
self.query_db("DELETE FROM user WHERE username=?", (user,))
def updateUser(self, username, data: dict[str, str]):
"""changge the data of a user
@@ -954,6 +1144,7 @@ class Database:
cursor.execute(query, params)
conn.commit()
self.close_connection(conn)
def getFacultyMember(self, name: str) -> tuple:
"""get a faculty member based on the name
@@ -963,7 +1154,12 @@ class Database:
Returns:
tuple: a tuple containing the data of the faculty member
"""
return self.query_db("SELECT titel, fname,lname,mail,telnr,fullname FROM prof WHERE fullname=?", (name,), one=True)
return self.query_db(
"SELECT titel, fname,lname,mail,telnr,fullname FROM prof WHERE fullname=?",
(name,),
one=True,
)
def updateFacultyMember(self, data: dict, oldlname: str, oldfname: str):
"""update the data of a faculty member
@@ -977,6 +1173,7 @@ class Database:
data["oldlname"] = oldlname
data["oldfname"] = oldfname
self.query_db(query, data)
def getFacultyMembers(self):
"""get a list of all faculty members