initial commit
This commit is contained in:
@@ -0,0 +1,51 @@
|
||||
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)
|
||||
if col.name == "token_version":
|
||||
sql = f"ALTER TABLE {table_name} ADD COLUMN {col.name} INTEGER DEFAULT 0 NOT NULL"
|
||||
elif col.name == "acquisition_mode":
|
||||
sql = f"ALTER TABLE {table_name} ADD COLUMN {col.name} VARCHAR(20) DEFAULT 'purchased'"
|
||||
else:
|
||||
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
|
||||
Reference in New Issue
Block a user