Spaces:
Running
Running
Download database/connection.py from Churchgate/facilityxperience: direct link, hf CLI and curl.
- Browser
- Download file 5.18 kB
-
https://huggingface.co/spaces/Churchgate/facilityxperience/resolve/main/database/connection.py
- Command line
-
hf download hf://spaces/Churchgate/facilityxperience/database/connection.py
-
curl -L -o connection.py https://huggingface.co/spaces/Churchgate/facilityxperience/resolve/main/database/connection.py
5.18 kB
| """ | |
| facilityXperience Database Connection Manager | |
| Enterprise-grade database connectivity with connection pooling | |
| """ | |
| import os | |
| from typing import Optional, Dict, Any | |
| from contextlib import contextmanager | |
| from sqlalchemy import create_engine, Engine, event | |
| from sqlalchemy.orm import sessionmaker, Session, declarative_base | |
| from sqlalchemy.pool import QueuePool | |
| from sqlalchemy.exc import SQLAlchemyError | |
| import logging | |
| logger = logging.getLogger(__name__) | |
| Base = declarative_base() | |
| class DatabaseManager: | |
| """Enterprise database connection manager with pooling""" | |
| _instance: Optional['DatabaseManager'] = None | |
| _engine: Optional[Engine] = None | |
| _SessionLocal: Optional[sessionmaker] = None | |
| def __new__(cls): | |
| if cls._instance is None: | |
| cls._instance = super().__new__(cls) | |
| return cls._instance | |
| def __init__(self): | |
| if not hasattr(self, 'initialized'): | |
| self.initialized = True | |
| self._setup_engine() | |
| def _get_connection_string(self) -> str: | |
| """Build database connection string from environment""" | |
| db_host = os.getenv("DB_HOST", "localhost") | |
| db_port = os.getenv("DB_PORT", "5432") | |
| db_name = os.getenv("DB_NAME", "facilityxperience") | |
| db_user = os.getenv("DB_USER", "fx_admin") | |
| db_password = os.getenv("DB_PASSWORD", "") | |
| return f"postgresql://{db_user}:{db_password}@{db_host}:{db_port}/{db_name}" | |
| def _setup_engine(self): | |
| """Initialize SQLAlchemy engine with connection pooling""" | |
| connection_string = self._get_connection_string() | |
| self._engine = create_engine( | |
| connection_string, | |
| poolclass=QueuePool, | |
| pool_size=int(os.getenv("DB_POOL_SIZE", "50")), | |
| max_overflow=int(os.getenv("DB_MAX_OVERFLOW", "100")), | |
| pool_pre_ping=True, | |
| pool_recycle=3600, | |
| echo=False, | |
| connect_args={ | |
| "connect_timeout": 10, | |
| "application_name": "facilityXperience", | |
| "options": "-c statement_timeout=30000" | |
| } | |
| ) | |
| # Add engine event listeners | |
| def receive_connect(dbapi_connection, connection_record): | |
| logger.info("New database connection established") | |
| def receive_checkout(dbapi_connection, connection_record, connection_proxy): | |
| logger.debug("Database connection checked out from pool") | |
| self._SessionLocal = sessionmaker( | |
| autocommit=False, | |
| autoflush=False, | |
| bind=self._engine | |
| ) | |
| logger.info("Database engine initialized with connection pooling") | |
| def engine(self) -> Engine: | |
| """Get SQLAlchemy engine""" | |
| if self._engine is None: | |
| self._setup_engine() | |
| return self._engine | |
| def SessionLocal(self) -> sessionmaker: | |
| """Get session factory""" | |
| if self._SessionLocal is None: | |
| self._setup_engine() | |
| return self._SessionLocal | |
| def get_session(self) -> Session: | |
| """Get a database session with automatic cleanup""" | |
| session = self.SessionLocal() | |
| try: | |
| yield session | |
| session.commit() | |
| except SQLAlchemyError as e: | |
| session.rollback() | |
| logger.error(f"Database error: {str(e)}") | |
| raise | |
| except Exception as e: | |
| session.rollback() | |
| logger.error(f"Unexpected error: {str(e)}") | |
| raise | |
| finally: | |
| session.close() | |
| def test_connection(self) -> bool: | |
| """Test database connectivity""" | |
| try: | |
| with self.get_session() as session: | |
| session.execute("SELECT 1") | |
| logger.info("Database connection test successful") | |
| return True | |
| except Exception as e: | |
| logger.error(f"Database connection test failed: {str(e)}") | |
| return False | |
| def get_pool_status(self) -> Dict[str, Any]: | |
| """Get connection pool statistics""" | |
| if self._engine: | |
| pool = self._engine.pool | |
| return { | |
| "size": pool.size(), | |
| "checked_in": pool.checkedin(), | |
| "checked_out": pool.checkedout(), | |
| "overflow": pool.overflow(), | |
| "total": pool.size() + pool.overflow() | |
| } | |
| return {} | |
| def dispose(self): | |
| """Dispose of engine and all connections""" | |
| if self._engine: | |
| self._engine.dispose() | |
| logger.info("Database engine disposed") | |
| # Global database manager instance | |
| db_manager = DatabaseManager() | |
| def get_db() -> Session: | |
| """FastAPI-style dependency for database sessions""" | |
| with db_manager.get_session() as session: | |
| yield session |