"""Per-request SQLAlchemy session dependency."""

from __future__ import annotations

from collections.abc import Iterator

from sqlalchemy.orm import Session

from ocr_sprint.db.base import get_sessionmaker


def get_session() -> Iterator[Session]:
    """Yield a session, committing on success and rolling back on errors."""
    factory = get_sessionmaker()
    session = factory()
    try:
        yield session
        session.commit()
    except Exception:
        session.rollback()
        raise
    finally:
        session.close()
