"""Database connection and session management Supports MySQL database with connection pooling. All tables use 'tr_' prefix to avoid conflicts in shared database. """ from contextlib import contextmanager from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker, Session from app.core.config import get_settings settings = get_settings() # Create engine with MySQL connection pooling # Pool settings are configurable via environment variables engine = create_engine( settings.DATABASE_URL, pool_size=settings.DB_POOL_SIZE, max_overflow=settings.DB_MAX_OVERFLOW, pool_timeout=settings.DB_POOL_TIMEOUT, pool_pre_ping=True, # Verify connection before using pool_recycle=settings.DB_POOL_RECYCLE, echo=settings.DEBUG, ) # Create session factory SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) # Base class for models Base = declarative_base() def get_db(): """FastAPI dependency to get database session""" db = SessionLocal() try: yield db finally: db.close() @contextmanager def get_db_context() -> Session: """Context manager for short-lived database sessions. Use this for operations that need a database session but should not hold onto it for the entire request/connection lifecycle. Example: with get_db_context() as db: result = db.query(Model).filter(...).first() """ db = SessionLocal() try: yield db finally: db.close()