_7ihdZddlZddlZddlmZddlmZejeZ GddZ y)znDatabase Manager for ChefSystem. Handles SQLite database connections, schema initialization, and migrations. N)Path)OptionalceZdZUdZdZeded<dZeed<de ddffd Z de fd Z de jfd Zdd Zde jfd Zdd ZddZde jddfdZde jddfdZddZxZS)DatabaseManagerzManages SQLite database connection and schema operations. Implements singleton pattern to ensure only one database connection exists. Supports context manager for transaction handling. N _instanceF _initializeddb_pathreturnc\|jt| ||_|jS)zCreate or return the singleton instance. Args: db_path: Path to the SQLite database file. Returns: DatabaseManager: The singleton instance. )rsuper__new__)clsr __class__s >/mnt/ssd/data/python-lab/ChefSystem/src/database/db_manager.pyr zDatabaseManager.__new__s) == !GOC0CM}}ctjsEt||_d|_dt_t j d|jyy)zoInitialize the database manager. Args: db_path: Path to the SQLite database file. NTz'DatabaseManager initialized with path: )rrrr connectionloggerinfo)selfr s r__init__zDatabaseManager.__init__%sD++=DL<@DO+/O ( KKA$,,P Q ,rc|j |jjjddt j t |j|_|jjdtj|j_ tjd|j|jS|jS#tj$r }tjd|dd}~wwxYw)a$Establish connection to the database. Creates a new connection if one doesn't exist, or returns the existing one. Enables foreign key constraints and sets row factory for dict-like access. Returns: sqlite3.Connection: Database connection object. NT)parentsexist_okzPRAGMA foreign_keys = ONz!Database connection established: zFailed to connect to database: exc_info)rr parentmkdirsqlite3connectstrexecuteRow row_factoryrrErrorerrorres rget_connectionzDatabaseManager.get_connection2s ?? "  ##))$)F#*//#dll2C"D''(BC/6kk+ ? ~NO t ==  >qcBT R sB0CD )DD c|j8 |jjd|_tjdyy#tj $r }tj d|dd}~wwxYw)zClose the database connection.NzDatabase connection closedz#Error closing database connection: Tr)rcloserrrr%r&r's rr+zDatabaseManager.closePsl ?? & %%'"& 89 ' ==  B1#FQU V s6AA9A44A9c"|jS)zfContext manager entry. Returns: sqlite3.Connection: Database connection. )r)rs r __enter__zDatabaseManager.__enter__[s ""$$rc|1 |jjtjdy |jjtjd|jy#tj $r }tj d|dd}~wwxYw#tj $r$}tj d|dYd}~yd}~wwxYw)aContext manager exit. Commits transaction on success, rolls back on error. Args: exc_type: Exception type if an error occurred. exc_val: Exception value if an error occurred. exc_tb: Exception traceback if an error occurred. NzTransaction committedzError committing transaction: TrzTransaction rolled back due to z Error rolling back transaction: ) rcommitrdebugrr%r&rollbackwarning__name__)rexc_typeexc_valexc_tbr(s r__exit__zDatabaseManager.__exit__cs   &&( 45  T((*!@ARAR@STU==  =aSAD Q == T ?sCd SS Ts./A2rRs6    8 $y y r