2024-12-26 16:32:43 +00:00
|
|
|
import os
|
2024-11-07 14:15:57 +00:00
|
|
|
import sqlite3
|
|
|
|
from typing import Optional
|
|
|
|
|
2024-11-11 16:14:01 +00:00
|
|
|
from termcolor import colored
|
|
|
|
|
2024-11-07 14:15:57 +00:00
|
|
|
|
|
|
|
class DatabaseService:
|
|
|
|
def __init__(self, db_name):
|
|
|
|
self.db_name = db_name
|
|
|
|
self.db_path = "/home/thomas/repos/eolas-db/db"
|
|
|
|
self.connection: Optional[sqlite3.Connection] = None
|
|
|
|
|
|
|
|
def connect(self) -> Optional[sqlite3.Connection]:
|
|
|
|
if self.connection is not None:
|
|
|
|
return self.connection
|
|
|
|
|
|
|
|
try:
|
2024-12-26 16:32:43 +00:00
|
|
|
if not os.path.exists(self.db_path):
|
|
|
|
os.makedirs(self.db_path)
|
|
|
|
print(colored("INFO Created database directory", "light_blue"))
|
2024-11-07 14:15:57 +00:00
|
|
|
self.connection = sqlite3.connect(f"{self.db_path}/{self.db_name}.db")
|
2024-11-14 08:49:48 +00:00
|
|
|
self.connection.execute("PRAGMA foreign_keys = ON")
|
2024-11-11 16:14:01 +00:00
|
|
|
print(colored("INFO Database connection established", "light_blue"))
|
2024-11-07 14:15:57 +00:00
|
|
|
return self.connection
|
|
|
|
|
|
|
|
except Exception as e:
|
2024-11-11 16:14:01 +00:00
|
|
|
raise Exception(f"ERROR Problem connecting to database: {e}")
|
2024-11-07 14:15:57 +00:00
|
|
|
|
|
|
|
def disconnect(self) -> None:
|
|
|
|
try:
|
|
|
|
if self.connection is not None:
|
|
|
|
self.connection.close()
|
|
|
|
self.connection = None
|
|
|
|
except Exception as e:
|
|
|
|
raise Exception(f"ERROR Problem disconnecting from database: {e}")
|