fix alembic migration
This commit is contained in:
33
api/app/core/alembic_revision_repair.py
Normal file
33
api/app/core/alembic_revision_repair.py
Normal file
@@ -0,0 +1,33 @@
|
||||
"""修复已撤回 migration 写入的 alembic_version(跨环境一次性兼容)。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import Connection, text
|
||||
|
||||
_WITHDRAWN_0020_REVISIONS = frozenset(
|
||||
{
|
||||
"0020_add_tts_audio_urls_column",
|
||||
"0020_backfill_missing_schema",
|
||||
"0020_backfill_all_missing_columns",
|
||||
}
|
||||
)
|
||||
_REPAIR_TARGET_REVISION = "0018_users_language_preference"
|
||||
|
||||
|
||||
def try_repair_withdrawn_0020_revision(conn: Connection) -> bool:
|
||||
"""
|
||||
若当前 stamp 为已撤回的 0020_*,回退到 0018 以便重新执行 0019_align_legacy_schema。
|
||||
|
||||
返回 True 表示已执行 UPDATE;调用方负责 commit。
|
||||
"""
|
||||
row = conn.execute(text("SELECT version_num FROM alembic_version")).fetchone()
|
||||
if row is None:
|
||||
return False
|
||||
current = row[0]
|
||||
if current not in _WITHDRAWN_0020_REVISIONS:
|
||||
return False
|
||||
conn.execute(
|
||||
text("UPDATE alembic_version SET version_num = :target"),
|
||||
{"target": _REPAIR_TARGET_REVISION},
|
||||
)
|
||||
return True
|
||||
@@ -21,10 +21,27 @@ logger = get_logger(__name__)
|
||||
_API_DIR: Final[Path] = Path(__file__).resolve().parent.parent.parent
|
||||
|
||||
|
||||
def _repair_withdrawn_revision_stamp_if_needed() -> None:
|
||||
from sqlalchemy import create_engine
|
||||
|
||||
from app.core.alembic_revision_repair import try_repair_withdrawn_0020_revision
|
||||
from app.core.db import _database_url
|
||||
|
||||
engine = create_engine(_database_url())
|
||||
with engine.connect() as conn:
|
||||
if try_repair_withdrawn_0020_revision(conn):
|
||||
conn.commit()
|
||||
logger.warning(
|
||||
"alembic_version 曾为已撤回的 0020_*,已回退到 0018;"
|
||||
"将重新执行 0019_align_legacy_schema"
|
||||
)
|
||||
|
||||
|
||||
def _run_alembic_upgrade_once() -> None:
|
||||
from alembic.command import upgrade
|
||||
from alembic.config import Config
|
||||
|
||||
_repair_withdrawn_revision_stamp_if_needed()
|
||||
cfg = Config(str(_API_DIR / "alembic.ini"))
|
||||
upgrade(cfg, "head")
|
||||
|
||||
|
||||
Reference in New Issue
Block a user