Files
school_compare/backend/database.py
T

44 lines
934 B
Python
Raw Normal View History

2026-01-06 17:22:39 +00:00
"""
Database connection setup using SQLAlchemy.
The schema is managed by dbt — the backend only reads from marts.* tables.
2026-01-06 17:22:39 +00:00
"""
from contextlib import contextmanager
from sqlalchemy import create_engine
2026-01-06 17:22:39 +00:00
from sqlalchemy.orm import sessionmaker, declarative_base
from .config import settings
engine = create_engine(
settings.database_url,
pool_size=10,
max_overflow=20,
pool_pre_ping=True,
pool_recycle=1800, # recycle connections every 30 min to avoid stale TCP
echo=False,
2026-01-06 17:22:39 +00:00
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
def get_db():
"""Dependency for FastAPI routes."""
2026-01-06 17:22:39 +00:00
db = SessionLocal()
try:
yield db
finally:
db.close()
@contextmanager
def get_db_session():
"""Context manager for non-FastAPI contexts (read-only)."""
2026-01-06 17:22:39 +00:00
db = SessionLocal()
try:
yield db
finally:
db.close()