diff --git a/backend/app/core/migrations.py b/backend/app/core/migrations.py new file mode 100644 index 0000000..cd1eb74 --- /dev/null +++ b/backend/app/core/migrations.py @@ -0,0 +1,46 @@ +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 diff --git a/backend/app/main.py b/backend/app/main.py index e2f99df..5f8b9c6 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -11,6 +11,7 @@ from fastapi.responses import JSONResponse from .core.config import settings as app_settings from .core.db import SessionLocal, engine, get_scheduler_db from .core.exceptions import CodedHTTPException, coded_http_exception_handler +from .core.migrations import run_sqlite_migrations from .models import Base from .routers import ( assets, @@ -56,6 +57,7 @@ def _scheduled_alert_job() -> None: @asynccontextmanager async def lifespan(app: FastAPI): Base.metadata.create_all(bind=engine) + run_sqlite_migrations(engine) with SessionLocal() as db: ensure_default_settings(db) db.commit() diff --git a/backend/app/services/bulk_templates.py b/backend/app/services/bulk_templates.py index e7f5a95..e020331 100644 --- a/backend/app/services/bulk_templates.py +++ b/backend/app/services/bulk_templates.py @@ -235,3 +235,4 @@ def build_insurance_template_xlsx(db: Session) -> BytesIO: wb.save(buf) buf.seek(0) return buf + diff --git a/backend/scripts/backup.py b/backend/scripts/backup.py index 1f94f45..731f9e1 100644 --- a/backend/scripts/backup.py +++ b/backend/scripts/backup.py @@ -252,3 +252,4 @@ def main() -> int: if __name__ == "__main__": sys.exit(main()) + diff --git a/backend/tests/test_gap_features.py b/backend/tests/test_gap_features.py index c35ca7d..5695f9a 100644 --- a/backend/tests/test_gap_features.py +++ b/backend/tests/test_gap_features.py @@ -201,3 +201,34 @@ def test_bulk_import_templates_endpoints(client): assert r_ins.status_code == 200 assert r_ins.headers["content-type"] == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" assert len(r_ins.content) > 1000 + + +def test_sqlite_auto_migration_reconciles_missing_columns(): + from sqlalchemy import create_engine + from app.core.migrations import run_sqlite_migrations + + test_eng = create_engine("sqlite:///:memory:") + with test_eng.begin() as conn: + # Create complaints table without assigned_team column + conn.exec_driver_sql( + "CREATE TABLE complaints (" + "id INTEGER PRIMARY KEY, " + "complaint_no VARCHAR(50), " + "asset_id INTEGER, " + "description TEXT, " + "priority VARCHAR(50), " + "registered_at DATETIME, " + "registered_by_id INTEGER, " + "received_by_id INTEGER, " + "call_status VARCHAR(50)" + ")" + ) + cols_before = {r[1] for r in conn.exec_driver_sql("PRAGMA table_info(complaints)").fetchall()} + assert "assigned_team" not in cols_before + + # Run auto-migration + run_sqlite_migrations(test_eng) + + with test_eng.begin() as conn: + cols_after = {r[1] for r in conn.exec_driver_sql("PRAGMA table_info(complaints)").fetchall()} + assert "assigned_team" in cols_after diff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.md index 304ede8..dd863ff 100644 --- a/docs/USER_GUIDE.md +++ b/docs/USER_GUIDE.md @@ -96,3 +96,4 @@ Coordinators manage legal contracts, equipment warranties, insurance coverage, a - Record serial numbers, trial durations, expected return dates, and log official returns. - **Notifications & Expiry Alerts (`/notifications`)**: - Receive automated 30-day advance alerts for expiring contracts, warranties, and insurance policies. +