Spaces:
Runtime error
Runtime error
| # database.py | |
| # Database connection setup | |
| # Supports both SQLite (local) and PostgreSQL (production/Supabase) | |
| from sqlalchemy import create_engine | |
| from sqlalchemy.ext.declarative import declarative_base | |
| from sqlalchemy.orm import sessionmaker | |
| import os | |
| # Get database URL from environment variable | |
| # If not set, fall back to SQLite for local development | |
| DATABASE_URL = os.getenv( | |
| "DATABASE_URL", | |
| "sqlite:///./shoptracker.db" | |
| ) | |
| # PostgreSQL needs different connect_args than SQLite | |
| if DATABASE_URL.startswith("sqlite"): | |
| engine = create_engine( | |
| DATABASE_URL, | |
| connect_args={"check_same_thread": False} | |
| ) | |
| else: | |
| engine = create_engine(DATABASE_URL) | |
| # Session factory — used in all API routes | |
| SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) | |
| # Base class for all database models | |
| Base = declarative_base() | |
| # Dependency — used in FastAPI route functions | |
| def get_db(): | |
| db = SessionLocal() | |
| try: | |
| yield db | |
| finally: | |
| db.close() | |