from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker from pathlib import Path # Create database directory if it doesn't exist DB_DIR = Path("/app") / "storage" / "db" DB_DIR.mkdir(parents=True, exist_ok=True) SQLALCHEMY_DATABASE_URL = f"sqlite:///{DB_DIR}/db.sqlite" # For local development, use a relative path LOCAL_DB_PATH = Path(__file__).parent.parent.parent / "storage" / "db" LOCAL_DB_PATH.mkdir(parents=True, exist_ok=True) LOCAL_DB_URL = f"sqlite:///{LOCAL_DB_PATH}/db.sqlite" # Choose the appropriate URL based on environment DATABASE_URL = LOCAL_DB_URL # Default to local development engine = create_engine( DATABASE_URL, connect_args={"check_same_thread": False} ) SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) Base = declarative_base() def get_db(): """ Dependency function to get a database session. Used as a FastAPI dependency in route handlers. """ db = SessionLocal() try: yield db finally: db.close() def create_db_and_tables(): """ Create database tables if they don't exist. Call this function on application startup. """ Base.metadata.create_all(bind=engine)