feat(freight-rpa): 库存/收料改名在手/入站,报表归属RPA,类名统一FreightRpa
把 shipping 侧 inventory/receipt 词根迁到 onhand/inbound,29 张表与 枚举/权限/前端/i18n 同步改名;在手与入站报表配置及文件改由 freight_rpa 持有,发货与调拨仅按 source_code 消费;ORM 类加 FreightRpa 前缀, 上传动作改为 freight_rpa_upload。含类名与上传动作改名规格文档。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
ffc0d4a430
commit
39fe3c05f2
453 files changed
+17945
-8646
No files matched your search
@@ -0,0 +1,564 @@
|
||||
"""
|
||||
migrations/versions/s17b1c2d3e4f5a_freight_rpa_batch_s_rename_tables.py
|
||||
|
||||
用途:批次 S 只改表结构——29 张货代 RPA / 发货库存表一次 rename,并改写这些表上的
|
||||
inventory/receipt 列名,以及名称里含旧表名的索引、主键、唯一、检查、外键。
|
||||
模型类与 __tablename__ 仍用旧名,留到后续任务。
|
||||
依赖:alembic.op、SQLAlchemy 反射;down_revision 为当前单 head tt16c7d8e9f0a1b2。
|
||||
逻辑:先按列规则改列,再 rename_table(PG/SQLite 都会改外键指向的表),最后扫全库
|
||||
对象名,把旧表名替换成新表名。验证批次索引
|
||||
ix_inventory_test_run_validation_batch 一对一改成
|
||||
ix_fr_onhand_cfg_test_runs_validation_batch_id。历史迁移没有单列
|
||||
recipient 索引,升级在新表上补建 ix_fr_inbound_notif_deliveries_recipient_user_id,
|
||||
降级删掉,不还原一个不存在的旧名。复合索引
|
||||
ix_shipping_receipt_delivery_file_recipient 不含完整旧表名,不改。
|
||||
PostgreSQL 用 ALTER ... RENAME;SQLite 对索引是重建,对表内约束是 batch 重建。
|
||||
downgrade 按相反顺序还原。不改 29 张以外的表(含 shipping_notice_freight_cancellations)上的列。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision = "s17b1c2d3e4f5a"
|
||||
down_revision = "tt16c7d8e9f0a1b2"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
# PostgreSQL 标识符上限(NAMEDATALEN-1)。ASCII 名称按字符计即按字节计。
|
||||
_MAX_IDENTIFIER_LENGTH = 63
|
||||
|
||||
# (旧表, 新表)。顺序与批次 S 任务书一致。
|
||||
_TABLE_RENAMES: list[tuple[str, str]] = [
|
||||
("shipping_inventory_sources", "freight_rpa_sources"),
|
||||
("shipping_rpa_profiles", "freight_rpa_profiles"),
|
||||
("shipping_inventory_fields", "freight_rpa_onhand_fields"),
|
||||
("shipping_inventory_source_parsing_binding_audits", "freight_rpa_onhand_source_parsing_binding_audits"),
|
||||
("shipping_inventory_parsing_profiles", "freight_rpa_parsing_profiles"),
|
||||
("shipping_inventory_structure_analyses", "freight_rpa_onhand_structure_analyses"),
|
||||
("shipping_inventory_configuration_test_runs", "freight_rpa_onhand_configuration_test_runs"),
|
||||
("shipping_inventory_validation_batches", "freight_rpa_onhand_validation_batches"),
|
||||
("shipping_inventory_routing_rules", "freight_rpa_onhand_routing_rules"),
|
||||
("shipping_inventory_routing_rule_conditions", "freight_rpa_onhand_routing_rule_conditions"),
|
||||
("shipping_inventory_routing_rule_versions", "freight_rpa_onhand_routing_rule_versions"),
|
||||
("shipping_inventory_external_mappings", "freight_rpa_onhand_external_mappings"),
|
||||
("shipping_inventory_mappings", "freight_rpa_onhand_mappings"),
|
||||
("shipping_task_inventory_rpa_attempts", "freight_rpa_onhand_task_rpa_attempts"),
|
||||
("shipping_receipt_report_configs", "freight_rpa_inbound_report_configs"),
|
||||
("shipping_receipt_rpa_unit_runs", "freight_rpa_inbound_rpa_unit_runs"),
|
||||
("shipping_receipt_report_files", "freight_rpa_inbound_report_files"),
|
||||
("shipping_receipt_notification_deliveries", "freight_rpa_inbound_notification_deliveries"),
|
||||
("shipping_inventory_files", "shipping_onhand_files"),
|
||||
("shipping_inventory_candidate_sets", "shipping_onhand_candidate_sets"),
|
||||
("shipping_inventory_candidate_sources", "shipping_onhand_candidate_sources"),
|
||||
("shipping_inventory_candidate_lines", "shipping_onhand_candidate_lines"),
|
||||
("shipping_inventory_preparation_attempts", "shipping_onhand_preparation_attempts"),
|
||||
("shipping_inventory_preparation_source_attempts", "shipping_onhand_preparation_source_attempts"),
|
||||
("shipping_task_inventory_links", "shipping_task_onhand_links"),
|
||||
("shipping_temporary_inventory_sessions", "shipping_temporary_onhand_sessions"),
|
||||
("shipping_notice_line_inventory_matches", "shipping_notice_line_onhand_matches"),
|
||||
("shipping_notice_inventory_verifications", "shipping_notice_onhand_verifications"),
|
||||
("shipping_notice_inventory_verification_lines", "shipping_notice_onhand_verification_lines"),
|
||||
]
|
||||
|
||||
# 显式列对照优先于「名字里的 inventory 换成 onhand」。
|
||||
_EXPLICIT_COLUMNS = {
|
||||
"inventory_source_id": "source_id",
|
||||
"inventory_snapshot_id": "onhand_snapshot_id",
|
||||
"inventory_file_id": "onhand_file_id",
|
||||
"inventory_source_code": "source_code",
|
||||
"active_inventory_candidate_set_id": "active_onhand_candidate_set_id",
|
||||
}
|
||||
|
||||
_RECEIPT_TABLES = frozenset({
|
||||
"shipping_receipt_report_configs",
|
||||
"shipping_receipt_rpa_unit_runs",
|
||||
"shipping_receipt_report_files",
|
||||
"shipping_receipt_notification_deliveries",
|
||||
})
|
||||
|
||||
# 替换后超过 63 字节、降级必须回到原名的对象。其余名称不截断。
|
||||
_EXACT_ORIGINS = (
|
||||
"shipping_receipt_notification_deliveries_recipient_user_id_fkey",
|
||||
)
|
||||
|
||||
# 只映射历史迁移真正建过的索引。aa1 的验证批次索引一对一换成模型短名。
|
||||
# 不收录 SQLAlchemy index=True 的自动名:库里没有那条 65 字节索引。
|
||||
_EXPLICIT_INDEX_NAMES = {
|
||||
"ix_inventory_test_run_validation_batch": "ix_fr_onhand_cfg_test_runs_validation_batch_id",
|
||||
}
|
||||
|
||||
# hi3 只建了复合索引 ix_shipping_receipt_delivery_file_recipient,没有单列 recipient 索引。
|
||||
# 升级在已改名的表上补建模型短名;降级删除,不假装有旧名可还原。
|
||||
_CREATED_RECIPIENT_INDEX = "ix_fr_inbound_notif_deliveries_recipient_user_id"
|
||||
_CREATED_RECIPIENT_TABLE = "freight_rpa_inbound_notification_deliveries"
|
||||
_CREATED_RECIPIENT_COLUMNS = ["recipient_user_id"]
|
||||
|
||||
|
||||
def _quote_ident(name: str) -> str:
|
||||
"""给 SQL 标识符加双引号,内部引号按标准加倍。
|
||||
|
||||
Args:
|
||||
name: 表、索引或约束名。
|
||||
|
||||
Returns:
|
||||
可拼进 DDL 的引用标识符。
|
||||
"""
|
||||
return '"' + name.replace('"', '""') + '"'
|
||||
|
||||
|
||||
def _substitute(name: str, pairs: list[tuple[str, str]]) -> str:
|
||||
"""把对象名中的表名 token 换成对照表里的另一个名字。
|
||||
|
||||
核心逻辑:按源 token 长度降序替换,避免短表名吃掉更长表名的前缀。
|
||||
调用方保证这 29 个旧名彼此不是子串,新名同理。
|
||||
|
||||
Args:
|
||||
name: 当前索引或约束名。
|
||||
pairs: (被替换的表名, 替换后的表名)。升级用旧→新,降级用新→旧。
|
||||
|
||||
Returns:
|
||||
替换后的对象名(尚未按 63 字节截断)。
|
||||
"""
|
||||
updated = name
|
||||
for source, destination in sorted(pairs, key=lambda item: len(item[0]), reverse=True):
|
||||
updated = updated.replace(source, destination)
|
||||
return updated
|
||||
|
||||
|
||||
def _clip(name: str) -> str:
|
||||
"""把标识符限制在 PostgreSQL 的 63 字节以内。
|
||||
|
||||
Args:
|
||||
name: 已完成表名替换的对象名。
|
||||
|
||||
Returns:
|
||||
长度不超过 63 的名字。未超长时原样返回。
|
||||
"""
|
||||
if len(name) <= _MAX_IDENTIFIER_LENGTH:
|
||||
return name
|
||||
return name[:_MAX_IDENTIFIER_LENGTH]
|
||||
|
||||
|
||||
def _target_name(current: str, pairs: list[tuple[str, str]], *, reverse: bool) -> str:
|
||||
"""计算对象改名的目标。
|
||||
|
||||
核心逻辑:_EXPLICIT_INDEX_NAMES 一对一改名,降级回到唯一的旧名。
|
||||
其余正向是表名替换再截断。反向时,若当前名正是某个已知超长原名的截断结果,
|
||||
则回到那个原名,避免降级丢掉被切掉的后缀。
|
||||
|
||||
Args:
|
||||
current: 库里现在的对象名。
|
||||
pairs: 本方向的表名替换对。
|
||||
reverse: True 表示 downgrade。
|
||||
|
||||
Returns:
|
||||
应改成的对象名。与 current 相同表示不用改。
|
||||
"""
|
||||
if reverse:
|
||||
for origin, short in _EXPLICIT_INDEX_NAMES.items():
|
||||
if current == short:
|
||||
return origin
|
||||
for origin in _EXACT_ORIGINS:
|
||||
if _clip(_substitute(origin, _TABLE_RENAMES)) == current:
|
||||
return origin
|
||||
elif current in _EXPLICIT_INDEX_NAMES:
|
||||
return _EXPLICIT_INDEX_NAMES[current]
|
||||
return _clip(_substitute(current, pairs))
|
||||
|
||||
|
||||
def _forward_column_name(table: str, column: str) -> str:
|
||||
"""按批次 S 列规则计算升级后的列名。
|
||||
|
||||
核心逻辑:五条显式对照优先;其余列名中的 inventory 换成 onhand;
|
||||
仅四张原 shipping_receipt_* 表再把 receipt 换成 inbound。
|
||||
|
||||
Args:
|
||||
table: 仍是旧表名的表。
|
||||
column: 当前列名。
|
||||
|
||||
Returns:
|
||||
新列名。无需改名时与 column 相同。
|
||||
"""
|
||||
renamed = _EXPLICIT_COLUMNS.get(column)
|
||||
if renamed is None:
|
||||
renamed = column.replace("inventory", "onhand") if "inventory" in column else column
|
||||
if table in _RECEIPT_TABLES and "receipt" in renamed:
|
||||
renamed = renamed.replace("receipt", "inbound")
|
||||
return renamed
|
||||
|
||||
|
||||
def _reverse_column_name(table: str, column: str) -> str:
|
||||
"""按升级规则的逆运算还原列名。
|
||||
|
||||
核心逻辑:先在四张 receipt 表上把 inbound 换回 receipt,再还原显式对照。
|
||||
source_code 只有 shipping_notice_line_inventory_matches 来自 inventory_source_code;
|
||||
其他表上本来就有的 source_code 必须留下。其余 onhand 换回 inventory。
|
||||
|
||||
Args:
|
||||
table: 已经改回旧表名的表。
|
||||
column: 升级后的列名。
|
||||
|
||||
Returns:
|
||||
升级前的列名。
|
||||
"""
|
||||
name = column
|
||||
if table in _RECEIPT_TABLES and "inbound" in name:
|
||||
name = name.replace("inbound", "receipt")
|
||||
if name == "source_id":
|
||||
return "inventory_source_id"
|
||||
if name == "source_code" and table == "shipping_notice_line_inventory_matches":
|
||||
return "inventory_source_code"
|
||||
if "onhand" in name:
|
||||
return name.replace("onhand", "inventory")
|
||||
return name
|
||||
|
||||
|
||||
def _rename_columns(table: str, renamer) -> None:
|
||||
"""把一张表上需要改名的列一次改完,目标名冲突则中止。
|
||||
|
||||
核心逻辑:先根据反射列算出对照,目标名彼此重复或撞上保留列就抛错,
|
||||
避免 ALTER 中途把两列收成同名。SQLite 与 PostgreSQL 都走 op.alter_column。
|
||||
|
||||
Args:
|
||||
table: 当前表名。
|
||||
renamer: 接受列名、返回新列名的函数。
|
||||
|
||||
Raises:
|
||||
RuntimeError: 目标列名已存在或两条列改到同一个名字。
|
||||
"""
|
||||
columns = sa.inspect(op.get_bind()).get_columns(table)
|
||||
planned: list[tuple[dict, str]] = []
|
||||
for column in columns:
|
||||
target = renamer(column["name"])
|
||||
if target != column["name"]:
|
||||
planned.append((column, target))
|
||||
staying = {column["name"] for column in columns} - {column["name"] for column, _target in planned}
|
||||
targets = [target for _column, target in planned]
|
||||
duplicates = sorted({name for name in targets if targets.count(name) > 1})
|
||||
occupied = sorted(target for target in targets if target in staying)
|
||||
if duplicates or occupied:
|
||||
raise RuntimeError(
|
||||
f"column rename collision on {table}: duplicates={duplicates} occupied={occupied}"
|
||||
)
|
||||
for column, target in planned:
|
||||
op.alter_column(
|
||||
table,
|
||||
column["name"],
|
||||
new_column_name=target,
|
||||
existing_type=column["type"],
|
||||
existing_nullable=column["nullable"],
|
||||
)
|
||||
|
||||
|
||||
def _iter_constraints(inspector, table: str):
|
||||
"""列出一张表上带名字的外键、唯一、检查和主键约束。
|
||||
|
||||
Args:
|
||||
inspector: 当前连接的 SQLAlchemy Inspector。
|
||||
table: 表名。
|
||||
|
||||
Yields:
|
||||
(kind, name, payload)。kind 使用 alembic batch 的 type_ 取值。
|
||||
外键 payload 是反射字典,唯一/主键 payload 是列名列表,检查 payload 是表达式。
|
||||
"""
|
||||
for foreign_key in inspector.get_foreign_keys(table) or []:
|
||||
yield "foreignkey", foreign_key.get("name"), foreign_key
|
||||
for unique in inspector.get_unique_constraints(table) or []:
|
||||
yield "unique", unique.get("name"), list(unique.get("column_names") or [])
|
||||
for check in inspector.get_check_constraints(table) or []:
|
||||
yield "check", check.get("name"), check.get("sqltext")
|
||||
primary = inspector.get_pk_constraint(table) or {}
|
||||
yield "primary", primary.get("name"), list(primary.get("constrained_columns") or [])
|
||||
|
||||
|
||||
def _collect_renames(bind, pairs: list[tuple[str, str]], *, reverse: bool) -> dict:
|
||||
"""扫描全库,收集名称中含表名 token、因而需要改名的索引和约束。
|
||||
|
||||
核心逻辑:PostgreSQL 上唯一/主键约束与其支撑索引同名,只改约束
|
||||
(RENAME CONSTRAINT 会带走索引)。SQLite 上独立索引用重建,
|
||||
表内约束才进 batch;同名时以索引为准,避免拆掉已经改过的索引。
|
||||
|
||||
Args:
|
||||
bind: 当前迁移连接。
|
||||
pairs: 本方向的表名替换对。
|
||||
reverse: True 表示 downgrade。
|
||||
|
||||
Returns:
|
||||
{表名: (索引列表[(旧, 新)], 约束列表[(kind, 旧, 新, payload)])}。
|
||||
"""
|
||||
inspector = sa.inspect(bind)
|
||||
dialect = bind.dialect.name
|
||||
planned: dict[str, tuple[list, list]] = {}
|
||||
for table in inspector.get_table_names():
|
||||
if table.startswith("sqlite_"):
|
||||
continue
|
||||
raw_indexes = []
|
||||
for index in inspector.get_indexes(table) or []:
|
||||
name = index.get("name")
|
||||
if name and not str(name).startswith("sqlite_"):
|
||||
raw_indexes.append(name)
|
||||
raw_constraints = []
|
||||
for kind, name, payload in _iter_constraints(inspector, table):
|
||||
if name and not str(name).startswith("sqlite_"):
|
||||
raw_constraints.append((kind, name, payload))
|
||||
|
||||
index_rows: list[tuple[str, str]] = []
|
||||
constraint_rows: list[tuple[str, str, str, object]] = []
|
||||
if dialect == "postgresql":
|
||||
constraint_names = {name for _kind, name, _payload in raw_constraints}
|
||||
for kind, name, payload in raw_constraints:
|
||||
target = _target_name(name, pairs, reverse=reverse)
|
||||
if target != name:
|
||||
constraint_rows.append((kind, name, target, payload))
|
||||
for name in raw_indexes:
|
||||
if name in constraint_names:
|
||||
continue
|
||||
target = _target_name(name, pairs, reverse=reverse)
|
||||
if target != name:
|
||||
index_rows.append((name, target))
|
||||
else:
|
||||
index_names = set(raw_indexes)
|
||||
for name in raw_indexes:
|
||||
target = _target_name(name, pairs, reverse=reverse)
|
||||
if target != name:
|
||||
index_rows.append((name, target))
|
||||
for kind, name, payload in raw_constraints:
|
||||
if name in index_names:
|
||||
continue
|
||||
target = _target_name(name, pairs, reverse=reverse)
|
||||
if target != name:
|
||||
constraint_rows.append((kind, name, target, payload))
|
||||
if index_rows or constraint_rows:
|
||||
planned[table] = (index_rows, constraint_rows)
|
||||
_reject_collisions(planned, _existing_object_names(inspector))
|
||||
return planned
|
||||
|
||||
|
||||
def _existing_object_names(inspector) -> set[str]:
|
||||
"""收集当前库里全部索引名和约束名,供目标名冲突检查。
|
||||
|
||||
Args:
|
||||
inspector: 当前连接的 Inspector。
|
||||
|
||||
Returns:
|
||||
已占用的对象名集合。
|
||||
"""
|
||||
found: set[str] = set()
|
||||
for table in inspector.get_table_names():
|
||||
if table.startswith("sqlite_"):
|
||||
continue
|
||||
for index in inspector.get_indexes(table) or []:
|
||||
if index.get("name"):
|
||||
found.add(index["name"])
|
||||
for _kind, name, _payload in _iter_constraints(inspector, table):
|
||||
if name:
|
||||
found.add(name)
|
||||
return found
|
||||
|
||||
|
||||
def _reject_collisions(planned: dict, existing: set[str]) -> None:
|
||||
"""目标对象名不能互相重复,也不能盖住一个本次不改名的既有对象。
|
||||
|
||||
Args:
|
||||
planned: _collect_renames 的结果。
|
||||
existing: 当前已占用的对象名。
|
||||
|
||||
Raises:
|
||||
RuntimeError: 两个对象要改成同一个名字,或目标名已被占用。
|
||||
"""
|
||||
sources: list[str] = []
|
||||
targets: list[str] = []
|
||||
for index_rows, constraint_rows in planned.values():
|
||||
for old, new in index_rows:
|
||||
sources.append(old)
|
||||
targets.append(new)
|
||||
for _kind, old, new, _payload in constraint_rows:
|
||||
sources.append(old)
|
||||
targets.append(new)
|
||||
if len(targets) != len(set(targets)):
|
||||
raise RuntimeError(f"object rename target collision: {targets}")
|
||||
source_set = set(sources)
|
||||
occupied = sorted(target for target in targets if target in existing and target not in source_set)
|
||||
if occupied:
|
||||
raise RuntimeError(f"object rename would overwrite existing names: {occupied}")
|
||||
|
||||
|
||||
def _rename_index(bind, old_name: str, new_name: str) -> None:
|
||||
"""改索引名。PostgreSQL 用 ALTER INDEX;SQLite 按 sqlite_master 重建。
|
||||
|
||||
Args:
|
||||
bind: 当前迁移连接。
|
||||
old_name: 现名。
|
||||
new_name: 新名。
|
||||
|
||||
Raises:
|
||||
RuntimeError: SQLite 找不到可重建的 CREATE INDEX 语句。
|
||||
"""
|
||||
if bind.dialect.name == "postgresql":
|
||||
op.execute(sa.text(
|
||||
f"ALTER INDEX {_quote_ident(old_name)} RENAME TO {_quote_ident(new_name)}"
|
||||
))
|
||||
return
|
||||
row = bind.execute(
|
||||
sa.text("SELECT sql FROM sqlite_master WHERE type = 'index' AND name = :name"),
|
||||
{"name": old_name},
|
||||
).fetchone()
|
||||
if row is None or not row[0]:
|
||||
raise RuntimeError(f"sqlite index {old_name} has no SQL to rebuild")
|
||||
sql = row[0]
|
||||
quoted = f'"{old_name}"'
|
||||
if quoted in sql:
|
||||
rebuilt = sql.replace(quoted, _quote_ident(new_name), 1)
|
||||
elif old_name in sql:
|
||||
rebuilt = sql.replace(old_name, new_name, 1)
|
||||
else:
|
||||
raise RuntimeError(f"index SQL does not contain {old_name}: {sql}")
|
||||
op.execute(sa.text(f"DROP INDEX {_quote_ident(old_name)}"))
|
||||
op.execute(sa.text(rebuilt))
|
||||
|
||||
|
||||
def _rename_constraints(bind, table: str, constraints: list) -> None:
|
||||
"""改一张表上的约束名。
|
||||
|
||||
核心逻辑:PostgreSQL 只 RENAME CONSTRAINT,不重建表。SQLite 没有
|
||||
RENAME CONSTRAINT,用一次 batch 先删后建,保留列、删除动作和外键目标。
|
||||
|
||||
Args:
|
||||
bind: 当前迁移连接。
|
||||
table: 约束所在表(已经是本阶段的表名)。
|
||||
constraints: (kind, 旧名, 新名, payload) 列表。
|
||||
"""
|
||||
if not constraints:
|
||||
return
|
||||
if bind.dialect.name == "postgresql":
|
||||
for _kind, old_name, new_name, _payload in constraints:
|
||||
op.execute(sa.text(
|
||||
f"ALTER TABLE {_quote_ident(table)} "
|
||||
f"RENAME CONSTRAINT {_quote_ident(old_name)} TO {_quote_ident(new_name)}"
|
||||
))
|
||||
return
|
||||
with op.batch_alter_table(table) as batch:
|
||||
for kind, old_name, _new_name, _payload in constraints:
|
||||
batch.drop_constraint(old_name, type_=kind)
|
||||
for kind, _old_name, new_name, payload in constraints:
|
||||
if kind == "foreignkey":
|
||||
options = payload.get("options") or {}
|
||||
batch.create_foreign_key(
|
||||
new_name,
|
||||
payload["referred_table"],
|
||||
payload["constrained_columns"],
|
||||
payload["referred_columns"],
|
||||
ondelete=options.get("ondelete"),
|
||||
onupdate=options.get("onupdate"),
|
||||
deferrable=options.get("deferrable"),
|
||||
initially=options.get("initially"),
|
||||
match=options.get("match"),
|
||||
referent_schema=payload.get("referred_schema"),
|
||||
)
|
||||
elif kind == "unique":
|
||||
batch.create_unique_constraint(new_name, payload)
|
||||
elif kind == "check":
|
||||
batch.create_check_constraint(new_name, payload)
|
||||
elif kind == "primary":
|
||||
batch.create_primary_key(new_name, payload)
|
||||
else:
|
||||
raise RuntimeError(f"unsupported constraint kind {kind}")
|
||||
|
||||
|
||||
def _rewrite_object_names(pairs: list[tuple[str, str]], *, reverse: bool) -> None:
|
||||
"""改写全库里名称包含旧/新表名的索引和约束。
|
||||
|
||||
核心逻辑:SQLite 先改索引再 batch 约束,这样 batch 反射到的是新索引名。
|
||||
PostgreSQL 先改约束(连带支撑索引),再改剩余普通索引。
|
||||
|
||||
Args:
|
||||
pairs: 本方向的表名替换对。
|
||||
reverse: True 表示 downgrade。
|
||||
"""
|
||||
bind = op.get_bind()
|
||||
planned = _collect_renames(bind, pairs, reverse=reverse)
|
||||
if bind.dialect.name == "postgresql":
|
||||
for table, (_indexes, constraints) in planned.items():
|
||||
_rename_constraints(bind, table, constraints)
|
||||
for _table, (indexes, _constraints) in planned.items():
|
||||
for old_name, new_name in indexes:
|
||||
_rename_index(bind, old_name, new_name)
|
||||
return
|
||||
for _table, (indexes, _constraints) in planned.items():
|
||||
for old_name, new_name in indexes:
|
||||
_rename_index(bind, old_name, new_name)
|
||||
refreshed = _collect_renames(bind, pairs, reverse=reverse)
|
||||
for table, (_indexes, constraints) in refreshed.items():
|
||||
_rename_constraints(bind, table, constraints)
|
||||
|
||||
|
||||
def _index_names(table: str) -> set[str]:
|
||||
"""列出一张表上当前的索引名。
|
||||
|
||||
Args:
|
||||
table: 当前表名。
|
||||
|
||||
Returns:
|
||||
非空索引名集合。表不存在时返回空集。
|
||||
"""
|
||||
bind = op.get_bind()
|
||||
inspector = sa.inspect(bind)
|
||||
if table not in set(inspector.get_table_names()):
|
||||
return set()
|
||||
return {index["name"] for index in inspector.get_indexes(table) or [] if index.get("name")}
|
||||
|
||||
|
||||
def _ensure_recipient_index() -> None:
|
||||
"""补建入站投递单列索引,名字与模型一致。
|
||||
|
||||
核心逻辑:历史迁移没有这条索引。表已经改成新名之后,短名不存在才创建,
|
||||
避免重复升级再插一条同名索引。
|
||||
"""
|
||||
if _CREATED_RECIPIENT_INDEX not in _index_names(_CREATED_RECIPIENT_TABLE):
|
||||
op.create_index(
|
||||
_CREATED_RECIPIENT_INDEX,
|
||||
_CREATED_RECIPIENT_TABLE,
|
||||
_CREATED_RECIPIENT_COLUMNS,
|
||||
)
|
||||
|
||||
|
||||
def _drop_recipient_index() -> None:
|
||||
"""删掉升级补建的入站投递单列索引。
|
||||
|
||||
核心逻辑:这条索引没有旧名。降级开始时表仍是新名,按短名删除;不存在则跳过。
|
||||
"""
|
||||
if _CREATED_RECIPIENT_INDEX in _index_names(_CREATED_RECIPIENT_TABLE):
|
||||
op.drop_index(_CREATED_RECIPIENT_INDEX, table_name=_CREATED_RECIPIENT_TABLE)
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""29 表升级:改列、改表名、再改索引与约束名。
|
||||
|
||||
核心逻辑:列改名发生在旧表名上,这样 receipt 表仍能被识别。
|
||||
rename_table 之后外键指向的表已经是新名,对象名扫描只改名字不改指向。
|
||||
最后补建历史迁移里不存在的单列 recipient 索引。
|
||||
"""
|
||||
for old, _new in _TABLE_RENAMES:
|
||||
_rename_columns(old, lambda column, table=old: _forward_column_name(table, column))
|
||||
for old, new in _TABLE_RENAMES:
|
||||
op.rename_table(old, new)
|
||||
_rewrite_object_names(_TABLE_RENAMES, reverse=False)
|
||||
_ensure_recipient_index()
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""按升级的相反顺序还原对象名、表名和列名。
|
||||
|
||||
核心逻辑:先删掉升级补建的单列索引,再还原其余对象名。验证批次索引
|
||||
经 _EXPLICIT_INDEX_NAMES 回到 ix_inventory_test_run_validation_batch。
|
||||
"""
|
||||
_drop_recipient_index()
|
||||
reverse_pairs = [(new, old) for old, new in _TABLE_RENAMES]
|
||||
_rewrite_object_names(reverse_pairs, reverse=True)
|
||||
for old, new in reversed(_TABLE_RENAMES):
|
||||
op.rename_table(new, old)
|
||||
for old, _new in reversed(_TABLE_RENAMES):
|
||||
_rename_columns(old, lambda column, table=old: _reverse_column_name(table, column))
|
||||
@@ -0,0 +1,481 @@
|
||||
"""
|
||||
migrations/versions/s17c2d3e4f5a6_freight_rpa_batch_s_enum_data.py
|
||||
|
||||
用途:批次 S 第二段,只改存量字符串,不改 s17b 的表结构。
|
||||
把 job_type、options_source、权限模块键、审计/任务事件名、
|
||||
step/stage/action 契约码从 inventory/receipt 词根改成 onhand/inbound。
|
||||
依赖:alembic.op、SQLAlchemy;down_revision 为 s17b1c2d3e4f5a。
|
||||
逻辑:按词边界替换已知列里的文本(JSON 先转成文本再写回,避免改格式)。
|
||||
权限模块键只替换 JSON 键 "shipping_inventory",并写入私有标记
|
||||
__s17c_perm_module;降级只回滚带该标记的行。
|
||||
PostgreSQL 上 shipping_audit_events 的 UPDATE 触发器在本迁移语句内临时关闭。
|
||||
改写审计字段后用 audit_snapshot_service 的同一套哈希重算 event_hash。
|
||||
不改 shipment_* / freight_upload*,也不改 s17b。
|
||||
schedule_tasks.data_source_type 的历史整值改成现行 job key freight-rpa-onhand。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision = "s17c2d3e4f5a6"
|
||||
down_revision = "s17b1c2d3e4f5a"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
# 升级方向。更长的旧词必须排在前面,避免短词先吃掉长词的一部分。
|
||||
_EXACT_PAIRS: tuple[tuple[str, str], ...] = (
|
||||
("retry_inventory_from_field_mapping", "retry_onhand_from_field_mapping"),
|
||||
("retry_inventory_from_preparation", "retry_onhand_from_preparation"),
|
||||
("retry_inventory_from_matching", "retry_onhand_from_matching"),
|
||||
("refresh_inventory_candidate_projection", "refresh_onhand_candidate_projection"),
|
||||
("override_line_inventory_source", "override_line_onhand_source"),
|
||||
("recheck_inventory_sufficiency", "recheck_onhand_sufficiency"),
|
||||
("retry_inventory_field_mapping", "retry_onhand_field_mapping"),
|
||||
("retry_inventory_preparation", "retry_onhand_preparation"),
|
||||
("poll_inventory_preparation", "poll_onhand_preparation"),
|
||||
("open_inventory_match_review", "open_onhand_match_review"),
|
||||
("retry_inventory_matching", "retry_onhand_matching"),
|
||||
("reload_inventory_result", "reload_onhand_result"),
|
||||
("download_inventory_file", "download_onhand_file"),
|
||||
("release_inventory_shortage", "release_onhand_shortage"),
|
||||
("upload_inventory_file", "upload_onhand_file"),
|
||||
("inventory_source_resolving", "onhand_source_resolving"),
|
||||
("inventory_source_routing", "onhand_source_routing"),
|
||||
("inventory_field_mapping", "onhand_field_mapping"),
|
||||
("inventory_preparation", "onhand_preparation"),
|
||||
("inventory_sufficiency", "onhand_sufficiency"),
|
||||
("shipping_inventory_callback_process", "freight_rpa_onhand_callback_process"),
|
||||
("shipping_inventory_callback_ignored", "freight_rpa_onhand_callback_ignored"),
|
||||
("shipping_inventory_sources", "freight_rpa_sources"),
|
||||
("shipping_receipt_sources", "freight_rpa_inbound_sources"),
|
||||
("shipping_receipt_rpa_callback_received", "shipping_inbound_rpa_callback_received"),
|
||||
("shipping_receipt_rpa_callback_timeout", "shipping_inbound_rpa_callback_timeout"),
|
||||
("shipping_receipt_rpa_units_listed", "shipping_inbound_rpa_units_listed"),
|
||||
("shipping_receipt_rpa_unit_retried", "shipping_inbound_rpa_unit_retried"),
|
||||
("rpa_report_inventory", "rpa_report_onhand"),
|
||||
("step3_inventory_prepare", "step3_onhand_prepare"),
|
||||
("step5_match_inventory", "step5_match_onhand"),
|
||||
("inventory_fetching", "onhand_fetching"),
|
||||
("inventory_matching", "onhand_matching"),
|
||||
("wait_inventory", "wait_onhand"),
|
||||
("ensure_inventory", "ensure_onhand"),
|
||||
)
|
||||
|
||||
# 权限模块 JSON 键。降级只认本迁移写入的标记,避免把 Task 5 已有的 freight_rpa 改回去。
|
||||
_PERMISSION_MARKER = "__s17c_perm_module"
|
||||
|
||||
# (表, 列, 是否 JSON)。缺表或缺列则跳过。
|
||||
_COLUMNS: tuple[tuple[str, str, bool], ...] = (
|
||||
("jobs", "job_type", False),
|
||||
("jobs", "payload_json", True),
|
||||
("jobs", "result_json", True),
|
||||
("jobs", "message", False),
|
||||
("jobs", "error_message", False),
|
||||
("kb_jobs", "job_type", False),
|
||||
("schedule_tasks", "job_params", True),
|
||||
("shipping_order_tasks", "stage", False),
|
||||
("shipping_order_tasks", "current_step", False),
|
||||
("shipping_order_tasks", "pending_human_reason", False),
|
||||
("shipping_order_tasks", "error_code", False),
|
||||
("shipping_order_tasks", "step_payload_json", True),
|
||||
("shipping_order_processing_runs", "current_stage_code", False),
|
||||
("shipping_order_processing_runs", "progress_summary_json", True),
|
||||
("shipping_task_events", "event_type", False),
|
||||
("shipping_task_events", "source", False),
|
||||
("shipping_task_events", "detail_json", True),
|
||||
("shipping_task_events", "before_json", True),
|
||||
("shipping_task_events", "after_json", True),
|
||||
("shipping_audit_events", "event_type", False),
|
||||
("shipping_audit_events", "source", False),
|
||||
("shipping_audit_events", "action", False),
|
||||
("shipping_audit_events", "reason_code", False),
|
||||
("shipping_audit_events", "error_code", False),
|
||||
("shipping_audit_events", "before_snapshot_json", True),
|
||||
("shipping_audit_events", "after_snapshot_json", True),
|
||||
("shipping_audit_events", "diff_json", True),
|
||||
("shipping_audit_events", "metadata_json", True),
|
||||
("shipping_audit_events", "context_refs_json", True),
|
||||
("shipping_process_executions", "current_gate_code", False),
|
||||
("shipping_process_executions", "last_passed_gate_code", False),
|
||||
("shipping_process_executions", "primary_next_action_code", False),
|
||||
("shipping_process_gates", "gate_code", False),
|
||||
("shipping_process_gates", "next_action_code", False),
|
||||
("shipping_process_gates", "blocking_reason_code", False),
|
||||
("shipping_process_gates", "blocking_reason_json", True),
|
||||
("shipping_process_gates", "recommendation_json", True),
|
||||
("shipping_process_gates", "effective_result_json", True),
|
||||
("shipping_process_gate_attempts", "input_snapshot_json", True),
|
||||
("shipping_process_gate_attempts", "output_snapshot_json", True),
|
||||
("shipping_process_gate_attempts", "rule_snapshot_json", True),
|
||||
("shipping_process_gate_attempts", "error_code", False),
|
||||
("shipping_process_recovery_plans", "current_gate", False),
|
||||
("shipping_process_recovery_plans", "action_code", False),
|
||||
("shipping_process_recovery_plans", "target_gate", False),
|
||||
("shipping_process_recovery_plans", "resume_after_gate", False),
|
||||
("shipping_process_recovery_plans", "failure_code", False),
|
||||
("shipping_process_recovery_plans", "invalidation_plan_json", True),
|
||||
("shipping_process_recovery_plans", "failure_detail_json", True),
|
||||
("shipping_onhand_preparation_attempts", "input_snapshot_json", True),
|
||||
("shipping_onhand_preparation_attempts", "output_snapshot_json", True),
|
||||
("shipping_onhand_preparation_source_attempts", "skip_reason", False),
|
||||
("freight_rpa_onhand_task_rpa_attempts", "error_code", False),
|
||||
("freight_rpa_onhand_task_rpa_attempts", "error_message", False),
|
||||
("freight_rpa_onhand_task_rpa_attempts", "callback_payload_json", True),
|
||||
("freight_rpa_onhand_task_rpa_attempts", "extra_json", True),
|
||||
)
|
||||
|
||||
_PERMISSION_COLUMNS: tuple[tuple[str, str, bool], ...] = (
|
||||
("users", "feature_permissions", True),
|
||||
("permission_roles", "feature_permissions", True),
|
||||
("app_settings", "value", False),
|
||||
)
|
||||
|
||||
_AUDIT_TRIGGER = "trg_shipping_audit_events_no_update"
|
||||
|
||||
# 排程 data_source_type 的整列等值。不是子串替换,避免把现行 platform_api_path 改回去。
|
||||
_LEGACY_ONHAND_DATA_SOURCE = "shipping_inventory_rpa"
|
||||
_ONHAND_PLATFORM_JOB_KEY = "freight-rpa-onhand"
|
||||
|
||||
|
||||
def _pairs(direction: str) -> tuple[tuple[str, str], ...]:
|
||||
"""返回某一方向的整词对照,按旧词长度降序。"""
|
||||
pairs = _EXACT_PAIRS if direction == "upgrade" else tuple((new, old) for old, new in _EXACT_PAIRS)
|
||||
return tuple(sorted(pairs, key=lambda item: len(item[0]), reverse=True))
|
||||
|
||||
|
||||
def _apply_permission_module(value: str, direction: str) -> str:
|
||||
"""
|
||||
只改权限模块 JSON 键 "shipping_inventory" ↔ "freight_rpa"。
|
||||
|
||||
核心逻辑:升级替换带引号且后接冒号的键,并写入 __s17c_perm_module。
|
||||
降级仅当标记还在时把该键改回并删掉标记。不改 freight_rpa_sources 等更长标识,
|
||||
也不改升级之前就已经是 "freight_rpa" 的行。
|
||||
"""
|
||||
if direction == "upgrade":
|
||||
pattern = re.compile(r'"shipping_inventory"(\s*:)')
|
||||
if pattern.search(value) is None:
|
||||
return value
|
||||
updated = pattern.sub(r'"freight_rpa"\1', value)
|
||||
if f'"{_PERMISSION_MARKER}"' in updated:
|
||||
return updated
|
||||
stripped = updated.rstrip()
|
||||
if not stripped.endswith("}"):
|
||||
return updated
|
||||
body = stripped[:-1].rstrip()
|
||||
comma = "" if body.endswith("{") else ","
|
||||
return f'{body}{comma}"{_PERMISSION_MARKER}":true}}'
|
||||
if f'"{_PERMISSION_MARKER}"' not in value:
|
||||
return value
|
||||
updated = re.sub(r'"freight_rpa"(\s*:)', r'"shipping_inventory"\1', value)
|
||||
updated = re.sub(
|
||||
rf',?\s*"{re.escape(_PERMISSION_MARKER)}"\s*:\s*true',
|
||||
"",
|
||||
updated,
|
||||
)
|
||||
updated = re.sub(r"\{\s*,", "{", updated)
|
||||
updated = re.sub(r",\s*\}", "}", updated)
|
||||
return updated
|
||||
|
||||
|
||||
def _prefix_pattern(direction: str) -> re.Pattern[str]:
|
||||
"""inventory_rpa_* / onhand_rpa_* 前缀。不吃模块名 inventory_rpa_workflow。"""
|
||||
if direction == "upgrade":
|
||||
return re.compile(r"(?<![A-Za-z0-9_/\\])inventory_rpa_(?!workflow\b)")
|
||||
return re.compile(r"(?<![A-Za-z0-9_/\\])onhand_rpa_(?!workflow\b)")
|
||||
|
||||
|
||||
def rewrite_persisted_text(value: str | None, *, direction: str, permission: bool = False) -> str | None:
|
||||
"""
|
||||
按词边界把存量契约字符串换成目标词根。
|
||||
|
||||
核心逻辑:整词优先(长词在前),再替换 inventory_rpa_ / onhand_rpa_ 前缀。
|
||||
路径片段(前有 / 或 \\,或后接 .py)和 ensure_inventory_via_rpa 这类更长标识不改。
|
||||
permission=True 时只改带引号的权限模块 JSON 键,降级依赖 __s17c_perm_module 标记。
|
||||
|
||||
Args:
|
||||
value: 列的原始文本。None 原样返回。
|
||||
direction: upgrade 或 downgrade。
|
||||
permission: 是否对本列应用权限模块键。
|
||||
|
||||
Returns:
|
||||
替换后的文本;无变化时与输入相同。
|
||||
"""
|
||||
if value is None:
|
||||
return None
|
||||
updated = str(value)
|
||||
for old, new in _pairs(direction):
|
||||
updated = re.sub(
|
||||
rf"(?<![A-Za-z0-9_/\\]){re.escape(old)}(?![A-Za-z0-9_]|\.py)",
|
||||
new,
|
||||
updated,
|
||||
)
|
||||
prefix_new = "onhand_rpa_" if direction == "upgrade" else "inventory_rpa_"
|
||||
updated = _prefix_pattern(direction).sub(prefix_new, updated)
|
||||
if permission:
|
||||
updated = _apply_permission_module(updated, direction)
|
||||
return updated
|
||||
|
||||
|
||||
def _quote(name: str) -> str:
|
||||
"""给表名或列名加双引号,避免 key 这类保留字。"""
|
||||
return '"' + name.replace('"', "") + '"'
|
||||
|
||||
|
||||
def _set_audit_update_trigger(connection, enabled: bool) -> None:
|
||||
"""PostgreSQL 上临时开关审计表的禁更新触发器。其它方言无此触发器。"""
|
||||
if connection.dialect.name != "postgresql":
|
||||
return
|
||||
if not connection.execute(
|
||||
sa.text("SELECT 1 FROM pg_trigger WHERE tgname = :name"),
|
||||
{"name": _AUDIT_TRIGGER},
|
||||
).scalar():
|
||||
return
|
||||
verb = "ENABLE" if enabled else "DISABLE"
|
||||
connection.execute(sa.text(
|
||||
f"ALTER TABLE shipping_audit_events {verb} TRIGGER {_AUDIT_TRIGGER}"
|
||||
))
|
||||
|
||||
|
||||
def _rewrite_column(connection, table: str, column: str, is_json: bool, *, permission: bool, direction: str) -> None:
|
||||
"""
|
||||
重写一张表的一列。表或列不存在则跳过。
|
||||
|
||||
核心逻辑:只选出文本里带 inventory、receipt RPA、receipt options_source 或降级新词的行,
|
||||
词边界替换后按主键写回。JSON 列在 PostgreSQL 上 CAST 回 JSON。
|
||||
"""
|
||||
inspector = sa.inspect(connection)
|
||||
if table not in inspector.get_table_names():
|
||||
return
|
||||
column_names = {item["name"] for item in inspector.get_columns(table)}
|
||||
if column not in column_names:
|
||||
return
|
||||
pk_cols = inspector.get_pk_constraint(table).get("constrained_columns") or []
|
||||
if len(pk_cols) != 1:
|
||||
return
|
||||
pk = pk_cols[0]
|
||||
if direction == "upgrade":
|
||||
needles = ("%inventory%", "%shipping_receipt_rpa_%", "%shipping_receipt_sources%")
|
||||
else:
|
||||
needles = ("%onhand%", "%shipping_inbound_rpa_%", "%freight_rpa%")
|
||||
rows = connection.execute(sa.text(
|
||||
f"SELECT {_quote(pk)}, CAST({_quote(column)} AS TEXT) "
|
||||
f"FROM {_quote(table)} "
|
||||
f"WHERE CAST({_quote(column)} AS TEXT) LIKE :needle "
|
||||
f"OR CAST({_quote(column)} AS TEXT) LIKE :receipt "
|
||||
f"OR CAST({_quote(column)} AS TEXT) LIKE :perm"
|
||||
), {"needle": needles[0], "receipt": needles[1], "perm": needles[2]}).fetchall()
|
||||
dialect = connection.dialect.name
|
||||
for row_id, raw in rows:
|
||||
rewritten = rewrite_persisted_text(raw, direction=direction, permission=permission)
|
||||
if rewritten is None or rewritten == raw:
|
||||
continue
|
||||
if dialect == "postgresql" and is_json:
|
||||
statement = (
|
||||
f"UPDATE {_quote(table)} SET {_quote(column)} = CAST(:value AS JSON) "
|
||||
f"WHERE {_quote(pk)} = :row_id"
|
||||
)
|
||||
else:
|
||||
statement = (
|
||||
f"UPDATE {_quote(table)} SET {_quote(column)} = :value "
|
||||
f"WHERE {_quote(pk)} = :row_id"
|
||||
)
|
||||
connection.execute(sa.text(statement), {"value": rewritten, "row_id": row_id})
|
||||
|
||||
|
||||
_AUDIT_HASH_FIELDS = (
|
||||
"id",
|
||||
"event_type",
|
||||
"aggregate_type",
|
||||
"aggregate_id",
|
||||
"action",
|
||||
"result",
|
||||
"reason_code",
|
||||
"workflow_id",
|
||||
"workflow_item_id",
|
||||
"workflow_item_version_id",
|
||||
"version_no",
|
||||
"run_no",
|
||||
"document_id",
|
||||
"review_case_no",
|
||||
"task_no",
|
||||
"operation_id",
|
||||
"request_id",
|
||||
"actor_type",
|
||||
"actor_id",
|
||||
"before_snapshot_json",
|
||||
"after_snapshot_json",
|
||||
"diff_json",
|
||||
"previous_event_hash",
|
||||
"event_hash",
|
||||
"sensitivity_level",
|
||||
)
|
||||
|
||||
|
||||
def _json_object(raw: object) -> dict | None:
|
||||
"""把审计快照列还原成 dict;空值或非对象返回 None。"""
|
||||
if raw is None or raw == "":
|
||||
return None
|
||||
if isinstance(raw, dict):
|
||||
return raw
|
||||
try:
|
||||
parsed = json.loads(str(raw))
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return parsed if isinstance(parsed, dict) else None
|
||||
|
||||
|
||||
def _rehash_shipping_audit_events(connection) -> None:
|
||||
"""
|
||||
用生产同一套 build_event_hash_payload / compute_event_hash 重算审计哈希。
|
||||
|
||||
核心逻辑:按聚合 id 升序走链。本行内容变了就重算 event_hash;
|
||||
前一行哈希变了就把本行 previous_event_hash 接上再重算,避免链断裂。
|
||||
缺 event_hash 列则跳过。
|
||||
"""
|
||||
inspector = sa.inspect(connection)
|
||||
if "shipping_audit_events" not in inspector.get_table_names():
|
||||
return
|
||||
present = {item["name"] for item in inspector.get_columns("shipping_audit_events")}
|
||||
if "id" not in present or "event_hash" not in present or "event_type" not in present:
|
||||
return
|
||||
from app.services.shipping_notice.audit_snapshot_service import (
|
||||
build_event_hash_payload,
|
||||
compute_event_hash,
|
||||
)
|
||||
|
||||
selected = [name for name in _AUDIT_HASH_FIELDS if name in present]
|
||||
rows = connection.execute(sa.text(
|
||||
"SELECT " + ", ".join(_quote(name) for name in selected) + " FROM shipping_audit_events ORDER BY "
|
||||
+ ("aggregate_type, aggregate_id, " if "aggregate_type" in present and "aggregate_id" in present else "")
|
||||
+ "id"
|
||||
)).mappings().all()
|
||||
running_hash: str | None = None
|
||||
current_group: tuple[str, str] | None = None
|
||||
for row in rows:
|
||||
group = (
|
||||
str(row.get("aggregate_type") or ""),
|
||||
str(row.get("aggregate_id") or ""),
|
||||
)
|
||||
if group != current_group:
|
||||
current_group = group
|
||||
running_hash = None
|
||||
previous_for_hash = row.get("previous_event_hash")
|
||||
else:
|
||||
previous_for_hash = running_hash
|
||||
payload = build_event_hash_payload(
|
||||
event_type=str(row.get("event_type") or ""),
|
||||
aggregate_type=str(row.get("aggregate_type") or ""),
|
||||
aggregate_id=str(row.get("aggregate_id") or ""),
|
||||
action=row.get("action"),
|
||||
result=row.get("result"),
|
||||
reason_code=row.get("reason_code"),
|
||||
workflow_id=row.get("workflow_id"),
|
||||
workflow_item_id=row.get("workflow_item_id"),
|
||||
workflow_item_version_id=row.get("workflow_item_version_id"),
|
||||
version_no=row.get("version_no"),
|
||||
run_no=row.get("run_no"),
|
||||
document_id=row.get("document_id"),
|
||||
review_case_no=row.get("review_case_no"),
|
||||
task_no=row.get("task_no"),
|
||||
operation_id=row.get("operation_id"),
|
||||
request_id=row.get("request_id"),
|
||||
actor_type=str(row.get("actor_type") or "system"),
|
||||
actor_id=row.get("actor_id"),
|
||||
before_snapshot=_json_object(row.get("before_snapshot_json")),
|
||||
after_snapshot=_json_object(row.get("after_snapshot_json")),
|
||||
diff_json=_json_object(row.get("diff_json")),
|
||||
previous_event_hash=previous_for_hash,
|
||||
sensitivity_level=row.get("sensitivity_level"),
|
||||
)
|
||||
new_hash = compute_event_hash(payload)
|
||||
if new_hash != row.get("event_hash") or previous_for_hash != row.get("previous_event_hash"):
|
||||
if "previous_event_hash" in present:
|
||||
connection.execute(sa.text(
|
||||
"UPDATE shipping_audit_events SET event_hash = :event_hash, "
|
||||
"previous_event_hash = :previous_event_hash WHERE id = :row_id"
|
||||
), {
|
||||
"event_hash": new_hash,
|
||||
"previous_event_hash": previous_for_hash,
|
||||
"row_id": row["id"],
|
||||
})
|
||||
else:
|
||||
connection.execute(sa.text(
|
||||
"UPDATE shipping_audit_events SET event_hash = :event_hash WHERE id = :row_id"
|
||||
), {"event_hash": new_hash, "row_id": row["id"]})
|
||||
running_hash = new_hash
|
||||
|
||||
|
||||
def _rewrite_legacy_onhand_data_source(connection, direction: str) -> None:
|
||||
"""
|
||||
把 schedule_tasks.data_source_type 的历史整值改成现行 platform job key。
|
||||
|
||||
核心逻辑:只匹配整列相等,不扫描其它列里的 freight-rpa-onhand。
|
||||
升级同时把 schedule_type / platform_api_path 拨到 platform_job。
|
||||
降级只把 data_source_type 从现行 job key 改回历史整值。
|
||||
|
||||
Args:
|
||||
connection: Alembic 绑定的连接。
|
||||
direction: upgrade 或 downgrade。
|
||||
"""
|
||||
inspector = sa.inspect(connection)
|
||||
if "schedule_tasks" not in inspector.get_table_names():
|
||||
return
|
||||
columns = {item["name"] for item in inspector.get_columns("schedule_tasks")}
|
||||
if "data_source_type" not in columns:
|
||||
return
|
||||
if direction == "upgrade":
|
||||
assignments = [f"{_quote('data_source_type')} = :new_source"]
|
||||
params: dict[str, str] = {
|
||||
"old_source": _LEGACY_ONHAND_DATA_SOURCE,
|
||||
"new_source": _ONHAND_PLATFORM_JOB_KEY,
|
||||
}
|
||||
if "schedule_type" in columns:
|
||||
assignments.append(f"{_quote('schedule_type')} = 'platform_job'")
|
||||
if "platform_api_path" in columns:
|
||||
assignments.append(f"{_quote('platform_api_path')} = :new_source")
|
||||
connection.execute(sa.text(
|
||||
f"UPDATE {_quote('schedule_tasks')} SET {', '.join(assignments)} "
|
||||
f"WHERE {_quote('data_source_type')} = :old_source"
|
||||
), params)
|
||||
return
|
||||
connection.execute(sa.text(
|
||||
f"UPDATE {_quote('schedule_tasks')} SET {_quote('data_source_type')} = :old_source "
|
||||
f"WHERE {_quote('data_source_type')} = :new_source"
|
||||
), {
|
||||
"old_source": _LEGACY_ONHAND_DATA_SOURCE,
|
||||
"new_source": _ONHAND_PLATFORM_JOB_KEY,
|
||||
})
|
||||
|
||||
|
||||
def _rewrite_all(connection, direction: str) -> None:
|
||||
"""按列清单重写契约字符串。审计表在 PostgreSQL 上先关禁更新触发器。"""
|
||||
_set_audit_update_trigger(connection, enabled=False)
|
||||
try:
|
||||
_rewrite_legacy_onhand_data_source(connection, direction)
|
||||
for table, column, is_json in _COLUMNS:
|
||||
_rewrite_column(
|
||||
connection, table, column, is_json, permission=False, direction=direction,
|
||||
)
|
||||
for table, column, is_json in _PERMISSION_COLUMNS:
|
||||
_rewrite_column(
|
||||
connection, table, column, is_json, permission=True, direction=direction,
|
||||
)
|
||||
_rehash_shipping_audit_events(connection)
|
||||
finally:
|
||||
_set_audit_update_trigger(connection, enabled=True)
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""把存量枚举、事件名、job_type、options_source 和权限模块键改成新词。"""
|
||||
_rewrite_all(op.get_bind(), "upgrade")
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""按同一对照表把新词改回旧词。"""
|
||||
_rewrite_all(op.get_bind(), "downgrade")
|
||||
@@ -0,0 +1,563 @@
|
||||
"""
|
||||
migrations/versions/s18d1e2f3a4b5_freight_rpa_phase_b_report_ownership.py
|
||||
|
||||
用途:货代 RPA 阶段 B 第一段——新建在手报表配置表 freight_rpa_onhand_report_configs,
|
||||
把站点表 freight_rpa_sources 上的 report_path_json / query_parameters_json /
|
||||
parsing_profile_id 三列搬进该表,把启用检查约束换成只看 excel_template_id 的
|
||||
模板版本(CHECK 不能跨表),再把 shipping_onhand_files 改名为
|
||||
freight_rpa_onhand_report_files,并按 s17b 的手法重写名字含旧表名的
|
||||
索引 / 约束对象名(列名一概不改)。
|
||||
依赖:alembic.op、SQLAlchemy 反射;down_revision 为批次 S 第二段 s17c2d3e4f5a6。
|
||||
解析方案表已在 s17b 落到 freight_rpa_parsing_profiles,本迁移不再出现
|
||||
解析方案表的第二条改名,禁止出现 freight_rpa_onhand_parsing_profiles。
|
||||
逻辑:先建配置表(外键到 freight_rpa_sources / freight_rpa_parsing_profiles / users,
|
||||
source_id 唯一),再把三列数据 INSERT 过去;然后用 batch_alter_table
|
||||
(PostgreSQL 直发 ALTER,SQLite 走重建)删旧启用约束、删三列、建模板约束;
|
||||
rename_table 之后扫全库对象名,把 shipping_onhand_files token 替换为
|
||||
freight_rpa_onhand_report_files,超过 PostgreSQL 63 字节的沿用 s17b 的截断。
|
||||
downgrade 按相反顺序还原:文件表改回旧名并回滚对象名,三列加回站点行,
|
||||
从配置表 UPDATE 回数据(无配置行的站点两列 JSON 用 COALESCE 回填 '{}' / '[]',
|
||||
避免 NULL 写入 NOT NULL 列),删掉配置表,最后恢复
|
||||
ck_freight_rpa_sources_enabled_bindings 原文(双绑定表达式)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision = "s18d1e2f3a4b5"
|
||||
down_revision = "s17c2d3e4f5a6"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
# PostgreSQL 标识符上限(NAMEDATALEN-1),与 s17b 一致。
|
||||
_MAX_IDENTIFIER_LENGTH = 63
|
||||
|
||||
_SOURCES_TABLE = "freight_rpa_sources"
|
||||
_CONFIG_TABLE = "freight_rpa_onhand_report_configs"
|
||||
_FILES_TABLE_OLD = "shipping_onhand_files"
|
||||
_FILES_TABLE_NEW = "freight_rpa_onhand_report_files"
|
||||
|
||||
# c27e 创建、s17b 改到新表名词根的启用约束,及其双绑定原文与模板版替代。
|
||||
_ENABLED_BINDINGS_CHECK = "ck_freight_rpa_sources_enabled_bindings"
|
||||
_ENABLED_TEMPLATE_CHECK = "ck_freight_rpa_sources_enabled_template"
|
||||
_ENABLED_BINDINGS_SQL = (
|
||||
"enabled = false OR (parsing_profile_id IS NOT NULL AND excel_template_id IS NOT NULL)"
|
||||
)
|
||||
_ENABLED_TEMPLATE_SQL = "enabled = false OR excel_template_id IS NOT NULL"
|
||||
# b17 建出的站点→解析方案外键名(不含旧表名词根,s17b 未改名),降级按原名还原。
|
||||
_SOURCES_PARSING_FK = "fk_inventory_sources_parsing_profile"
|
||||
# 站点→解析方案列的自动索引名(模型 index=True;s17b 换到新表名词根),降级补回。
|
||||
_SOURCES_PARSING_INDEX = "ix_freight_rpa_sources_parsing_profile_id"
|
||||
# 本期搬离站点行的三列。
|
||||
_MOVED_COLUMNS = ("report_path_json", "query_parameters_json", "parsing_profile_id")
|
||||
|
||||
|
||||
def _quote_ident(name: str) -> str:
|
||||
"""给 SQL 标识符加双引号,内部引号按标准加倍。
|
||||
|
||||
Args:
|
||||
name: 表、索引或约束名。
|
||||
|
||||
Returns:
|
||||
可拼进 DDL 的引用标识符。
|
||||
"""
|
||||
return '"' + name.replace('"', '""') + '"'
|
||||
|
||||
|
||||
def _substitute(name: str, pairs: list[tuple[str, str]]) -> str:
|
||||
"""把对象名中的表名 token 换成对照表里的另一个名字。
|
||||
|
||||
核心逻辑:按源 token 长度降序替换,避免短表名吃掉更长表名的前缀。
|
||||
本迁移只有一对 token(文件表新旧名),直接替换。
|
||||
|
||||
Args:
|
||||
name: 当前索引或约束名。
|
||||
pairs: (被替换的表名, 替换后的表名)。升级用旧→新,降级用新→旧。
|
||||
|
||||
Returns:
|
||||
替换后的对象名(尚未按 63 字节截断)。
|
||||
"""
|
||||
updated = name
|
||||
for source, destination in sorted(pairs, key=lambda item: len(item[0]), reverse=True):
|
||||
updated = updated.replace(source, destination)
|
||||
return updated
|
||||
|
||||
|
||||
def _clip(name: str) -> str:
|
||||
"""把标识符限制在 PostgreSQL 的 63 字节以内(沿用 s17b 的截断函数)。
|
||||
|
||||
Args:
|
||||
name: 已完成表名替换的对象名。
|
||||
|
||||
Returns:
|
||||
长度不超过 63 的名字。未超长时原样返回。
|
||||
"""
|
||||
if len(name) <= _MAX_IDENTIFIER_LENGTH:
|
||||
return name
|
||||
return name[:_MAX_IDENTIFIER_LENGTH]
|
||||
|
||||
|
||||
def _iter_constraints(inspector, table: str):
|
||||
"""列出一张表上带名字的外键、唯一、检查和主键约束。
|
||||
|
||||
Args:
|
||||
inspector: 当前连接的 SQLAlchemy Inspector。
|
||||
table: 表名。
|
||||
|
||||
Yields:
|
||||
(kind, name, payload)。kind 使用 alembic batch 的 type_ 取值。
|
||||
外键 payload 是反射字典,唯一/主键 payload 是列名列表,检查 payload 是表达式。
|
||||
"""
|
||||
for foreign_key in inspector.get_foreign_keys(table) or []:
|
||||
yield "foreignkey", foreign_key.get("name"), foreign_key
|
||||
for unique in inspector.get_unique_constraints(table) or []:
|
||||
yield "unique", unique.get("name"), list(unique.get("column_names") or [])
|
||||
for check in inspector.get_check_constraints(table) or []:
|
||||
yield "check", check.get("name"), check.get("sqltext")
|
||||
primary = inspector.get_pk_constraint(table) or {}
|
||||
yield "primary", primary.get("name"), list(primary.get("constrained_columns") or [])
|
||||
|
||||
|
||||
def _target_name(current: str, pairs: list[tuple[str, str]]) -> str:
|
||||
"""计算对象改名的目标:表名替换再截断。
|
||||
|
||||
Args:
|
||||
current: 库里现在的对象名。
|
||||
pairs: 本方向的表名替换对。
|
||||
|
||||
Returns:
|
||||
应改成的对象名。与 current 相同表示不用改。
|
||||
"""
|
||||
return _clip(_substitute(current, pairs))
|
||||
|
||||
|
||||
def _existing_object_names(inspector) -> set[str]:
|
||||
"""收集当前库里全部索引名和约束名,供目标名冲突检查。
|
||||
|
||||
Args:
|
||||
inspector: 当前连接的 Inspector。
|
||||
|
||||
Returns:
|
||||
已占用的对象名集合。
|
||||
"""
|
||||
found: set[str] = set()
|
||||
for table in inspector.get_table_names():
|
||||
if table.startswith("sqlite_"):
|
||||
continue
|
||||
for index in inspector.get_indexes(table) or []:
|
||||
if index.get("name"):
|
||||
found.add(index["name"])
|
||||
for _kind, name, _payload in _iter_constraints(inspector, table):
|
||||
if name:
|
||||
found.add(name)
|
||||
return found
|
||||
|
||||
|
||||
def _reject_collisions(planned: dict, existing: set[str]) -> None:
|
||||
"""目标对象名不能互相重复,也不能盖住一个本次不改名的既有对象。
|
||||
|
||||
Args:
|
||||
planned: {表名: (索引列表, 约束列表)} 形态的改名计划。
|
||||
existing: 当前已占用的对象名。
|
||||
|
||||
Raises:
|
||||
RuntimeError: 两个对象要改成同一个名字,或目标名已被占用。
|
||||
"""
|
||||
sources: list[str] = []
|
||||
targets: list[str] = []
|
||||
for index_rows, constraint_rows in planned.values():
|
||||
for old_name, new_name in index_rows:
|
||||
sources.append(old_name)
|
||||
targets.append(new_name)
|
||||
for _kind, old_name, new_name, _payload in constraint_rows:
|
||||
sources.append(old_name)
|
||||
targets.append(new_name)
|
||||
if len(targets) != len(set(targets)):
|
||||
raise RuntimeError(f"object rename target collision: {targets}")
|
||||
source_set = set(sources)
|
||||
occupied = sorted(target for target in targets if target in existing and target not in source_set)
|
||||
if occupied:
|
||||
raise RuntimeError(f"object rename would overwrite existing names: {occupied}")
|
||||
|
||||
|
||||
def _collect_renames(bind, pairs: list[tuple[str, str]]) -> dict:
|
||||
"""扫描全库,收集名称中含表名 token、因而需要改名的索引和约束。
|
||||
|
||||
核心逻辑(沿用 s17b):PostgreSQL 上唯一/主键约束与其支撑索引同名,
|
||||
只走约束(RENAME CONSTRAINT 会带走索引);SQLite 上独立索引用重建,
|
||||
表内约束才进 batch,同名时以索引为准,避免拆掉已改过的索引。
|
||||
|
||||
Args:
|
||||
bind: 当前迁移连接。
|
||||
pairs: 本方向的表名替换对。
|
||||
|
||||
Returns:
|
||||
{表名: (索引列表[(旧, 新)], 约束列表[(kind, 旧, 新, payload)])}。
|
||||
"""
|
||||
inspector = sa.inspect(bind)
|
||||
dialect = bind.dialect.name
|
||||
planned: dict[str, tuple[list, list]] = {}
|
||||
for table in inspector.get_table_names():
|
||||
if table.startswith("sqlite_"):
|
||||
continue
|
||||
raw_indexes: list[str] = []
|
||||
for index in inspector.get_indexes(table) or []:
|
||||
name = index.get("name")
|
||||
if name and not str(name).startswith("sqlite_"):
|
||||
raw_indexes.append(name)
|
||||
raw_constraints = []
|
||||
for kind, name, payload in _iter_constraints(inspector, table):
|
||||
if name and not str(name).startswith("sqlite_"):
|
||||
raw_constraints.append((kind, name, payload))
|
||||
|
||||
index_rows: list[tuple[str, str]] = []
|
||||
constraint_rows: list[tuple[str, str, str, object]] = []
|
||||
if dialect == "postgresql":
|
||||
constraint_names = {name for _kind, name, _payload in raw_constraints}
|
||||
for kind, name, payload in raw_constraints:
|
||||
target = _target_name(name, pairs)
|
||||
if target != name:
|
||||
constraint_rows.append((kind, name, target, payload))
|
||||
for name in raw_indexes:
|
||||
if name in constraint_names:
|
||||
continue
|
||||
target = _target_name(name, pairs)
|
||||
if target != name:
|
||||
index_rows.append((name, target))
|
||||
else:
|
||||
index_names = set(raw_indexes)
|
||||
for name in raw_indexes:
|
||||
target = _target_name(name, pairs)
|
||||
if target != name:
|
||||
index_rows.append((name, target))
|
||||
for kind, name, payload in raw_constraints:
|
||||
if name in index_names:
|
||||
continue
|
||||
target = _target_name(name, pairs)
|
||||
if target != name:
|
||||
constraint_rows.append((kind, name, target, payload))
|
||||
if index_rows or constraint_rows:
|
||||
planned[table] = (index_rows, constraint_rows)
|
||||
_reject_collisions(planned, _existing_object_names(inspector))
|
||||
return planned
|
||||
|
||||
|
||||
def _rename_index(bind, old_name: str, new_name: str) -> None:
|
||||
"""改索引名。PostgreSQL 用 ALTER INDEX;SQLite 按 sqlite_master 重建。
|
||||
|
||||
Args:
|
||||
bind: 当前迁移连接。
|
||||
old_name: 现名。
|
||||
new_name: 新名。
|
||||
|
||||
Raises:
|
||||
RuntimeError: SQLite 找不到可重建的 CREATE INDEX 语句。
|
||||
"""
|
||||
if bind.dialect.name == "postgresql":
|
||||
op.execute(sa.text(
|
||||
f"ALTER INDEX {_quote_ident(old_name)} RENAME TO {_quote_ident(new_name)}"
|
||||
))
|
||||
return
|
||||
row = bind.execute(
|
||||
sa.text("SELECT sql FROM sqlite_master WHERE type = 'index' AND name = :name"),
|
||||
{"name": old_name},
|
||||
).fetchone()
|
||||
if row is None or not row[0]:
|
||||
raise RuntimeError(f"sqlite index {old_name} has no SQL to rebuild")
|
||||
sql = row[0]
|
||||
quoted = f'"{old_name}"'
|
||||
if quoted in sql:
|
||||
rebuilt = sql.replace(quoted, _quote_ident(new_name), 1)
|
||||
elif old_name in sql:
|
||||
rebuilt = sql.replace(old_name, new_name, 1)
|
||||
else:
|
||||
raise RuntimeError(f"index SQL does not contain {old_name}: {sql}")
|
||||
op.execute(sa.text(f"DROP INDEX {_quote_ident(old_name)}"))
|
||||
op.execute(sa.text(rebuilt))
|
||||
|
||||
|
||||
def _rename_constraints(bind, table: str, constraints: list) -> None:
|
||||
"""改一张表上的约束名。
|
||||
|
||||
核心逻辑(沿用 s17b):PostgreSQL 只 RENAME CONSTRAINT,不重建表;
|
||||
SQLite 没有 RENAME CONSTRAINT,用一次 batch 先删后建,
|
||||
保留列、外键目标与删除动作。
|
||||
|
||||
Args:
|
||||
bind: 当前迁移连接。
|
||||
table: 约束所在表(已经是本阶段的表名)。
|
||||
constraints: (kind, 旧名, 新名, payload) 列表。
|
||||
"""
|
||||
if not constraints:
|
||||
return
|
||||
if bind.dialect.name == "postgresql":
|
||||
for _kind, old_name, new_name, _payload in constraints:
|
||||
op.execute(sa.text(
|
||||
f"ALTER TABLE {_quote_ident(table)} "
|
||||
f"RENAME CONSTRAINT {_quote_ident(old_name)} TO {_quote_ident(new_name)}"
|
||||
))
|
||||
return
|
||||
with op.batch_alter_table(table) as batch:
|
||||
for kind, old_name, _new_name, _payload in constraints:
|
||||
batch.drop_constraint(old_name, type_=kind)
|
||||
for kind, _old_name, new_name, payload in constraints:
|
||||
if kind == "foreignkey":
|
||||
options = payload.get("options") or {}
|
||||
batch.create_foreign_key(
|
||||
new_name,
|
||||
payload["referred_table"],
|
||||
payload["constrained_columns"],
|
||||
payload["referred_columns"],
|
||||
ondelete=options.get("ondelete"),
|
||||
onupdate=options.get("onupdate"),
|
||||
deferrable=options.get("deferrable"),
|
||||
initially=options.get("initially"),
|
||||
match=options.get("match"),
|
||||
referent_schema=payload.get("referred_schema"),
|
||||
)
|
||||
elif kind == "unique":
|
||||
batch.create_unique_constraint(new_name, payload)
|
||||
elif kind == "check":
|
||||
batch.create_check_constraint(new_name, payload)
|
||||
elif kind == "primary":
|
||||
batch.create_primary_key(new_name, payload)
|
||||
else:
|
||||
raise RuntimeError(f"unsupported constraint kind {kind}")
|
||||
|
||||
|
||||
def _rewrite_object_names(pairs: list[tuple[str, str]]) -> None:
|
||||
"""改写全库里名称包含旧/新文件表名的索引和约束。
|
||||
|
||||
核心逻辑(沿用 s17b):SQLite 先改索引再 batch 约束,这样 batch
|
||||
反射到的是新索引名;PostgreSQL 先改约束(连带支撑索引),
|
||||
再改剩余普通索引。
|
||||
|
||||
Args:
|
||||
pairs: 本方向的表名替换对。
|
||||
"""
|
||||
bind = op.get_bind()
|
||||
planned = _collect_renames(bind, pairs)
|
||||
if bind.dialect.name == "postgresql":
|
||||
for table, (_indexes, constraints) in planned.items():
|
||||
_rename_constraints(bind, table, constraints)
|
||||
for _table, (indexes, _constraints) in planned.items():
|
||||
for old_name, new_name in indexes:
|
||||
_rename_index(bind, old_name, new_name)
|
||||
return
|
||||
for _table, (indexes, _constraints) in planned.items():
|
||||
for old_name, new_name in indexes:
|
||||
_rename_index(bind, old_name, new_name)
|
||||
refreshed = _collect_renames(op.get_bind(), pairs)
|
||||
for table, (_indexes, constraints) in refreshed.items():
|
||||
_rename_constraints(op.get_bind(), table, constraints)
|
||||
|
||||
|
||||
def _enabled_bindings_constraint_name(bind) -> str | None:
|
||||
"""找到站点表上现存的旧启用检查约束名。
|
||||
|
||||
核心逻辑:优先按 s17b 之后的既定名 ck_freight_rpa_sources_enabled_bindings
|
||||
命中;若历史库上的名字仍是改名前的其它拼写,则按「定义里同时含
|
||||
parsing_profile_id 与 excel_template_id」反射定位那一条再删。
|
||||
|
||||
Args:
|
||||
bind: 当前迁移连接。
|
||||
|
||||
Returns:
|
||||
约束名;站点上没有该约束时返回 None。
|
||||
"""
|
||||
checks = sa.inspect(bind).get_check_constraints(_SOURCES_TABLE) or []
|
||||
for item in checks:
|
||||
if item.get("name") == _ENABLED_BINDINGS_CHECK:
|
||||
return item["name"]
|
||||
for item in checks:
|
||||
sqltext = str(item.get("sqltext") or "")
|
||||
if "parsing_profile_id" in sqltext and "excel_template_id" in sqltext:
|
||||
return item.get("name")
|
||||
return None
|
||||
|
||||
|
||||
def _create_config_table() -> None:
|
||||
"""新建在手报表配置表,形状与 ShippingOnhandReportConfig 模型一致。
|
||||
|
||||
核心逻辑:source_id 唯一且指向站点(级联删除);parsing_profile_id
|
||||
可空,指向 s17b 落定的 freight_rpa_parsing_profiles;created_by /
|
||||
updated_by 指向 users。JSON 两列与 config_version 同入站配置表风格。
|
||||
"""
|
||||
op.create_table(
|
||||
_CONFIG_TABLE,
|
||||
sa.Column("id", sa.Integer(), primary_key=True),
|
||||
sa.Column("source_id", sa.Integer(), nullable=False),
|
||||
sa.Column("parsing_profile_id", sa.Integer(), nullable=True),
|
||||
sa.Column("report_path_json", sa.JSON(), nullable=False, server_default=sa.text("'{}'")),
|
||||
sa.Column("query_parameters_json", sa.JSON(), nullable=False, server_default=sa.text("'[]'")),
|
||||
sa.Column("config_version", sa.Integer(), nullable=False, server_default=sa.text("1")),
|
||||
sa.Column("created_by", sa.Integer(), nullable=True),
|
||||
sa.Column("updated_by", sa.Integer(), nullable=True),
|
||||
sa.Column("created_at", sa.DateTime(), nullable=False),
|
||||
sa.Column("updated_at", sa.DateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(
|
||||
["source_id"], ["freight_rpa_sources.id"],
|
||||
name="fk_freight_rpa_onhand_report_configs_source", ondelete="CASCADE",
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["parsing_profile_id"], ["freight_rpa_parsing_profiles.id"],
|
||||
name="fk_freight_rpa_onhand_report_configs_parsing_profile",
|
||||
),
|
||||
sa.ForeignKeyConstraint(["created_by"], ["users.id"]),
|
||||
sa.ForeignKeyConstraint(["updated_by"], ["users.id"]),
|
||||
sa.UniqueConstraint("source_id", name="uq_freight_rpa_onhand_report_configs_source"),
|
||||
)
|
||||
op.create_index(
|
||||
"ix_freight_rpa_onhand_report_configs_source_id", _CONFIG_TABLE, ["source_id"],
|
||||
)
|
||||
op.create_index(
|
||||
"ix_freight_rpa_onhand_report_configs_parsing_profile_id",
|
||||
_CONFIG_TABLE,
|
||||
["parsing_profile_id"],
|
||||
)
|
||||
|
||||
|
||||
def _moved_column_dependents(bind) -> tuple[list[str], list[str]]:
|
||||
"""列出站点表上直接依赖三列中任一列的索引与外键名。
|
||||
|
||||
核心逻辑:SQLite batch 重建不会自动放弃被删列上的索引(alembic 会按原样重建),
|
||||
PostgreSQL 虽随列自动删除,但先显式 DROP 也不冲突;故两侧统一先删。
|
||||
只有约束列与被删列相交的对象算依赖,excel_template 等其余外键不动。
|
||||
|
||||
Args:
|
||||
bind: 当前迁移连接。
|
||||
|
||||
Returns:
|
||||
(索引名列表, 外键名列表)。无名的内部对象反射不出名字,本就不在重建范围。
|
||||
"""
|
||||
inspector = sa.inspect(bind)
|
||||
dropped = set(_MOVED_COLUMNS)
|
||||
index_names = [
|
||||
str(item["name"])
|
||||
for item in inspector.get_indexes(_SOURCES_TABLE) or []
|
||||
if item.get("name")
|
||||
and set(item.get("column_names") or []) & dropped
|
||||
]
|
||||
foreign_key_names = [
|
||||
str(item["name"])
|
||||
for item in inspector.get_foreign_keys(_SOURCES_TABLE) or []
|
||||
if item.get("name")
|
||||
and set(item.get("constrained_columns") or []) & dropped
|
||||
]
|
||||
return index_names, foreign_key_names
|
||||
|
||||
|
||||
def _move_columns_off_source() -> None:
|
||||
"""删站点上三列,替换启用约束为模板版。
|
||||
|
||||
核心逻辑:数据已 INSERT 到配置表后才执行。batch_alter_table 在
|
||||
PostgreSQL 直发 ALTER,在 SQLite 走重建;解析方案外键与其索引随
|
||||
parsing_profile_id 列一并消失。
|
||||
"""
|
||||
bind = op.get_bind()
|
||||
old_check = _enabled_bindings_constraint_name(bind)
|
||||
moved_indexes, moved_keys = _moved_column_dependents(bind)
|
||||
checks = {
|
||||
item.get("name")
|
||||
for item in sa.inspect(bind).get_check_constraints(_SOURCES_TABLE) or []
|
||||
}
|
||||
with op.batch_alter_table(_SOURCES_TABLE) as batch:
|
||||
# 被删列上的索引/外键先显式退场,SQLite 重建才不会引用已不存在的列。
|
||||
for index_name in moved_indexes:
|
||||
batch.drop_index(index_name)
|
||||
for foreign_key_name in moved_keys:
|
||||
batch.drop_constraint(foreign_key_name, type_="foreignkey")
|
||||
if old_check:
|
||||
batch.drop_constraint(old_check, type_="check")
|
||||
batch.drop_column("report_path_json")
|
||||
batch.drop_column("query_parameters_json")
|
||||
batch.drop_column("parsing_profile_id")
|
||||
if _ENABLED_TEMPLATE_CHECK not in checks:
|
||||
batch.create_check_constraint(_ENABLED_TEMPLATE_CHECK, _ENABLED_TEMPLATE_SQL)
|
||||
|
||||
|
||||
def _restore_columns_on_source() -> None:
|
||||
"""把三列按原可空性与默认值加回站点行,并去掉模板版启用约束。
|
||||
|
||||
核心逻辑:downgrade 专用。parsing_profile_id 外键按 b17 的原名
|
||||
fk_inventory_sources_parsing_profile 还原(s17b 未改过该名)。
|
||||
"""
|
||||
bind = op.get_bind()
|
||||
checks = {
|
||||
item.get("name")
|
||||
for item in sa.inspect(bind).get_check_constraints(_SOURCES_TABLE) or []
|
||||
}
|
||||
with op.batch_alter_table(_SOURCES_TABLE) as batch:
|
||||
if _ENABLED_TEMPLATE_CHECK in checks:
|
||||
batch.drop_constraint(_ENABLED_TEMPLATE_CHECK, type_="check")
|
||||
batch.add_column(sa.Column(
|
||||
"report_path_json", sa.JSON(), nullable=False, server_default=sa.text("'{}'"),
|
||||
))
|
||||
batch.add_column(sa.Column(
|
||||
"query_parameters_json", sa.JSON(), nullable=False, server_default=sa.text("'[]'"),
|
||||
))
|
||||
batch.add_column(sa.Column("parsing_profile_id", sa.Integer(), nullable=True))
|
||||
batch.create_foreign_key(
|
||||
_SOURCES_PARSING_FK, "freight_rpa_parsing_profiles",
|
||||
["parsing_profile_id"], ["id"],
|
||||
)
|
||||
batch.create_index(_SOURCES_PARSING_INDEX, ["parsing_profile_id"])
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""建在手报表配置表、搬三列、换启用约束、改文件表名并重写对象名。
|
||||
|
||||
核心逻辑:顺序不可颠倒——配置表必须先于数据搬移存在;三列必须先搬
|
||||
数据再删;文件表改名后 object 名扫描才能扫到旧 token 的索引/约束。
|
||||
"""
|
||||
# [STEP 1] 配置表就位并把站点三列数据搬到新表(created_by/updated_by 留空)。
|
||||
_create_config_table()
|
||||
op.execute(sa.text(
|
||||
"INSERT INTO freight_rpa_onhand_report_configs "
|
||||
"(source_id, report_path_json, query_parameters_json, parsing_profile_id, "
|
||||
"config_version, created_at, updated_at) "
|
||||
"SELECT id, report_path_json, query_parameters_json, parsing_profile_id, "
|
||||
"config_version, created_at, updated_at FROM freight_rpa_sources"
|
||||
))
|
||||
# [STEP 2] 站点行删三列,启用约束换成只看 excel_template_id 的模板版。
|
||||
_move_columns_off_source()
|
||||
# [STEP 3] 在手文件表归 RPA:改表名并重写名字含旧表名的索引/约束对象名。
|
||||
op.rename_table(_FILES_TABLE_OLD, _FILES_TABLE_NEW)
|
||||
_rewrite_object_names([(_FILES_TABLE_OLD, _FILES_TABLE_NEW)])
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""按升级相反顺序还原:文件表名、三列、数据、配置表与旧启用约束。
|
||||
|
||||
核心逻辑:先改回文件表并回滚对象名;再在站点上恢复三列与外键,
|
||||
从配置表 UPDATE 回数据后删表;最后重建 ck_freight_rpa_sources_enabled_bindings
|
||||
原文(parsing_profile + excel_template 双绑定)。
|
||||
"""
|
||||
# [STEP 1] 在手文件表名与对象名回滚。
|
||||
op.rename_table(_FILES_TABLE_NEW, _FILES_TABLE_OLD)
|
||||
_rewrite_object_names([(_FILES_TABLE_NEW, _FILES_TABLE_OLD)])
|
||||
# [STEP 2] 站点行加回三列与解析方案外键,模板版启用约束退场。
|
||||
_restore_columns_on_source()
|
||||
# [STEP 3] 把配置行数据 UPDATE 回站点行。站点没有配置行时子查询返回 NULL,
|
||||
# 两列 JSON 在站点行上是 NOT NULL,必须 COALESCE 回 server_default 形态;
|
||||
# parsing_profile_id 可空,允许保持 NULL。
|
||||
op.execute(sa.text(
|
||||
"UPDATE freight_rpa_sources SET "
|
||||
"report_path_json = COALESCE(("
|
||||
"SELECT c.report_path_json FROM freight_rpa_onhand_report_configs c "
|
||||
"WHERE c.source_id = freight_rpa_sources.id), '{}'), "
|
||||
"query_parameters_json = COALESCE(("
|
||||
"SELECT c.query_parameters_json FROM freight_rpa_onhand_report_configs c "
|
||||
"WHERE c.source_id = freight_rpa_sources.id), '[]'), "
|
||||
"parsing_profile_id = ("
|
||||
"SELECT c.parsing_profile_id FROM freight_rpa_onhand_report_configs c "
|
||||
"WHERE c.source_id = freight_rpa_sources.id)"
|
||||
))
|
||||
# [STEP 4] 配置表退役。
|
||||
op.drop_table(_CONFIG_TABLE)
|
||||
# [STEP 5] 恢复双绑定的原启用约束。
|
||||
with op.batch_alter_table(_SOURCES_TABLE) as batch:
|
||||
batch.create_check_constraint(_ENABLED_BINDINGS_CHECK, _ENABLED_BINDINGS_SQL)
|
||||
@@ -8,7 +8,7 @@ Create Date: 2026-10-16
|
||||
shipping-inventory-rpa→freight-rpa-onhand(在手/库存)、
|
||||
freight-receipt-rpa→freight-rpa-inbound(入站/收料)、
|
||||
freight-receipt-rpa-retention→freight-rpa-inbound-retention(入站归档保留期清理),
|
||||
与 job_registry.py / freight_onhand_rpa_*、freight_inbound_rpa_* 排程壳改名同窗口发布。
|
||||
与 job_registry.py / freight_rpa_onhand_*、freight_rpa_inbound_* 排程壳改名同窗口发布。
|
||||
依赖:实施时 flask db heads 的单 head 为 tt16a7b8c9d0e1f2(调拨域迁移,其上游即
|
||||
tt15b6a7b8c9d0);本迁移若直挂 tt15 会产生双 head,故按单 head 纪律链在其上。
|
||||
逻辑:列为 platform_api_path(String(500),承载归一化 job key——自 b9c0d1e2f3a4 起
|
||||
|
||||
Reference in new issue
Block a user