Johnntirs's picture
Room Visualizer backend (Docker)
0cdb4e8
Raw
History Blame Contribute Delete
1.09 kB
"""SQLAlchemy engine and session setup for the local SQLite database."""
from __future__ import annotations
from collections.abc import Iterator
from sqlalchemy import create_engine
from sqlalchemy.orm import DeclarativeBase, Session, sessionmaker
from .config import settings
# check_same_thread=False lets the SQLite connection be used across the
# threadpool that FastAPI/uvicorn uses for sync endpoints.
engine = create_engine(
settings.DATABASE_URL,
connect_args={"check_same_thread": False},
future=True,
)
SessionLocal = sessionmaker(bind=engine, autoflush=False, autocommit=False, future=True)
class Base(DeclarativeBase):
"""Declarative base for all ORM models."""
def init_db() -> None:
"""Create tables if they do not already exist."""
from . import models # noqa: F401 -- ensure models are imported/registered
Base.metadata.create_all(bind=engine)
def get_db() -> Iterator[Session]:
"""FastAPI dependency: yield a DB session and always close it."""
db = SessionLocal()
try:
yield db
finally:
db.close()