46 lines
1.4 KiB
Python
46 lines
1.4 KiB
Python
|
|
"""Base repository for all other repository classes."""
|
||
|
|
|
||
|
|
import logging
|
||
|
|
from contextlib import contextmanager
|
||
|
|
from typing import Optional
|
||
|
|
|
||
|
|
from ..connection import get_db_manager
|
||
|
|
|
||
|
|
|
||
|
|
class DatabaseOperationError(Exception):
|
||
|
|
"""Custom exception for database operation errors."""
|
||
|
|
pass
|
||
|
|
|
||
|
|
|
||
|
|
class BaseRepository:
|
||
|
|
"""Base class for all repository classes."""
|
||
|
|
|
||
|
|
def __init__(self, logger: Optional[logging.Logger] = None):
|
||
|
|
"""Initialize repository with optional logger."""
|
||
|
|
self.logger = logger
|
||
|
|
self._db_manager = get_db_manager()
|
||
|
|
self._db_manager.initialize()
|
||
|
|
|
||
|
|
def log_info(self, message: str) -> None:
|
||
|
|
"""Log info message if logger is available."""
|
||
|
|
if self.logger:
|
||
|
|
self.logger.info(message)
|
||
|
|
|
||
|
|
def log_debug(self, message: str) -> None:
|
||
|
|
"""Log debug message if logger is available."""
|
||
|
|
if self.logger:
|
||
|
|
self.logger.debug(message)
|
||
|
|
|
||
|
|
def log_error(self, message: str) -> None:
|
||
|
|
"""Log error message if logger is available."""
|
||
|
|
if self.logger:
|
||
|
|
self.logger.error(message)
|
||
|
|
|
||
|
|
@contextmanager
|
||
|
|
def get_session(self):
|
||
|
|
"""Get database session with automatic cleanup."""
|
||
|
|
if not self._db_manager:
|
||
|
|
raise DatabaseOperationError("Database manager not initialized")
|
||
|
|
|
||
|
|
with self._db_manager.get_session() as session:
|
||
|
|
yield session
|