from pathlib import Path from sqlalchemy import create_engine from sqlalchemy.orm import DeclarativeBase, sessionmaker from .config import settings class Base(DeclarativeBase): pass if settings.database_url.startswith("sqlite"): Path(settings.database_url.replace("sqlite:///", "")).parent.mkdir(parents=True, exist_ok=True) engine = create_engine(settings.database_url, connect_args={"check_same_thread": False}) else: engine = create_engine(settings.database_url, pool_pre_ping=True) SessionLocal = sessionmaker(bind=engine, autoflush=False, autocommit=False) def get_db(): db = SessionLocal() try: yield db finally: # A request may exit through an exception or an early return before a # route explicitly commits. Roll back first so any checked-out # connection is returned to QueuePool in a clean state, then close the # Session itself. Session.close() also rolls back, but doing it here # makes the lifecycle guarantee explicit and observable in tests. try: db.rollback() finally: db.close()