emojinize / app /database.py
Luturtun's picture
Phase 3 completed
4a7773e
Raw
History Blame Contribute Delete
806 Bytes
"""SQLAlchemy engine, session factory, and FastAPI dependency."""
import os
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, Session
DATABASE_URL = os.getenv(
"DATABASE_URL",
"postgresql://postgres:postgres@localhost:5432/emojinize",
)
engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
def get_db() -> Session:
"""
Yield a database session for a single request, then close it.
FastAPI injects this as a dependency via Depends(get_db).
The session is always closed even if the handler raises an exception.
Yields:
An active SQLAlchemy Session bound to the configured DATABASE_URL.
"""
db = SessionLocal()
try:
yield db
finally:
db.close()