"""Database engine and session setup. The connection string comes from the DATABASE_URL environment variable, e.g. postgresql+psycopg://wpsuite:secret@db-host:5432/wpsuite If unset, it falls back to a local SQLite file so the API can be run and tested on any machine without Postgres. The schema is identical either way (SQLAlchemy handles the dialect differences). """ import os from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, DeclarativeBase # Load a local .env if present (dev convenience). In production the DATABASE_URL # normally comes from the systemd unit's Environment / EnvironmentFile instead. try: from dotenv import load_dotenv load_dotenv() except Exception: pass DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///./wpsuite.db") # SQLite needs this flag to be used from FastAPI's threadpool; Postgres ignores it. connect_args = {"check_same_thread": False} if DATABASE_URL.startswith("sqlite") else {} engine = create_engine(DATABASE_URL, connect_args=connect_args, pool_pre_ping=True, future=True) SessionLocal = sessionmaker(bind=engine, autoflush=False, autocommit=False, future=True) class Base(DeclarativeBase): pass def get_db(): """FastAPI dependency that yields a session and always closes it.""" db = SessionLocal() try: yield db finally: db.close()