fix: auto-migrate SQLite schema to reconcile newly added columns on startup
This commit is contained in:
@@ -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
|
||||||
@@ -11,6 +11,7 @@ from fastapi.responses import JSONResponse
|
|||||||
from .core.config import settings as app_settings
|
from .core.config import settings as app_settings
|
||||||
from .core.db import SessionLocal, engine, get_scheduler_db
|
from .core.db import SessionLocal, engine, get_scheduler_db
|
||||||
from .core.exceptions import CodedHTTPException, coded_http_exception_handler
|
from .core.exceptions import CodedHTTPException, coded_http_exception_handler
|
||||||
|
from .core.migrations import run_sqlite_migrations
|
||||||
from .models import Base
|
from .models import Base
|
||||||
from .routers import (
|
from .routers import (
|
||||||
assets,
|
assets,
|
||||||
@@ -56,6 +57,7 @@ def _scheduled_alert_job() -> None:
|
|||||||
@asynccontextmanager
|
@asynccontextmanager
|
||||||
async def lifespan(app: FastAPI):
|
async def lifespan(app: FastAPI):
|
||||||
Base.metadata.create_all(bind=engine)
|
Base.metadata.create_all(bind=engine)
|
||||||
|
run_sqlite_migrations(engine)
|
||||||
with SessionLocal() as db:
|
with SessionLocal() as db:
|
||||||
ensure_default_settings(db)
|
ensure_default_settings(db)
|
||||||
db.commit()
|
db.commit()
|
||||||
|
|||||||
@@ -235,3 +235,4 @@ def build_insurance_template_xlsx(db: Session) -> BytesIO:
|
|||||||
wb.save(buf)
|
wb.save(buf)
|
||||||
buf.seek(0)
|
buf.seek(0)
|
||||||
return buf
|
return buf
|
||||||
|
|
||||||
|
|||||||
@@ -252,3 +252,4 @@ def main() -> int:
|
|||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
sys.exit(main())
|
sys.exit(main())
|
||||||
|
|
||||||
|
|||||||
@@ -201,3 +201,34 @@ def test_bulk_import_templates_endpoints(client):
|
|||||||
assert r_ins.status_code == 200
|
assert r_ins.status_code == 200
|
||||||
assert r_ins.headers["content-type"] == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
assert r_ins.headers["content-type"] == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
||||||
assert len(r_ins.content) > 1000
|
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
|
||||||
|
|||||||
@@ -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.
|
- Record serial numbers, trial durations, expected return dates, and log official returns.
|
||||||
- **Notifications & Expiry Alerts (`/notifications`)**:
|
- **Notifications & Expiry Alerts (`/notifications`)**:
|
||||||
- Receive automated 30-day advance alerts for expiring contracts, warranties, and insurance policies.
|
- Receive automated 30-day advance alerts for expiring contracts, warranties, and insurance policies.
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user