fix: auto-migrate SQLite schema to reconcile newly added columns on startup

This commit is contained in:
Atharv1705
2026-11-13 18:43:37 +05:30
parent d9ca4bbb02
commit 640ae9c1b4
6 changed files with 82 additions and 0 deletions
+46
View File
@@ -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
+2
View File
@@ -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()
+1
View File
@@ -235,3 +235,4 @@ def build_insurance_template_xlsx(db: Session) -> BytesIO:
wb.save(buf)
buf.seek(0)
return buf
+1
View File
@@ -252,3 +252,4 @@ def main() -> int:
if __name__ == "__main__":
sys.exit(main())
+31
View File
@@ -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