Spaces:
Running
Running
Download app/persistence/database/session.py from fallingbody/Mockai: direct link, hf CLI and curl.
- Browser
- Download file 3.39 kB
-
https://huggingface.co/spaces/fallingbody/Mockai/resolve/main/app/persistence/database/session.py
- Command line
-
hf download hf://spaces/fallingbody/Mockai/app/persistence/database/session.py
-
curl -L -o session.py https://huggingface.co/spaces/fallingbody/Mockai/resolve/main/app/persistence/database/session.py
3.39 kB
| from sqlalchemy import create_engine, event, exc, text | |
| from sqlalchemy.orm import sessionmaker, scoped_session | |
| from app.core.config import settings | |
| from app.core.logger import get_logger | |
| logger = get_logger(__name__) | |
| # Main database engine | |
| raw_db_url = settings.DATABASE_URL | |
| if not raw_db_url or "sqlite" in raw_db_url: | |
| raise ValueError("A valid PostgreSQL DATABASE_URL must be configured in the environment") | |
| db_url = raw_db_url.strip() | |
| # 1. Normalize deprecated postgres:// to postgresql:// | |
| if db_url.startswith("postgres://"): | |
| db_url = db_url.replace("postgres://", "postgresql://", 1) | |
| # 2. Check available drivers | |
| has_psycopg3 = False | |
| try: | |
| import psycopg # noqa: F401 | |
| has_psycopg3 = True | |
| except ImportError: | |
| pass | |
| has_psycopg2 = False | |
| try: | |
| import psycopg2.extras | |
| psycopg2.extras.register_uuid() | |
| logger.info("Successfully registered psycopg2 UUID adapter") | |
| has_psycopg2 = True | |
| except Exception as e: | |
| logger.warning(f"Failed to register psycopg2 UUID adapter: {e}") | |
| # 3. Ensure compatible driver dialect is specified in URL | |
| if db_url.startswith("postgresql+psycopg://") and not has_psycopg3: | |
| logger.warning("psycopg (v3) not found; falling back to postgresql+psycopg2://") | |
| db_url = db_url.replace("postgresql+psycopg://", "postgresql+psycopg2://", 1) | |
| elif db_url.startswith("postgresql://") and not db_url.startswith("postgresql+"): | |
| if not has_psycopg3 and has_psycopg2: | |
| logger.info("Explicitly routing postgresql:// to postgresql+psycopg2://") | |
| db_url = db_url.replace("postgresql://", "postgresql+psycopg2://", 1) | |
| engine = create_engine( | |
| db_url, | |
| pool_pre_ping=True, | |
| pool_size=5, | |
| max_overflow=5, | |
| pool_recycle=3600, | |
| connect_args={"connect_timeout": 10}, | |
| echo=False, | |
| ) | |
| # Event listener to log connection issues | |
| def receive_connect(dbapi_conn, connection_record): | |
| logger.info("Database connection established") | |
| def receive_pool_checkout(dbapi_conn, connection_record, connection_proxy): | |
| connection_record.info['checkout_time'] = __import__('time').time() | |
| def receive_pool_checkin(dbapi_conn, connection_record): | |
| checkout_time = connection_record.info.get('checkout_time') | |
| if checkout_time: | |
| duration = __import__('time').time() - checkout_time | |
| if duration > 5.0: | |
| logger.warning(f"Long database connection held for {duration:.2f}s") | |
| SessionLocal = scoped_session( | |
| sessionmaker( | |
| autocommit=False, | |
| autoflush=False, | |
| bind=engine, | |
| ) | |
| ) | |
| import time | |
| def get_db_session(): | |
| """ | |
| Returns a scoped SQLAlchemy session. Retries on connection failure. | |
| """ | |
| max_retries = 3 | |
| retry_delay = 2 | |
| for attempt in range(max_retries): | |
| try: | |
| session = SessionLocal() | |
| session.execute(text("SELECT 1")) | |
| return session | |
| except Exception as e: | |
| if attempt < max_retries - 1: | |
| logger.warning(f"Database connection attempt {attempt + 1} failed, retrying...: {e}") | |
| if 'session' in locals(): | |
| session.close() | |
| time.sleep(retry_delay) | |
| else: | |
| logger.error(f"Database connection failed after {max_retries} attempts: {e}") | |
| raise | |