import logging from sqlalchemy.engine import Engine from ..models import Base logger = logging.getLogger("poona_ams") def run_sqlite_migrations(engine: Engine) -> None: """ Auto-migrate SQLite database schema additions for existing databases. SQLite create_all() creates missing tables but does not alter existing tables to add newly defined columns. This reconciles table columns safely on startup without losing existing data. """ if engine.dialect.name != "sqlite": return try: with engine.begin() as conn: existing_tables = { row[0] for row in conn.exec_driver_sql( "SELECT name FROM sqlite_master WHERE type='table'" ).fetchall() } for table_name, table in Base.metadata.tables.items(): if table_name not in existing_tables: continue existing_cols = { row[1] for row in conn.exec_driver_sql( f"PRAGMA table_info({table_name})" ).fetchall() } for col in table.columns: if col.name not in existing_cols: col_type = col.type.compile(engine.dialect) sql = f"ALTER TABLE {table_name} ADD COLUMN {col.name} {col_type}" logger.info("Auto-migrating SQLite: %s", sql) conn.exec_driver_sql(sql) except Exception: logger.exception("Failed running SQLite auto-migrations.") raise