database.py 847 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. """
  2. app/database.py
  3. ───────────────
  4. SQLAlchemy synchronous engine, session factory, and declarative base.
  5. """
  6. from __future__ import annotations
  7. from sqlalchemy import create_engine
  8. from sqlalchemy.orm import DeclarativeBase, sessionmaker
  9. from app.config import settings
  10. engine = create_engine(
  11. settings.DATABASE_URL,
  12. pool_pre_ping=True, # recycle stale connections automatically
  13. pool_size=10,
  14. max_overflow=20,
  15. )
  16. SessionLocal = sessionmaker(
  17. autocommit=False,
  18. autoflush=False,
  19. bind=engine,
  20. )
  21. class Base(DeclarativeBase):
  22. """Shared declarative base – all ORM models inherit from this."""
  23. pass
  24. def get_db():
  25. """FastAPI dependency: yields a scoped DB session and guarantees closure."""
  26. db = SessionLocal()
  27. try:
  28. yield db
  29. finally:
  30. db.close()