from collections.abc import Generator from pathlib import Path from sqlalchemy import create_engine, event, text from sqlalchemy.orm import DeclarativeBase, Session, sessionmaker from app.config import get_settings class Base(DeclarativeBase): pass settings = get_settings() Path(settings.sqlite_path).parent.mkdir(parents=True, exist_ok=True) engine = create_engine( settings.sqlite_url, connect_args={"check_same_thread": False}, future=True, ) @event.listens_for(engine, "connect") def configure_sqlite(dbapi_connection, _connection_record) -> None: cursor = dbapi_connection.cursor() cursor.execute("PRAGMA journal_mode=WAL") cursor.execute("PRAGMA busy_timeout=5000") cursor.execute("PRAGMA foreign_keys=ON") cursor.close() SessionLocal = sessionmaker(bind=engine, autoflush=False, autocommit=False, expire_on_commit=False) def init_db() -> None: from app import models # noqa: F401 Base.metadata.create_all(bind=engine) migrate_db() def migrate_db() -> None: migrations = { "videos": { "thumbnail_url": "TEXT NOT NULL DEFAULT ''", "progress_percent": "INTEGER NOT NULL DEFAULT 0", "progress_stage": "TEXT NOT NULL DEFAULT ''", "progress_log": "TEXT NOT NULL DEFAULT ''", } } with engine.begin() as connection: for table, columns in migrations.items(): existing = { row[1] for row in connection.execute(text(f"PRAGMA table_info({table})")).fetchall() } for column, definition in columns.items(): if column not in existing: connection.execute(text(f"ALTER TABLE {table} ADD COLUMN {column} {definition}")) def get_session() -> Generator[Session, None, None]: with SessionLocal() as session: yield session