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.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()
|
||||
|
||||
@@ -235,3 +235,4 @@ def build_insurance_template_xlsx(db: Session) -> BytesIO:
|
||||
wb.save(buf)
|
||||
buf.seek(0)
|
||||
return buf
|
||||
|
||||
|
||||
Reference in New Issue
Block a user