"""SQLite engine and sessions. WAL mode lets the API read while a worker subprocess writes.""" from __future__ import annotations import threading from collections.abc import Iterator from functools import lru_cache from sqlalchemy import Engine, event from sqlmodel import Session, SQLModel, create_engine from stemdeck import models # noqa: F401 (register tables) from stemdeck.settings import get_settings # Threads that ask for the engine at the same moment (the API's first requests, the cloud container's snapshot # thread) must not each create the tables and add the new columns: one of them would fail on "duplicate column". _engine_lock = threading.Lock() def get_engine() -> Engine: with _engine_lock: return _build_engine() get_engine.cache_clear = lambda: _build_engine.cache_clear() # type: ignore[attr-defined] # tests reset it @lru_cache def _build_engine() -> Engine: path = get_settings().db_path engine = create_engine( f"sqlite:///{path.as_posix()}", connect_args={"check_same_thread": False, "timeout": 30}, ) @event.listens_for(engine, "connect") def _pragmas(dbapi_conn, _record) -> None: # noqa: ANN001 cur = dbapi_conn.cursor() cur.execute("PRAGMA journal_mode=WAL") cur.execute("PRAGMA synchronous=NORMAL") cur.execute("PRAGMA foreign_keys=ON") cur.close() SQLModel.metadata.create_all(engine) _add_new_columns(engine) return engine # Columns added after the first release: create_all() never alters an existing table, so add them here. # Each must be nullable (or have a constant default) for ALTER TABLE ADD COLUMN. ADDED_COLUMNS: tuple[tuple[str, str, str], ...] = ( ("song", "source_url", "VARCHAR"), ("song", "owner", "VARCHAR NOT NULL DEFAULT 'local'"), ("song", "client", "VARCHAR NOT NULL DEFAULT ''"), ) def _add_new_columns(engine: Engine) -> None: with engine.begin() as conn: for table, column, ddl in ADDED_COLUMNS: existing = {row[1] for row in conn.exec_driver_sql(f"PRAGMA table_info({table})")} if column not in existing: conn.exec_driver_sql(f"ALTER TABLE {table} ADD COLUMN {column} {ddl}") def get_session() -> Iterator[Session]: with Session(get_engine()) as session: yield session