"""直播履约 clean/legacy 流程分界。 - 存量任务统一标记为 legacy(flow_version=1); - 迁移执行时设置 clean_flow_started_at,之后的订单进入 clean 流程; - 已经是 clean 的任务不会再被自动调度逻辑回退。 """ from __future__ import annotations import sqlalchemy as sa from alembic import op revision: str = "20261124_0132" down_revision: str | None = "20261124_0131" branch_labels: str | None = None depends_on: str | None = None TASK_TABLE = "platform_fulfillment_tasks" SETTINGS_TABLE = "platform_fulfillment_settings" def _column_exists(table: str, name: str) -> bool: conn = op.get_bind() count = conn.execute( sa.text( "SELECT COUNT(*) FROM information_schema.columns " "WHERE table_schema = DATABASE() AND table_name = :table " "AND column_name = :name" ), {"table": table, "name": name}, ).scalar() return bool(count) def _index_exists(table: str, name: str) -> bool: conn = op.get_bind() count = conn.execute( sa.text( "SELECT COUNT(*) FROM information_schema.statistics " "WHERE table_schema = DATABASE() AND table_name = :table " "AND index_name = :name" ), {"table": table, "name": name}, ).scalar() return bool(count) def upgrade() -> None: if not _column_exists(TASK_TABLE, "flow_version"): op.add_column( TASK_TABLE, sa.Column( "flow_version", sa.Integer(), nullable=False, server_default="1", ), ) if not _index_exists(TASK_TABLE, "ix_platform_fulfillment_tasks_flow_version"): op.create_index( "ix_platform_fulfillment_tasks_flow_version", TASK_TABLE, ["flow_version"], ) if not _column_exists(SETTINGS_TABLE, "clean_flow_started_at"): op.add_column( SETTINGS_TABLE, sa.Column("clean_flow_started_at", sa.DateTime(), nullable=True), ) # 迁移执行时刻就是 Cutover;存量任务已在 flow_version 默认值 1。 op.execute( sa.text( """ UPDATE platform_fulfillment_settings SET clean_flow_started_at = UTC_TIMESTAMP() WHERE id = 1 AND clean_flow_started_at IS NULL """ ) ) def downgrade() -> None: if _column_exists(SETTINGS_TABLE, "clean_flow_started_at"): op.drop_column(SETTINGS_TABLE, "clean_flow_started_at") if _index_exists(TASK_TABLE, "ix_platform_fulfillment_tasks_flow_version"): op.drop_index( "ix_platform_fulfillment_tasks_flow_version", table_name=TASK_TABLE, ) if _column_exists(TASK_TABLE, "flow_version"): op.drop_column(TASK_TABLE, "flow_version")