| 1234567891011121314151617181920212223242526272829303132333435363738 |
- """
- app/database.py
- ───────────────
- SQLAlchemy synchronous engine, session factory, and declarative base.
- """
- from __future__ import annotations
- from sqlalchemy import create_engine
- from sqlalchemy.orm import DeclarativeBase, sessionmaker
- from app.config import settings
- engine = create_engine(
- settings.DATABASE_URL,
- pool_pre_ping=True, # recycle stale connections automatically
- pool_size=10,
- max_overflow=20,
- )
- SessionLocal = sessionmaker(
- autocommit=False,
- autoflush=False,
- bind=engine,
- )
- class Base(DeclarativeBase):
- """Shared declarative base – all ORM models inherit from this."""
- pass
- def get_db():
- """FastAPI dependency: yields a scoped DB session and guarantees closure."""
- db = SessionLocal()
- try:
- yield db
- finally:
- db.close()
|