Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /SHAdd0WTAka_Zen-Ai-Pentest /database /connection.py
| """ | |
| Database Connection Management Module | |
| This module provides database connection management including: | |
| - SQLAlchemy engine creation and configuration | |
| - Session management with context managers | |
| - Connection pooling configuration | |
| - Database lifecycle management (init/close) | |
| - Health check utilities | |
| Usage: | |
| from database.connection import DatabaseManager, get_db_session | |
| # Initialize database | |
| db_manager = DatabaseManager("postgresql://user:pass@localhost/db") | |
| db_manager.initialize() | |
| # Use context manager for sessions | |
| with db_manager.session_scope() as session: | |
| result = session.query(Model).all() | |
| """ | |
| import logging | |
| import threading | |
| import time | |
| from contextlib import contextmanager | |
| from typing import Any, Callable, Dict, Generator, Optional | |
| from urllib.parse import urlparse | |
| from sqlalchemy import create_engine, event, text | |
| from sqlalchemy.engine import Engine | |
| from sqlalchemy.exc import SQLAlchemyError | |
| from sqlalchemy.orm import Session, scoped_session, sessionmaker | |
| from sqlalchemy.pool import NullPool, QueuePool, StaticPool | |
| # Configure logging | |
| logger = logging.getLogger(__name__) | |
| class ConnectionPoolConfig: | |
| """Configuration for database connection pooling.""" | |
| def __init__( | |
| self, | |
| pool_size: int = 5, | |
| max_overflow: int = 10, | |
| pool_timeout: int = 30, | |
| pool_recycle: int = 3600, | |
| pool_pre_ping: bool = True, | |
| pool_class: Optional[str] = None, | |
| echo: bool = False, | |
| ): | |
| """ | |
| Initialize connection pool configuration. | |
| Args: | |
| pool_size: Number of connections to keep in pool | |
| max_overflow: Max number of connections to create beyond pool_size | |
| pool_timeout: Seconds to wait for available connection | |
| pool_recycle: Seconds after which to recycle connections | |
| pool_pre_ping: Verify connections before using from pool | |
| pool_class: Pool class name ('QueuePool', 'NullPool', 'StaticPool') | |
| echo: Enable SQL statement logging | |
| """ | |
| self.pool_size = pool_size | |
| self.max_overflow = max_overflow | |
| self.pool_timeout = pool_timeout | |
| self.pool_recycle = pool_recycle | |
| self.pool_pre_ping = pool_pre_ping | |
| self.pool_class = pool_class or "QueuePool" | |
| self.echo = echo | |
| def to_dict(self) -> Dict[str, Any]: | |
| """Convert configuration to dictionary.""" | |
| return { | |
| "pool_size": self.pool_size, | |
| "max_overflow": self.max_overflow, | |
| "pool_timeout": self.pool_timeout, | |
| "pool_recycle": self.pool_recycle, | |
| "pool_pre_ping": self.pool_pre_ping, | |
| "pool_class": self.pool_class, | |
| "echo": self.echo, | |
| } | |
| def from_dict(cls, config_dict: Dict[str, Any]) -> "ConnectionPoolConfig": | |
| """Create configuration from dictionary.""" | |
| return cls( | |
| pool_size=config_dict.get("pool_size", 5), | |
| max_overflow=config_dict.get("max_overflow", 10), | |
| pool_timeout=config_dict.get("pool_timeout", 30), | |
| pool_recycle=config_dict.get("pool_recycle", 3600), | |
| pool_pre_ping=config_dict.get("pool_pre_ping", True), | |
| pool_class=config_dict.get("pool_class"), | |
| echo=config_dict.get("echo", False), | |
| ) | |
| class DatabaseManager: | |
| """ | |
| Database connection manager with pooling and session handling. | |
| Provides thread-safe database connection management with: | |
| - Connection pooling | |
| - Session lifecycle management | |
| - Health monitoring | |
| - Transaction support | |
| """ | |
| _instance: Optional["DatabaseManager"] = None | |
| _lock = threading.Lock() | |
| def __new__(cls, *args, **kwargs) -> "DatabaseManager": | |
| """Implement singleton pattern for database manager.""" | |
| if cls._instance is None: | |
| with cls._lock: | |
| if cls._instance is None: | |
| cls._instance = super().__new__(cls) | |
| cls._instance._initialized = False | |
| return cls._instance | |
| def __init__( | |
| self, | |
| database_url: Optional[str] = None, | |
| pool_config: Optional[ConnectionPoolConfig] = None, | |
| connect_args: Optional[Dict[str, Any]] = None, | |
| ): | |
| """ | |
| Initialize database manager. | |
| Args: | |
| database_url: Database connection URL | |
| pool_config: Connection pool configuration | |
| connect_args: Additional connection arguments | |
| """ | |
| # Skip if already initialized (singleton pattern) | |
| if self._initialized: | |
| return | |
| self._database_url = database_url | |
| self._pool_config = pool_config or ConnectionPoolConfig() | |
| self._connect_args = connect_args or {} | |
| self._engine: Optional[Engine] = None | |
| self._session_factory: Optional[sessionmaker] = None | |
| self._scoped_session: Optional[scoped_session] = None | |
| self._initialized = False | |
| self._stats = { | |
| "connections_created": 0, | |
| "connections_checked_out": 0, | |
| "connections_checked_in": 0, | |
| "session_count": 0, | |
| "error_count": 0, | |
| } | |
| self._stats_lock = threading.Lock() | |
| def engine(self) -> Optional[Engine]: | |
| """Get the SQLAlchemy engine instance.""" | |
| return self._engine | |
| def is_initialized(self) -> bool: | |
| """Check if database manager is initialized.""" | |
| return self._initialized | |
| def stats(self) -> Dict[str, int]: | |
| """Get connection statistics.""" | |
| with self._stats_lock: | |
| return self._stats.copy() | |
| def _get_pool_class(self) -> type: | |
| """Get pool class based on configuration.""" | |
| pool_classes = { | |
| "QueuePool": QueuePool, | |
| "NullPool": NullPool, | |
| "StaticPool": StaticPool, | |
| } | |
| return pool_classes.get(self._pool_config.pool_class, QueuePool) | |
| def _setup_event_listeners(self) -> None: | |
| """Set up SQLAlchemy event listeners for monitoring.""" | |
| if not self._engine: | |
| return | |
| def on_connect(dbapi_conn, connection_record): | |
| with self._stats_lock: | |
| self._stats["connections_created"] += 1 | |
| logger.debug("New database connection created") | |
| def on_checkout(dbapi_conn, connection_record, connection_proxy): | |
| with self._stats_lock: | |
| self._stats["connections_checked_out"] += 1 | |
| logger.debug("Database connection checked out from pool") | |
| def on_checkin(dbapi_conn, connection_record): | |
| with self._stats_lock: | |
| self._stats["connections_checked_in"] += 1 | |
| logger.debug("Database connection checked in to pool") | |
| def initialize(self) -> None: | |
| """ | |
| Initialize database engine and session factory. | |
| Raises: | |
| RuntimeError: If database_url is not set | |
| SQLAlchemyError: If engine creation fails | |
| """ | |
| if self._initialized: | |
| logger.warning("Database manager already initialized") | |
| return | |
| if not self._database_url: | |
| raise RuntimeError("Database URL not configured") | |
| try: | |
| # Determine pool class | |
| pool_class = self._get_pool_class() | |
| # Create engine with pooling configuration | |
| engine_kwargs = { | |
| "poolclass": pool_class, | |
| "pool_pre_ping": self._pool_config.pool_pre_ping, | |
| "echo": self._pool_config.echo, | |
| "connect_args": self._connect_args, | |
| } | |
| # Only add pool-specific args for QueuePool | |
| if pool_class == QueuePool: | |
| engine_kwargs.update( | |
| { | |
| "pool_size": self._pool_config.pool_size, | |
| "max_overflow": self._pool_config.max_overflow, | |
| "pool_timeout": self._pool_config.pool_timeout, | |
| "pool_recycle": self._pool_config.pool_recycle, | |
| } | |
| ) | |
| self._engine = create_engine(self._database_url, **engine_kwargs) | |
| # Set up event listeners | |
| self._setup_event_listeners() | |
| # Create session factory | |
| self._session_factory = sessionmaker( | |
| bind=self._engine, | |
| autocommit=False, | |
| autoflush=False, | |
| expire_on_commit=False, | |
| ) | |
| # Create scoped session for thread safety | |
| self._scoped_session = scoped_session(self._session_factory) | |
| self._initialized = True | |
| logger.info("Database manager initialized successfully") | |
| except SQLAlchemyError as e: | |
| logger.error(f"Failed to initialize database: {e}") | |
| raise | |
| def close(self) -> None: | |
| """ | |
| Close database connections and cleanup resources. | |
| """ | |
| if not self._initialized: | |
| logger.warning("Database manager not initialized, nothing to close") | |
| return | |
| try: | |
| # Close scoped session | |
| if self._scoped_session: | |
| self._scoped_session.remove() | |
| self._scoped_session = None | |
| # Dispose engine | |
| if self._engine: | |
| self._engine.dispose() | |
| self._engine = None | |
| self._session_factory = None | |
| self._initialized = False | |
| logger.info("Database manager closed successfully") | |
| except SQLAlchemyError as e: | |
| logger.error(f"Error closing database: {e}") | |
| raise | |
| def create_tables(self, base_metadata: Any) -> None: | |
| """ | |
| Create all tables defined in the metadata. | |
| Args: | |
| base_metadata: SQLAlchemy declarative base metadata | |
| """ | |
| if not self._engine: | |
| raise RuntimeError("Database not initialized") | |
| try: | |
| base_metadata.create_all(self._engine) | |
| logger.info("Database tables created successfully") | |
| except SQLAlchemyError as e: | |
| logger.error(f"Failed to create tables: {e}") | |
| raise | |
| def drop_tables(self, base_metadata: Any) -> None: | |
| """ | |
| Drop all tables defined in the metadata. | |
| Args: | |
| base_metadata: SQLAlchemy declarative base metadata | |
| """ | |
| if not self._engine: | |
| raise RuntimeError("Database not initialized") | |
| try: | |
| base_metadata.drop_all(self._engine) | |
| logger.info("Database tables dropped successfully") | |
| except SQLAlchemyError as e: | |
| logger.error(f"Failed to drop tables: {e}") | |
| raise | |
| def get_session(self) -> Session: | |
| """ | |
| Get a new database session. | |
| Returns: | |
| SQLAlchemy Session instance | |
| Raises: | |
| RuntimeError: If database not initialized | |
| """ | |
| if not self._initialized or not self._session_factory: | |
| raise RuntimeError("Database not initialized. Call initialize() first.") | |
| with self._stats_lock: | |
| self._stats["session_count"] += 1 | |
| return self._session_factory() | |
| def get_scoped_session(self) -> Session: | |
| """ | |
| Get a thread-local scoped session. | |
| Returns: | |
| SQLAlchemy scoped session instance | |
| Raises: | |
| RuntimeError: If database not initialized | |
| """ | |
| if not self._initialized or not self._scoped_session: | |
| raise RuntimeError("Database not initialized. Call initialize() first.") | |
| return self._scoped_session() | |
| def session_scope(self) -> Generator[Session, None, None]: | |
| """ | |
| Provide a transactional scope around a series of operations. | |
| Usage: | |
| with db_manager.session_scope() as session: | |
| session.add(obj) | |
| # Automatically commits or rolls back | |
| Yields: | |
| SQLAlchemy Session instance | |
| Raises: | |
| RuntimeError: If database not initialized | |
| SQLAlchemyError: If database operation fails | |
| """ | |
| if not self._initialized: | |
| raise RuntimeError("Database not initialized. Call initialize() first.") | |
| session = self.get_session() | |
| try: | |
| yield session | |
| session.commit() | |
| except SQLAlchemyError as e: | |
| session.rollback() | |
| with self._stats_lock: | |
| self._stats["error_count"] += 1 | |
| logger.error(f"Session error, rolling back: {e}") | |
| raise | |
| except Exception as e: | |
| session.rollback() | |
| with self._stats_lock: | |
| self._stats["error_count"] += 1 | |
| logger.error(f"Unexpected error in session, rolling back: {e}") | |
| raise | |
| finally: | |
| session.close() | |
| def health_check(self) -> Dict[str, Any]: | |
| """ | |
| Perform database health check. | |
| Returns: | |
| Dictionary with health status information | |
| """ | |
| if not self._initialized or not self._engine: | |
| return { | |
| "healthy": False, | |
| "error": "Database not initialized", | |
| "response_time_ms": None, | |
| } | |
| start_time = time.time() | |
| try: | |
| # Execute simple query to verify connection | |
| with self._engine.connect() as conn: | |
| conn.execute(text("SELECT 1")) | |
| response_time = (time.time() - start_time) * 1000 | |
| # Get pool statistics | |
| pool = self._engine.pool | |
| pool_status = { | |
| "size": pool.size() if hasattr(pool, "size") else -1, | |
| "checked_in": (pool.checkedin() if hasattr(pool, "checkedin") else -1), | |
| "checked_out": (pool.checkedout() if hasattr(pool, "checkedout") else -1), | |
| "overflow": (pool.overflow() if hasattr(pool, "overflow") else -1), | |
| } | |
| return { | |
| "healthy": True, | |
| "response_time_ms": round(response_time, 2), | |
| "pool": pool_status, | |
| "stats": self.stats, | |
| } | |
| except SQLAlchemyError as e: | |
| return { | |
| "healthy": False, | |
| "error": str(e), | |
| "response_time_ms": round((time.time() - start_time) * 1000, 2), | |
| } | |
| def execute_with_retry( | |
| self, | |
| operation: Callable[[Session], Any], | |
| max_retries: int = 3, | |
| retry_delay: float = 1.0, | |
| ) -> Any: | |
| """ | |
| Execute a database operation with retry logic. | |
| Args: | |
| operation: Function that takes a session and performs operations | |
| max_retries: Maximum number of retry attempts | |
| retry_delay: Delay between retries in seconds | |
| Returns: | |
| Result of the operation | |
| Raises: | |
| SQLAlchemyError: If all retries fail | |
| RuntimeError: If database not initialized | |
| """ | |
| if not self._initialized: | |
| raise RuntimeError("Database not initialized. Call initialize() first.") | |
| last_error = None | |
| for attempt in range(max_retries): | |
| session = self.get_session() | |
| try: | |
| result = operation(session) | |
| session.commit() | |
| return result | |
| except SQLAlchemyError as e: | |
| session.rollback() | |
| last_error = e | |
| with self._stats_lock: | |
| self._stats["error_count"] += 1 | |
| logger.warning(f"Operation failed (attempt {attempt + 1}/{max_retries}): {e}") | |
| if attempt < max_retries - 1: | |
| time.sleep(retry_delay * (attempt + 1)) # Exponential backoff | |
| finally: | |
| session.close() | |
| logger.error(f"Operation failed after {max_retries} attempts") | |
| raise last_error | |
| def reset_stats(self) -> None: | |
| """Reset connection statistics.""" | |
| with self._stats_lock: | |
| self._stats = { | |
| "connections_created": 0, | |
| "connections_checked_out": 0, | |
| "connections_checked_in": 0, | |
| "session_count": 0, | |
| "error_count": 0, | |
| } | |
| # Global database manager instance | |
| db_manager: Optional[DatabaseManager] = None | |
| def init_db_manager( | |
| database_url: str, | |
| pool_config: Optional[ConnectionPoolConfig] = None, | |
| connect_args: Optional[Dict[str, Any]] = None, | |
| ) -> DatabaseManager: | |
| """ | |
| Initialize global database manager. | |
| Args: | |
| database_url: Database connection URL | |
| pool_config: Optional connection pool configuration | |
| connect_args: Optional additional connection arguments | |
| Returns: | |
| Initialized DatabaseManager instance | |
| """ | |
| global db_manager | |
| db_manager = DatabaseManager(database_url, pool_config, connect_args) | |
| db_manager.initialize() | |
| return db_manager | |
| def close_db_manager() -> None: | |
| """Close global database manager.""" | |
| global db_manager | |
| if db_manager: | |
| db_manager.close() | |
| db_manager = None | |
| def get_db_session() -> Session: | |
| """ | |
| Get a database session from global manager. | |
| Returns: | |
| SQLAlchemy Session instance | |
| Raises: | |
| RuntimeError: If database manager not initialized | |
| """ | |
| if db_manager is None: | |
| raise RuntimeError("Database manager not initialized. Call init_db_manager() first.") | |
| return db_manager.get_session() | |
| def get_db_context() -> Generator[Session, None, None]: | |
| """ | |
| Context manager for database sessions. | |
| Usage: | |
| with get_db_context() as session: | |
| result = session.query(Model).all() | |
| Yields: | |
| SQLAlchemy Session instance | |
| """ | |
| if db_manager is None: | |
| raise RuntimeError("Database manager not initialized. Call init_db_manager() first.") | |
| with db_manager.session_scope() as session: | |
| yield session | |
| def get_db_generator() -> Generator[Session, None, None]: | |
| """ | |
| Generator for database sessions (for FastAPI dependency injection). | |
| Usage: | |
| @app.get("/items") | |
| def get_items(db: Session = Depends(get_db_generator)): | |
| ... | |
| Yields: | |
| SQLAlchemy Session instance | |
| """ | |
| if db_manager is None: | |
| raise RuntimeError("Database manager not initialized. Call init_db_manager() first.") | |
| session = db_manager.get_session() | |
| try: | |
| yield session | |
| session.commit() | |
| except SQLAlchemyError: | |
| session.rollback() | |
| raise | |
| finally: | |
| session.close() | |
| def is_valid_database_url(url: str) -> bool: | |
| """ | |
| Validate database URL format. | |
| Args: | |
| url: Database connection URL | |
| Returns: | |
| True if URL format is valid | |
| """ | |
| if not url or not isinstance(url, str): | |
| return False | |
| try: | |
| parsed = urlparse(url) | |
| # Check for required components | |
| if not parsed.scheme: | |
| return False | |
| # Support dialect+driver format (e.g., postgresql+psycopg2, mysql+pymysql) | |
| base_scheme = parsed.scheme.split("+")[0] | |
| valid_schemes = ( | |
| "sqlite", | |
| "postgresql", | |
| "mysql", | |
| "mariadb", | |
| "mssql", | |
| "oracle", | |
| ) | |
| if base_scheme not in valid_schemes: | |
| return False | |
| # SQLite can have empty host/netloc | |
| if base_scheme != "sqlite" and not parsed.hostname: | |
| return False | |
| return True | |
| except Exception: | |
| return False | |
| def create_test_connection_pool_config() -> ConnectionPoolConfig: | |
| """ | |
| Create connection pool configuration optimized for testing. | |
| Returns: | |
| ConnectionPoolConfig with test-optimized settings | |
| """ | |
| return ConnectionPoolConfig( | |
| pool_size=1, | |
| max_overflow=0, | |
| pool_timeout=5, | |
| pool_recycle=300, | |
| pool_pre_ping=True, | |
| pool_class="StaticPool", | |
| echo=False, | |
| ) | |
Xet Storage Details
- Size:
- 20.3 kB
- Xet hash:
- 19c871c08f3b3abc6833a122191a862701ce571367238dbcebe5a2537308ecb0
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.