bozo-backend/Database.py

76 lines
2.4 KiB
Python
Raw Normal View History

import mysql.connector
import User
2023-06-04 06:31:08 -04:00
def is_in(lst: list, name: str):
for i in lst:
if (i[0] == name):
return (1);
return (0);
class Database:
def __init__(self, host, port, user, password):
"""
: param host: The ip of the database
: type host: str
: param port: The port of the database
: type port: int
: param user: The user to login on the database
: type user: str
: param password: The password of the user
: type password: str
"""
self.mydb = mysql.connector.connect(
host = host,
port = port,
user = user,
password = password,
)
2023-06-04 06:05:32 -04:00
self.cursor = self.mydb.cursor()
2023-06-04 06:12:14 -04:00
self.cursor.execute("SHOW DATABASES");
2023-06-04 06:31:08 -04:00
if (not is_in(self.cursor, "zeolak")):
2023-06-04 06:12:14 -04:00
self.cursor.execute("CREATE DATABASE zeolak")
self.mydb = mysql.connector.connect(
host = host,
port = port,
user = user,
password = password,
database = "zeolak"
)
self.cursor = self.mydb.cursor()
def _create_table(self, name: str, content: dict):
command: str = f"CREATE TABLE {name} ("
2023-06-04 06:31:08 -04:00
for key, value in content.items():
command += f"{key} {value}, "
command = command[:-2]
command += ")"
self.cursor.execute(command)
def create_user_table(self):
self.cursor.execute("SHOW TABLES");
2023-06-04 06:31:08 -04:00
if (not is_in(self.cursor, "users")):
data = {
"email": "VARCHAR(255)",
"username": "VARCHAR(255)",
"first_name": "VARCHAR(255)",
"last_name": "VARCHAR(255)",
"password": "VARCHAR(255)"
}
self._create_table("users", data)
def add_user(self, user: User):
2023-06-08 10:32:44 -04:00
self.cursor.execute(f"SELECT * FROM `users` WHERE `email` = '{user.email}'")
if (len(self.cursor.fetchall())):
return ("Email already used")
if (len(user.password) < 8):
return ("Password too short (minimum 8 chars)")
if (len(user.first_name) == 0):
return ("First name empty")
if (len(user.last_name) == 0):
return ("Last name empty")
if (len(user.username) == 0):
return ("Username empty")
self.cursor.execute(user.to_insert_sql())
self.mydb.commit()