maple/util/db.py
2024-04-06 18:32:49 +02:00

59 lines
1.6 KiB
Python

import sqlite3
from sqlite3 import Error, Connection
from util.config import DB_PATH
from util.enums import AnimeListServices
def setup_database() -> bool:
"""
First-time DB setup (creating tables etc.)
:return: True if all went smoothly, else False
"""
conn = create_connection()
if conn is None:
return False
try:
c = conn.cursor()
c.execute("""CREATE TABLE IF NOT EXISTS connections (
id integer PRIMARY KEY,
uid text NOT NULL,
animelist text NOT NULL,
service text NOT NULL
);""")
except Error as e:
print("Error while creating table 'connections':")
print(e)
return False
conn.close()
return True
def add_user_connection(uid: str, listname: str, service: AnimeListServices) -> bool:
conn = create_connection()
if conn is None:
return False
try:
c = conn.cursor()
c.execute(f"""INSERT INTO connections(uid,animelist,service) VALUES('{uid}','{listname}','{service.value}')""")
except Error as e:
print("Error while adding a new connection:")
print(e)
return False
def create_connection() -> Connection | None:
"""
Creates a connection to an SQLite database
:return: Connection if connected successfully, else None
"""
conn = None
try:
conn = sqlite3.connect(DB_PATH)
print(f"Connected, SQLite vetsion {sqlite3.version}")
return conn
except Error as e:
print("Error while connecting to DB:")
print(e)
return conn