|
| 1 | +"""可选:启动时自动执行 alembic 迁移(默认关,`AUTO_MIGRATE=true` 开启)。 |
| 2 | +
|
| 3 | +背景:本项目库多由 `*.sql` 初始化、**不在 alembic 管控下**(无 alembic_version 表)。直接 |
| 4 | +`alembic upgrade head` 会从 0001_baseline 重跑建表而报错。故本模块: |
| 5 | + 1) 已纳管(有 alembic_version)→ 直接 `upgrade head`; |
| 6 | + 2) 未纳管 → 先 `stamp` 到基线(`AUTO_MIGRATE_BASELINE`,默认 `0002_seed_system`,即 ezdata.sql 对应的 |
| 7 | + "建表+种子"状态)再 `upgrade head`。配合幂等迁移(add/alter 前查存在性),无论新库/滞后库都安全。 |
| 8 | +迁移失败只记日志、**不阻断启动**。 |
| 9 | +""" |
| 10 | + |
| 11 | +import os |
| 12 | + |
| 13 | +from utils.log_util import logger |
| 14 | + |
| 15 | + |
| 16 | +def _truthy(v: str | None) -> bool: |
| 17 | + return str(v or '').strip().lower() in ('1', 'true', 'yes', 'on') |
| 18 | + |
| 19 | + |
| 20 | +def run_auto_migrate() -> None: |
| 21 | + """按 AUTO_MIGRATE 开关执行 alembic 迁移(同步阻塞,由调用方 threadpool 包裹)。""" |
| 22 | + if not _truthy(os.getenv('AUTO_MIGRATE')): |
| 23 | + return |
| 24 | + try: |
| 25 | + from alembic import command # noqa: PLC0415 |
| 26 | + from alembic.config import Config # noqa: PLC0415 |
| 27 | + from alembic.runtime.migration import MigrationContext # noqa: PLC0415 |
| 28 | + from sqlalchemy import create_engine # noqa: PLC0415 |
| 29 | + |
| 30 | + from config.database import SYNC_SQLALCHEMY_DATABASE_URL # noqa: PLC0415 |
| 31 | + |
| 32 | + eng = create_engine(SYNC_SQLALCHEMY_DATABASE_URL) |
| 33 | + try: |
| 34 | + with eng.connect() as conn: |
| 35 | + current = MigrationContext.configure(conn).get_current_revision() |
| 36 | + finally: |
| 37 | + eng.dispose() |
| 38 | + |
| 39 | + cfg = Config('alembic.ini') |
| 40 | + if current is None: # 库未纳入 alembic:先标记到基线,避免从 baseline 重跑 |
| 41 | + baseline = (os.getenv('AUTO_MIGRATE_BASELINE') or '0002_seed_system').strip() |
| 42 | + logger.info(f'🔖 AUTO_MIGRATE: 库未纳入 alembic,先 stamp 到 {baseline}') |
| 43 | + command.stamp(cfg, baseline) |
| 44 | + logger.info('⛓️ AUTO_MIGRATE: alembic upgrade head …') |
| 45 | + command.upgrade(cfg, 'head') |
| 46 | + logger.info('✅️ AUTO_MIGRATE: 迁移完成') |
| 47 | + except Exception as e: # noqa: BLE001 |
| 48 | + logger.error(f'❌ AUTO_MIGRATE 迁移失败(不阻断启动,可手动处理): {e}') |
0 commit comments