Spaces:
Running
Running
File size: 1,241 Bytes
26a0c00 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | """
SQLAlchemy database setup with SQLite.
Uses synchronous SQLAlchemy for simplicity and compatibility.
"""
import os
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, declarative_base
from app.config import get_settings
settings = get_settings()
# ββ Ensure data directory exists βββββββββββββββββββββ
db_path = settings.DATABASE_URL.replace("sqlite:///", "")
os.makedirs(os.path.dirname(db_path) if os.path.dirname(db_path) else ".", exist_ok=True)
# ββ Engine & Session βββββββββββββββββββββββββββββββββ
engine = create_engine(
settings.DATABASE_URL,
connect_args={"check_same_thread": False}, # Required for SQLite
echo=settings.DEBUG,
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
def get_db():
"""FastAPI dependency β yields a DB session per request."""
db = SessionLocal()
try:
yield db
finally:
db.close()
def init_db():
"""Create all tables on startup."""
from app import models # noqa: F401 β import to register models
Base.metadata.create_all(bind=engine)
|