Merge branch 'dev' into common-problems-fuzzy-query

This commit is contained in:
HTEWJ\26070045 committed 2026-10-23 09:41:26 +08:00
commit d3204f1db8
790 files changed
+71443 -26080

No files matched your search

@@ -0,0 +1,30 @@
"""合并设备验收发送归档与调拨类型列宽两条 Alembic 头。
Revision ID: mh15f6a7b8c9
Revises: eah8c9d0e1f2, tt13d4e5f6a7b8
Create Date: 2026-10-15 13:20:00.000000
用途:将 ``eah8c9d0e1f2``(设备验收企微事件、第 4 轮开关与 Excel 归档)与
``tt13d4e5f6a7b8``(transfer_runs.transfer_type 放宽至 String(64))
收成单一升级路径,避免 ``flask db upgrade`` / pre-push 因多 head 失败。
依赖:``eah8c9d0e1f2``、``tt13d4e5f6a7b8``。
逻辑:不修改业务表,只声明两条已完成迁移线在此收敛。
"""
from alembic import op # noqa: F401 - Alembic migration module contract
revision = "mh15f6a7b8c9"
down_revision = ("eah8c9d0e1f2", "tt13d4e5f6a7b8")
branch_labels = None
depends_on = None
def upgrade() -> None:
"""合并设备验收 head 与调拨类型列宽 head,不执行数据库结构变更。"""
pass
def downgrade() -> None:
"""撤销合并节点;不会回滚两个父分支的业务变更。"""
pass
@@ -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)
@@ -0,0 +1,275 @@
"""
migrations/versions/s19a0b1c2d3e4_freight_rpa_outbound_and_inbound_slim.py
用途:新建出站 RPA 三表,并拆除入站 per-file 企微投递表
freight_rpa_inbound_notification_deliveries(Task 2 已删 Python 模型)。
依赖:alembic.op、SQLAlchemy;down_revision 为实施时单 head s18d1e2f3a4b5。
逻辑:autogenerate 噪声过大(无关 drop / 历史索引改名),故手写本 revision。
升级先 drop 投递表及其历史索引,再按 ORM 同构建
configs → unit_runs → files;降级先拆出站三表,再按 s17b 后的现行结构
还原投递表(不恢复投递数据)。
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision = "s19a0b1c2d3e4"
down_revision = "s18d1e2f3a4b5"
branch_labels = None
depends_on = None
_DELIVERIES_TABLE = "freight_rpa_inbound_notification_deliveries"
_DELIVERIES_INDEXES = (
"ix_fr_inbound_notif_deliveries_recipient_user_id",
"ix_shipping_receipt_delivery_file_recipient",
"ix_shipping_receipt_delivery_unit_created",
)
def upgrade() -> None:
"""Drop inbound notification deliveries, then create outbound config / run / file tables."""
# [STEP 1] 入站投递账本:索引名含 s17b 未改的 shipping_receipt_delivery_* 与补建短名。
for index_name in _DELIVERIES_INDEXES:
op.drop_index(index_name, table_name=_DELIVERIES_TABLE)
op.drop_table(_DELIVERIES_TABLE)
# [STEP 2] 出站配置:站点一对一,字段与入站配置同构,无独立启停列。
op.create_table(
"freight_rpa_outbound_report_configs",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("source_id", sa.Integer(), nullable=False),
sa.Column("parsing_profile_id", sa.Integer(), nullable=True),
sa.Column("report_path_json", sa.JSON(), server_default=sa.text("'{}'"), nullable=False),
sa.Column("query_parameters_json", sa.JSON(), server_default=sa.text("'[]'"), nullable=False),
sa.Column("config_version", sa.Integer(), server_default=sa.text("1"), nullable=False),
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(["created_by"], ["users.id"]),
sa.ForeignKeyConstraint(["parsing_profile_id"], ["freight_rpa_parsing_profiles.id"]),
sa.ForeignKeyConstraint(["source_id"], ["freight_rpa_sources.id"]),
sa.ForeignKeyConstraint(["updated_by"], ["users.id"]),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint("source_id", name="uq_freight_rpa_outbound_report_configs_source"),
)
op.create_index(
"ix_freight_rpa_outbound_report_configs_parsing_profile_id",
"freight_rpa_outbound_report_configs",
["parsing_profile_id"],
unique=False,
)
op.create_index(
"ix_freight_rpa_outbound_report_configs_source_id",
"freight_rpa_outbound_report_configs",
["source_id"],
unique=False,
)
# [STEP 3] 出站执行单元:回调幂等;schedule_run_id 可空以支持按需触发。
op.create_table(
"freight_rpa_outbound_rpa_unit_runs",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("schedule_run_id", sa.Integer(), nullable=True),
sa.Column("source_id", sa.Integer(), nullable=False),
sa.Column("retry_of_id", sa.Integer(), nullable=True),
sa.Column("source_code", sa.String(length=64), nullable=False),
sa.Column("connector_type", sa.String(length=32), nullable=False),
sa.Column("warehouse_id", sa.String(length=64), nullable=True),
sa.Column("callback_id", sa.String(length=128), nullable=False),
sa.Column("status", sa.String(length=32), server_default="queued", nullable=False),
sa.Column("config_snapshot_json", sa.JSON(), nullable=False),
sa.Column("trigger_snapshot_json", sa.JSON(), nullable=False),
sa.Column("result_json", sa.JSON(), nullable=False),
sa.Column("error_code", sa.String(length=64), nullable=True),
sa.Column("error_message", sa.Text(), nullable=True),
sa.Column("started_at", sa.DateTime(), nullable=True),
sa.Column("finished_at", sa.DateTime(), nullable=True),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.CheckConstraint(
"status IN ('queued', 'awaiting_rpa', 'processing', 'success', 'empty', 'failed', 'cancelled')",
name="ck_freight_rpa_outbound_rpa_unit_runs_status",
),
sa.ForeignKeyConstraint(["retry_of_id"], ["freight_rpa_outbound_rpa_unit_runs.id"]),
sa.ForeignKeyConstraint(["schedule_run_id"], ["schedule_runs.id"]),
sa.ForeignKeyConstraint(["source_id"], ["freight_rpa_sources.id"]),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint("callback_id", name="uq_freight_rpa_outbound_rpa_unit_runs_callback"),
)
op.create_index(
"ix_freight_rpa_outbound_rpa_unit_runs_retry_of_id",
"freight_rpa_outbound_rpa_unit_runs",
["retry_of_id"],
unique=False,
)
op.create_index(
"ix_freight_rpa_outbound_rpa_unit_runs_schedule_run_id",
"freight_rpa_outbound_rpa_unit_runs",
["schedule_run_id"],
unique=False,
)
op.create_index(
"ix_freight_rpa_outbound_rpa_unit_runs_source_id",
"freight_rpa_outbound_rpa_unit_runs",
["source_id"],
unique=False,
)
op.create_index(
"ix_freight_rpa_outbound_unit_run_schedule_status",
"freight_rpa_outbound_rpa_unit_runs",
["schedule_run_id", "status"],
unique=False,
)
op.create_index(
"ix_freight_rpa_outbound_unit_run_source_created",
"freight_rpa_outbound_rpa_unit_runs",
["source_id", "created_at"],
unique=False,
)
# [STEP 4] 出站归档文件:含解析失败分层列,不建 notification_deliveries。
op.create_table(
"freight_rpa_outbound_report_files",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("unit_run_id", sa.Integer(), nullable=False),
sa.Column("storage_provider", sa.String(length=32), nullable=False),
sa.Column("storage_bucket", sa.String(length=128), nullable=False),
sa.Column("storage_key", sa.String(length=1024), nullable=False),
sa.Column("original_filename", sa.String(length=255), nullable=False),
sa.Column("content_type", sa.String(length=128), nullable=True),
sa.Column("file_size", sa.Integer(), nullable=False),
sa.Column("sha256", sa.String(length=64), nullable=False),
sa.Column("parse_failed_at", sa.DateTime(), nullable=True),
sa.Column("parse_error_code", sa.String(length=64), nullable=True),
sa.Column("parse_error_message", sa.Text(), nullable=True),
sa.Column("archive_expires_at", sa.DateTime(), nullable=True),
sa.Column("archive_deleted_at", sa.DateTime(), nullable=True),
sa.Column("archive_delete_result_json", sa.JSON(), nullable=False),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.CheckConstraint("file_size >= 0", name="ck_freight_rpa_outbound_report_files_size"),
sa.ForeignKeyConstraint(["unit_run_id"], ["freight_rpa_outbound_rpa_unit_runs.id"]),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint("unit_run_id", "sha256", name="uq_freight_rpa_outbound_report_files_unit_sha256"),
)
op.create_index(
"ix_freight_rpa_outbound_report_files_expires",
"freight_rpa_outbound_report_files",
["archive_expires_at", "archive_deleted_at"],
unique=False,
)
op.create_index(
"ix_freight_rpa_outbound_report_files_unit",
"freight_rpa_outbound_report_files",
["unit_run_id"],
unique=False,
)
op.create_index(
"ix_freight_rpa_outbound_report_files_unit_run_id",
"freight_rpa_outbound_report_files",
["unit_run_id"],
unique=False,
)
def downgrade() -> None:
"""Drop outbound tables, then restore the inbound deliveries table structure (empty)."""
op.drop_index(
"ix_freight_rpa_outbound_report_files_unit_run_id",
table_name="freight_rpa_outbound_report_files",
)
op.drop_index(
"ix_freight_rpa_outbound_report_files_unit",
table_name="freight_rpa_outbound_report_files",
)
op.drop_index(
"ix_freight_rpa_outbound_report_files_expires",
table_name="freight_rpa_outbound_report_files",
)
op.drop_table("freight_rpa_outbound_report_files")
op.drop_index(
"ix_freight_rpa_outbound_unit_run_source_created",
table_name="freight_rpa_outbound_rpa_unit_runs",
)
op.drop_index(
"ix_freight_rpa_outbound_unit_run_schedule_status",
table_name="freight_rpa_outbound_rpa_unit_runs",
)
op.drop_index(
"ix_freight_rpa_outbound_rpa_unit_runs_source_id",
table_name="freight_rpa_outbound_rpa_unit_runs",
)
op.drop_index(
"ix_freight_rpa_outbound_rpa_unit_runs_schedule_run_id",
table_name="freight_rpa_outbound_rpa_unit_runs",
)
op.drop_index(
"ix_freight_rpa_outbound_rpa_unit_runs_retry_of_id",
table_name="freight_rpa_outbound_rpa_unit_runs",
)
op.drop_table("freight_rpa_outbound_rpa_unit_runs")
op.drop_index(
"ix_freight_rpa_outbound_report_configs_source_id",
table_name="freight_rpa_outbound_report_configs",
)
op.drop_index(
"ix_freight_rpa_outbound_report_configs_parsing_profile_id",
table_name="freight_rpa_outbound_report_configs",
)
op.drop_table("freight_rpa_outbound_report_configs")
# 还原投递表结构供降级路径;不回填 Task 2 之后的投递行。
op.create_table(
_DELIVERIES_TABLE,
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("unit_run_id", sa.Integer(), nullable=True),
sa.Column("report_file_id", sa.Integer(), nullable=True),
sa.Column("recipient_user_id", sa.Integer(), nullable=False),
sa.Column("message_type", sa.String(length=16), nullable=False),
sa.Column("idempotency_key", sa.String(length=255), nullable=False),
sa.Column("status", sa.String(length=16), server_default=sa.text("'pending'"), nullable=False),
sa.Column("response_summary_json", sa.JSON(), server_default=sa.text("'{}'"), nullable=False),
sa.Column("error_code", sa.String(length=64), nullable=True),
sa.Column("error_message", sa.Text(), nullable=True),
sa.Column("sent_at", sa.DateTime(), nullable=True),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.Column("updated_at", sa.DateTime(), nullable=False),
sa.CheckConstraint(
"message_type IN ('file', 'summary')",
name="ck_freight_rpa_inbound_notification_deliveries_type",
),
sa.CheckConstraint(
"status IN ('pending', 'sending', 'success', 'failed')",
name="ck_freight_rpa_inbound_notification_deliveries_status",
),
sa.ForeignKeyConstraint(["unit_run_id"], ["freight_rpa_inbound_rpa_unit_runs.id"]),
sa.ForeignKeyConstraint(["report_file_id"], ["freight_rpa_inbound_report_files.id"]),
sa.ForeignKeyConstraint(["recipient_user_id"], ["users.id"]),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint(
"idempotency_key",
name="uq_freight_rpa_inbound_notification_deliveries_idempotency",
),
)
op.create_index(
"ix_fr_inbound_notif_deliveries_recipient_user_id",
_DELIVERIES_TABLE,
["recipient_user_id"],
unique=False,
)
op.create_index(
"ix_shipping_receipt_delivery_file_recipient",
_DELIVERIES_TABLE,
["report_file_id", "recipient_user_id"],
unique=False,
)
op.create_index(
"ix_shipping_receipt_delivery_unit_created",
_DELIVERIES_TABLE,
["unit_run_id", "created_at"],
unique=False,
)
@@ -0,0 +1,57 @@
"""transfer_type_configs 建表并移除 transfer_runs 类型枚举 CHECK
Revision ID: tt10a1b2c3d4e
Revises: b7a2b2155155
Create Date: 2026-10-14 12:00:00.000000
用途:调拨类型配置化(ADR 0002)第一步:新建 transfer_type_configs(编码/
四语言名称/启停/排序 + 范围规则/仓库定义/转换规则);同时移除
transfer_runs.transfer_type 的枚举 CHECK 约束(类型合法性此后由配置表
校验,服务层接线由后续任务完成)。
依赖:b7a2b2155155 为实施时 flask db heads 显示的实际 head(已确认单 head)。
逻辑:新表与 ORM 模型 TransferTypeConfig 同构(uq_transfer_type_configs_code
唯一,JSON 列沿用本目录惯例不带 server_default);transfer_type 列本身
保留不动,仅去 CHECK;downgrade 按 tt3d4e5f6a7b 原始字面量重建 CHECK,
保证回滚零漂移。
"""
from alembic import op
import sqlalchemy as sa
revision = 'tt10a1b2c3d4e'
down_revision = 'b7a2b2155155'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""建类型配置表;移除 transfer_runs.transfer_type 枚举 CHECK(列保留)。"""
op.create_table(
'transfer_type_configs',
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('code', sa.String(length=64), nullable=False),
sa.Column('names_json', sa.JSON(), nullable=False),
sa.Column('enabled', sa.Boolean(), nullable=False, server_default=sa.false()),
sa.Column('sort_order', sa.Integer(), nullable=False, server_default='0'),
sa.Column('scope_rules_json', sa.JSON(), nullable=False),
sa.Column('warehouse_config_json', sa.JSON(), nullable=False),
sa.Column('transform_rules_json', sa.JSON(), nullable=False),
sa.Column('description', sa.Text(), nullable=True),
sa.Column('created_by', sa.Integer(), sa.ForeignKey('users.id'), nullable=True),
sa.Column('updated_by', sa.Integer(), sa.ForeignKey('users.id'), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.UniqueConstraint('code', name='uq_transfer_type_configs_code'),
)
op.drop_constraint('ck_transfer_runs_transfer_type', 'transfer_runs', type_='check')
def downgrade() -> None:
"""回滚:删配置表;按 tt3d4e5f6a7b 原始字面量重建 transfer_type CHECK。"""
op.drop_table('transfer_type_configs')
op.create_check_constraint(
'ck_transfer_runs_transfer_type',
'transfer_runs',
"transfer_type IN ('in_transit_to_hub', 'hub_repair_out', 'hub_to_hub')",
)
@@ -0,0 +1,106 @@
"""transfer_movement_ledger 库存异动档建表
Revision ID: tt11b2c3d4e5f
Revises: tt10a1b2c3d4e
Create Date: 2026-10-14 14:00:00.000000
用途:库存异动档(ADR 0001,规格 §4.2)第一步:新建 transfer_movement_ledger——
外部系统收料/出货记录的平台镜像;本期收料全量落档,出货侧结构与模型就位
(record_kind='shipment' + 🔖预留列),匹配明细改为匹配时从档圈定。
依赖:tt10a1b2c3d4e 为实施时 flask db heads 显示的实际 head(已确认单 head)。
逻辑:新表与 ORM 模型 TransferMovementLedger 同构——自然键六成分
(source_code, record_kind, doc_no, line_no, line_seq, in_out_flag) 全部
NOT NULL(可空成分 server_default '')+ uq_transfer_movement_ledger_
natural_key 唯一(幂等增量落地);业务/证据列一律 nullable(外部列宽松
落地,movement_date 可空=不进收料日期圈定);source_file_id FK
ON DELETE SET NULL(来源文件清理后档事实留存);transfer_executed
封存位 default false(已执行记录防二次调拨)。索引两条:
圈档主路径 (source_code, record_kind, movement_date) 与封存扫描
(record_kind, transfer_executed)。D15 无存量数据,无回填。
"""
from alembic import op
import sqlalchemy as sa
revision = 'tt11b2c3d4e5f'
down_revision = 'tt10a1b2c3d4e'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""建库存异动档表与两条索引(与 TransferMovementLedger 模型同构)。"""
op.create_table(
'transfer_movement_ledger',
# A 单据标识(自然键成分,NOT NULL;可空成分 default '')
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('doc_no', sa.String(length=64), nullable=False),
sa.Column('line_no', sa.String(length=32), nullable=False),
sa.Column('line_seq', sa.String(length=32), nullable=False, server_default=''),
sa.Column('in_out_flag', sa.String(length=8), nullable=False, server_default=''),
# B 物料与数量(数量 Decimal 文本,与 transfer_invoice_items.receipt_quantity 同约定)
sa.Column('material_code', sa.String(length=64), nullable=True),
sa.Column('material_name', sa.String(length=200), nullable=True),
sa.Column('specification', sa.String(length=200), nullable=True),
sa.Column('lot_no', sa.String(length=64), nullable=True),
sa.Column('quantity', sa.String(length=40), nullable=True),
sa.Column('unit', sa.String(length=32), nullable=True),
# C 仓储与日期(movement_date 可空:空值记录照常落档,不进收料日期圈定)
sa.Column('warehouse_code', sa.String(length=64), nullable=True),
sa.Column('storage_code', sa.String(length=64), nullable=True),
sa.Column('movement_date', sa.String(length=16), nullable=True),
# D 业务属性(⭐本期新增强业务字段;🔖预留列,nullable,出货侧直接映射)
sa.Column('order_type', sa.String(length=64), nullable=True),
sa.Column('odm_id', sa.String(length=64), nullable=True),
sa.Column('odm_name', sa.String(length=128), nullable=True),
sa.Column('carton_id', sa.String(length=64), nullable=True),
sa.Column('pallet_id', sa.String(length=64), nullable=True),
sa.Column('doc_nature', sa.String(length=64), nullable=True),
sa.Column('movement_type', sa.String(length=64), nullable=True),
sa.Column('reason_code', sa.String(length=32), nullable=True),
sa.Column('source_ref_no', sa.String(length=64), nullable=True),
sa.Column('partner_code', sa.String(length=64), nullable=True),
sa.Column('remark', sa.Text(), nullable=True),
# E 平台溯源(证据字段:evidence_sync 原行更新时整体换新)
sa.Column('source_code', sa.String(length=64), nullable=False),
sa.Column('record_kind', sa.String(length=16), nullable=False),
sa.Column(
'source_file_id', sa.Integer(),
sa.ForeignKey('shipping_receipt_report_files.id', ondelete='SET NULL'),
nullable=True,
),
sa.Column('file_version', sa.String(length=64), nullable=True),
sa.Column('file_sha256', sa.String(length=64), nullable=True),
sa.Column('sheet_name', sa.String(length=128), nullable=True),
sa.Column('row_no', sa.Integer(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
# F 平台回写(档级封存:票据执行成功落单号时回写,永不解除)
sa.Column('transfer_executed', sa.Boolean(), nullable=False, server_default=sa.false()),
sa.Column('executed_doc_no', sa.String(length=64), nullable=True),
# 自然键唯一(幂等增量落地兜底)
sa.UniqueConstraint(
'source_code', 'record_kind', 'doc_no', 'line_no', 'line_seq', 'in_out_flag',
name='uq_transfer_movement_ledger_natural_key',
),
)
# 匹配创建圈档主路径:来源 + 记录种类 + 收料日期范围扫描。
op.create_index(
'ix_transfer_movement_ledger_source_kind_date',
'transfer_movement_ledger',
['source_code', 'record_kind', 'movement_date'],
)
# 档级封存/待匹配桶扫描:按记录种类过滤已执行位。
op.create_index(
'ix_transfer_movement_ledger_kind_executed',
'transfer_movement_ledger',
['record_kind', 'transfer_executed'],
)
def downgrade() -> None:
"""回滚:删索引与档表(D15 无存量数据,直接 drop 零损失)。"""
op.drop_index('ix_transfer_movement_ledger_kind_executed', table_name='transfer_movement_ledger')
op.drop_index('ix_transfer_movement_ledger_source_kind_date', table_name='transfer_movement_ledger')
op.drop_table('transfer_movement_ledger')
@@ -0,0 +1,57 @@
"""transfer_invoice_items 加 ledger_record_id 外键(匹配出生翻转)
Revision ID: tt12c3d4e5f6a7
Revises: tt11b2c3d4e5f
Create Date: 2026-10-14 16:00:00.000000
用途:匹配明细出生翻转(ADR 0001/D4,规格 §4.3)——transfer_invoice_items 增
ledger_record_id FK → transfer_movement_ledger.id(nullable + 索引):行由
匹配创建时从档圈定生成,ledger_record_id 指向来源档记录(业务字段=档原值)。
可空语义:隔离的历史行允许 NULL(D15 无存量数据,本列为纯前瞻结构)。
依赖:tt11b2c3d4e5f 为实施时 flask db heads 显示的实际 head(已确认单 head)。
逻辑:加列(nullable,不强制 NOT NULL——存量兼容,服务层保证新行恒非空)+
单列索引 ix_transfer_invoice_items_ledger_record_id(D17 圈档互斥的
「按档记录查占用行」高频检查走索引)。D15 无存量数据,无回填。
"""
from alembic import op
import sqlalchemy as sa
revision = 'tt12c3d4e5f6a7'
down_revision = 'tt11b2c3d4e5f'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""加 ledger_record_id FK 列与占用互斥检查索引(与模型同构)。
batch_alter_table:PostgreSQL(目标环境)渲染为普通 ALTER TABLE;
SQLite(本地/测试)经 copy-and-move 支持 ADD COLUMN 带 FK 约束。
"""
with op.batch_alter_table("transfer_invoice_items") as batch_op:
batch_op.add_column(
sa.Column(
"ledger_record_id", sa.Integer(),
# 显式命名 FK:batch 模式(SQLite copy-and-move)要求约束具名;
# PostgreSQL 渲染为命名 ADD CONSTRAINT。
sa.ForeignKey(
"transfer_movement_ledger.id",
name="fk_transfer_invoice_items_ledger_record_id",
),
nullable=True,
),
)
op.create_index(
"ix_transfer_invoice_items_ledger_record_id",
"transfer_invoice_items",
["ledger_record_id"],
)
def downgrade() -> None:
"""回滚:删索引与列(D15 无存量数据,直接 drop 零损失)。"""
op.drop_index("ix_transfer_invoice_items_ledger_record_id", table_name="transfer_invoice_items")
with op.batch_alter_table("transfer_invoice_items") as batch_op:
batch_op.drop_column("ledger_record_id")
@@ -0,0 +1,56 @@
"""transfer_runs.transfer_type 列宽放宽 String(32) → String(64)
Revision ID: tt13d4e5f6a7b8
Revises: tt12c3d4e5f6a7
Create Date: 2026-10-14 23:50:00.000000
用途:终审 I2 修复——消除「类型配置 code 与 Run 落库列宽」错位:配置表
transfer_type_configs.code 允许 ≤64 字符(正则 ^[a-z][a-z0-9_]{1,63}$),
而 transfer_runs.transfer_type 只有 String(32)——33~64 字符的 code 一旦建
匹配,Run 写入即超长(SQLite 静默截断 / PostgreSQL 直接 500)。
依赖:tt12c3d4e5f6a7 为实施时 flask db heads 显示的实际单 head(已确认)。
逻辑:alter_column 放宽到 String(64);nullable=False 与 server_default
'in_transit_to_hub' 保持建列(tt3d4e5f6a7b)初值不变——默认值是上线 SOP
的依赖(配置为空时 Run 默认归「在途仓至HUB仓」,规格 §7)。batch 模式下
PostgreSQL 渲染为普通 ALTER TYPE(varchar 放宽为元数据级变更,不重写表),
SQLite(本地/测试)经 copy-and-move 重建,故两侧都显式传 server_default
防默认值丢失;downgrade 收回 32(回滚前须确认无 >32 字符 code 的存量 Run,
否则 PG 收窄会截断报错——fail-closed 可接受)。
"""
from alembic import op
import sqlalchemy as sa
revision = 'tt13d4e5f6a7b8'
down_revision = 'tt12c3d4e5f6a7'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""transfer_runs.transfer_type 放宽至 String(64)(与配置表 code 上限对齐)。"""
with op.batch_alter_table("transfer_runs") as batch_op:
batch_op.alter_column(
"transfer_type",
existing_type=sa.String(length=32),
type_=sa.String(length=64),
existing_nullable=False,
nullable=False,
# SQLite copy-and-move 重建表时 server_default 必须显式携带,否则丢失;
# PostgreSQL 渲染为等值 SET DEFAULT(幂等无害)。
server_default='in_transit_to_hub',
)
def downgrade() -> None:
"""回滚:收回 String(32)(tt3d4e5f6a7b 建列字面量;server_default 同步保持)。"""
with op.batch_alter_table("transfer_runs") as batch_op:
batch_op.alter_column(
"transfer_type",
existing_type=sa.String(length=64),
type_=sa.String(length=32),
existing_nullable=False,
nullable=False,
server_default='in_transit_to_hub',
)
@@ -0,0 +1,89 @@
"""tt14 入站化:receipt_* 列更名 movement_*、record_kind 值迁移、自然键扩 8 成分
Revision ID: tt14a5f6a7b8c9
Revises: mh15f6a7b8c9
Create Date: 2026-10-15 10:00:00.000000
用途:落实 spec D1/D6——真实 WMS 文件行身份是「单据+行+箱/批」,自然键扩
carton_id+lot_no;receipt 说辞一次性更名(无兼容层)。明细/单据列是方向
中立(出站调拨同样产生明细),按控制器裁决用 movement_*(与异动档
transfer_movement_ledger.movement_date 命名对齐),不用 inbound_*。
依赖:mh15f6a7b8c9 为实施时 flask db heads 显示的实际单 head(并行会话已把
eah8c9d0e1f2 与 tt13d4e5f6a7b8 合并,本迁移链接其后避免双头)。
逻辑:batch_alter_table 完成 RENAME(PG/SQLite 双兼容);record_kind 值迁移为
数据 UPDATE(未上线为空操作,test 环境兜底);唯一约束按 8 成分重建,
进键维度列 carton_id/lot_no 同步 NOT NULL + default ''(R7 终审:nullable
成分的 NULL 不参与唯一比对会逃逸约束;落档链路恒写 '',无存量 NULL)。
列类型取自建表迁移(it1a2b3c4d5e/it2c3d4e5f6a7/tt0d1e2f3a4b)逐一核对。
"""
from alembic import op
import sqlalchemy as sa
revision = "tt14a5f6a7b8c9"
down_revision = "mh15f6a7b8c9"
branch_labels = None
depends_on = None
def upgrade() -> None:
"""receipt_* 列更名 movement_*、record_kind 值迁移 receipt→inbound、自然键扩 8 成分。"""
with op.batch_alter_table("transfer_invoice_items") as batch:
batch.alter_column("receipt_date", new_column_name="movement_date",
existing_type=sa.String(length=16), existing_nullable=True)
batch.alter_column("receipt_quantity", new_column_name="movement_quantity",
existing_type=sa.String(length=40), existing_nullable=False)
batch.alter_column("receipt_warehouse_code", new_column_name="movement_warehouse_code",
existing_type=sa.String(length=64), existing_nullable=False)
with op.batch_alter_table("transfer_documents") as batch:
batch.alter_column("receipt_date", new_column_name="movement_date",
existing_type=sa.String(length=16), existing_nullable=False)
op.execute("UPDATE transfer_movement_ledger SET record_kind='inbound' WHERE record_kind='receipt'")
op.execute("UPDATE transfer_movement_ledger SET record_kind='outbound' WHERE record_kind='shipment'")
with op.batch_alter_table("transfer_movement_ledger") as batch:
# R7(终审修复):carton_id/lot_no 进键即 NOT NULL + default ''——nullable
# 成分在 PG/SQLite 唯一比对中 NULL≠NULL,会逃逸唯一约束(同箱同批塌缩)。
# 落档链路恒写 '',无存量 NULL(未上线),SET NOT NULL 安全。
batch.alter_column("carton_id", existing_type=sa.String(length=64),
nullable=False, server_default='', existing_server_default=None)
batch.alter_column("lot_no", existing_type=sa.String(length=64),
nullable=False, server_default='', existing_server_default=None)
batch.drop_constraint("uq_transfer_movement_ledger_natural_key", type_="unique")
batch.create_unique_constraint(
"uq_transfer_movement_ledger_natural_key",
["source_code", "record_kind", "doc_no", "line_no", "line_seq",
"in_out_flag", "carton_id", "lot_no"],
)
def downgrade() -> None:
"""回滚:自然键收回 6 成分、维度列还原可空无默认、record_kind 值还原、列名还原。
注意:收窄为 6 成分唯一约束时,要求不存在同 6 元组异 carton/lot 并存数据,
否则约束重建 IntegrityError(固有语义,非缺陷——6 成分键本就无法区分同键多箱/批)。
"""
with op.batch_alter_table("transfer_movement_ledger") as batch:
# 对称还原 tt14 upgrade:server_default=None 渲染 DROP DEFAULT(PG),SQLite
# batch 重建表时不携带默认值(alembic 1.19 语义,False=不动、None=移除)。
batch.alter_column("carton_id", existing_type=sa.String(length=64),
nullable=True, server_default=None, existing_server_default='')
batch.alter_column("lot_no", existing_type=sa.String(length=64),
nullable=True, server_default=None, existing_server_default='')
batch.drop_constraint("uq_transfer_movement_ledger_natural_key", type_="unique")
batch.create_unique_constraint(
"uq_transfer_movement_ledger_natural_key",
["source_code", "record_kind", "doc_no", "line_no", "line_seq", "in_out_flag"],
)
op.execute("UPDATE transfer_movement_ledger SET record_kind='receipt' WHERE record_kind='inbound'")
op.execute("UPDATE transfer_movement_ledger SET record_kind='shipment' WHERE record_kind='outbound'")
with op.batch_alter_table("transfer_documents") as batch:
batch.alter_column("movement_date", new_column_name="receipt_date",
existing_type=sa.String(length=16), existing_nullable=False)
with op.batch_alter_table("transfer_invoice_items") as batch:
batch.alter_column("movement_date", new_column_name="receipt_date",
existing_type=sa.String(length=16), existing_nullable=True)
batch.alter_column("movement_quantity", new_column_name="receipt_quantity",
existing_type=sa.String(length=40), existing_nullable=False)
batch.alter_column("movement_warehouse_code", new_column_name="receipt_warehouse_code",
existing_type=sa.String(length=64), existing_nullable=False)
@@ -0,0 +1,66 @@
"""tt15 purpose 枚举改版:inventory/movement → onhand/inbound/outbound
Revision ID: tt15b6a7b8c9d0
Revises: tt14a5f6a7b8c9
Create Date: 2026-10-15 12:00:00.000000
用途:通用文件解析规则表 shipping_inventory_parsing_profiles.purpose 由二值
(inventory / movement)扩为方向化三元枚举(onhand / inbound / outbound):
onhand=在手库存文件(原 inventory),inbound=入站收料文件(原 movement),
outbound=出站文件(结构就位,暂无运行时消费方)。
依赖:tt14a5f6a7b8c9 为实施时 flask db heads 显示的实际单 head;purpose 列与旧
CHECK 由 b17e3d4c5a60 / if1b2c3d4e5g 建立。
逻辑:四个操作按序执行——DROP 旧 CHECK → 数据 UPDATE(inventory→onhand、
movement→inbound)→ ADD 新 CHECK → SET DEFAULT 'onhand'。SQLite 不支持裸
ALTER TABLE DROP CONSTRAINT / ALTER COLUMN SET DEFAULT,故 DDL 全部走
batch_alter_table(batch 重建表,SQLite 往返可执行),PG 端渲染等价于裸
ALTER 语句;数据 UPDATE 用 op.execute 独立执行(不进 batch)。
downgrade 对称:outbound 行无 1:1 旧值,迁移到 'movement'(结构就位语义最接近)。
"""
from alembic import op
import sqlalchemy as sa
revision = "tt15b6a7b8c9d0"
down_revision = "tt14a5f6a7b8c9"
branch_labels = None
depends_on = None
def upgrade() -> None:
"""purpose 枚举改版:换 CHECK、迁移存量值、default 置 'onhand'。"""
with op.batch_alter_table("shipping_inventory_parsing_profiles") as batch:
batch.drop_constraint(
"ck_shipping_inventory_parsing_profiles_purpose", type_="check",
)
op.execute("UPDATE shipping_inventory_parsing_profiles SET purpose='onhand' WHERE purpose='inventory'")
op.execute("UPDATE shipping_inventory_parsing_profiles SET purpose='inbound' WHERE purpose='movement'")
with op.batch_alter_table("shipping_inventory_parsing_profiles") as batch:
batch.create_check_constraint(
"ck_shipping_inventory_parsing_profiles_purpose",
"purpose IN ('onhand', 'inbound', 'outbound')",
)
batch.alter_column(
"purpose", existing_type=sa.String(length=16), existing_nullable=False,
server_default="onhand", existing_server_default="inventory",
)
def downgrade() -> None:
"""回滚:default 还原 'inventory'、换回旧 CHECK,存量值对称还原(outbound→movement)。"""
with op.batch_alter_table("shipping_inventory_parsing_profiles") as batch:
batch.drop_constraint(
"ck_shipping_inventory_parsing_profiles_purpose", type_="check",
)
batch.alter_column(
"purpose", existing_type=sa.String(length=16), existing_nullable=False,
server_default="inventory", existing_server_default="onhand",
)
op.execute("UPDATE shipping_inventory_parsing_profiles SET purpose='inventory' WHERE purpose='onhand'")
op.execute("UPDATE shipping_inventory_parsing_profiles SET purpose='movement' WHERE purpose IN ('inbound', 'outbound')")
with op.batch_alter_table("shipping_inventory_parsing_profiles") as batch:
batch.create_check_constraint(
"ck_shipping_inventory_parsing_profiles_purpose",
"purpose IN ('inventory', 'movement')",
)
@@ -0,0 +1,62 @@
"""retire not_matured item status (maturity concept removal 2026-10-16)
Revision ID: tt16a7b8c9d0e1f2
Revises: tt15b6a7b8c9d0
Create Date: 2026-10-16
用途:「成熟」概念退役(用户裁定:数据无成熟属性,日期边界由调用方入参严格
给定)——transfer_invoice_items.status 冻结枚举删去 'not_matured'
(13 态 → 12 态),CHECK 约束 ck_transfer_invoice_items_status 同步重建。
数据迁移:存量 not_matured 行重映射为 'cancelled'(语义最近=未进入执行且不再
可执行;D17 占用过滤本就排除 cancelled,占用随之自然释放)。result_code
保留历史值 'not_matured' 不改写(无约束的自由文本,留审计溯源)。
降级:仅重建旧 CHECK(含 not_matured);已重映射的行无法还原原状态(dev 数据,
有损降级,docstring 如实声明)。
依赖:无数据依赖;与 tt14/tt15 并行域迁移同链(单 head 顺序 tt14→tt15→tt16)。
"""
from alembic import op
revision = 'tt16a7b8c9d0e1f2'
down_revision = 'tt15b6a7b8c9d0'
branch_labels = None
depends_on = None
# 12 态枚举(与 app.models.in_transit_transfer.TRANSFER_ITEM_STATUSES 同步;
# 迁移文件不 import 应用模型,避免迁移期模型漂移牵连)。
_ITEM_STATUSES_V12 = (
'file_pending', 'file_ready', 'matching', 'ready_to_execute', 'executing',
'success', 'duplicate_success', 'blocked_recoverable',
'result_unknown', 'manually_closed', 'cancelled', 'notification_failed',
)
_ITEM_STATUSES_V13 = ('not_matured',) + _ITEM_STATUSES_V12[:8] + _ITEM_STATUSES_V12[8:]
def _statuses_sql(statuses: tuple[str, ...]) -> str:
return ', '.join(repr(s) for s in statuses)
def upgrade() -> None:
# [STEP 1] 存量 not_matured 行重映射 cancelled(必须先于 CHECK 重建,否则
# 旧值撞新约束);占用释放由 D17 占用过滤排除 cancelled 自然达成。
op.execute(
"UPDATE transfer_invoice_items SET status = 'cancelled' "
"WHERE status = 'not_matured'"
)
# [STEP 2] CHECK 重建:旧约束 → 12 态新约束。
op.drop_constraint('ck_transfer_invoice_items_status', 'transfer_invoice_items', type_='check')
op.create_check_constraint(
'ck_transfer_invoice_items_status',
'transfer_invoice_items',
f"status IN ({_statuses_sql(_ITEM_STATUSES_V12)})",
)
def downgrade() -> None:
# [STEP 1] CHECK 回退到 13 态(已重映射的 cancelled 行无法识别还原,有损降级)。
op.drop_constraint('ck_transfer_invoice_items_status', 'transfer_invoice_items', type_='check')
op.create_check_constraint(
'ck_transfer_invoice_items_status',
'transfer_invoice_items',
f"status IN ({_statuses_sql(_ITEM_STATUSES_V13)})",
)
@@ -0,0 +1,54 @@
"""tt16:RPA 排程任务 key 更名(批次 R,随代码同窗口发布)
Revision ID: tt16c7d8e9f0a1b2
Revises: tt16a7b8c9d0e1f2
Create Date: 2026-10-16
用途:schedule_tasks.platform_api_path 存量的三个 RPA 平台 job key 入站化改名——
shipping-inventory-rpa→freight-rpa-onhand(在手/库存)、
freight-receipt-rpa→freight-rpa-inbound(入站/收料)、
freight-receipt-rpa-retention→freight-rpa-inbound-retention(入站归档保留期清理),
与 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 起
排程表无独立 job_key 列,运行时一律读写 platform_api_path,见
schedule_contract.normalize_job_key);三键 UPDATE;
options_source 键(shipping_inventory_sources / shipping_receipt_sources)
绑定业务表名,本批不动(批次 S)。
降级:反向映射对称 UPDATE,逐键还原;无表结构变更,SQLite/PG 语句通用。
Fix round 1:SQL 列名由计划骨架误写的 job_key 修正为真实列 platform_api_path
(计划骨架错误,控制方已认领;契约测试桩表同步改真实列名)。
"""
from alembic import op
revision = "tt16c7d8e9f0a1b2"
down_revision = "tt16a7b8c9d0e1f2"
branch_labels = None
depends_on = None
# 升级方向三键对照;downgrade 取反。键值与 job_registry.register_platform_job 一致。
_MAPPING = {
"shipping-inventory-rpa": "freight-rpa-onhand",
"freight-receipt-rpa": "freight-rpa-inbound",
"freight-receipt-rpa-retention": "freight-rpa-inbound-retention",
}
def upgrade() -> None:
"""job key 三键前向改名:platform_api_path 旧行 UPDATE 为新键(无表结构变更)。"""
for old_key, new_key in _MAPPING.items():
op.execute(
f"UPDATE schedule_tasks SET platform_api_path='{new_key}' "
f"WHERE platform_api_path='{old_key}'"
)
def downgrade() -> None:
"""job key 三键反向还原:platform_api_path 新键 UPDATE 回旧键(与 upgrade 对称)。"""
for old_key, new_key in _MAPPING.items():
op.execute(
f"UPDATE schedule_tasks SET platform_api_path='{old_key}' "
f"WHERE platform_api_path='{new_key}'"
)
@@ -0,0 +1,52 @@
"""transfer_movement_ledger 增加外部单号/外部项次并扩自然键唯一约束(2026-10-21)
Revision ID: tt21c8d9e0f1a2
Revises: s19a0b1c2d3e4
Create Date: 2026-10-21
用途:库存异动档新增外部单据身份两列(external_doc_no/external_line_no,对应
CRANE/Lognet 出站报告的 WMS Order #/行号),并把两列加入自然键唯一约束
uq_transfer_movement_ledger_natural_key(8→10 成分)——外部单号+项次作为
档幂等主键管控:同一外部单号+项次的重复落档/证据更新收敛到同一档行。
依赖:movement_contract.MOVEMENT_FIELDS 追加同名契约字段(模型列 1:1 镜像断言
在 ledger_sync 导入期 fail-fast)。
逻辑:两列 NOT NULL + server_default ''(自然键可空成分以空串参与唯一比对,
防 PG NULL 逃逸);约束先删后建(PG/SQLite 通用)。存量行两列填默认空串
参与键;来源配置外部映射后重放同文件即按新键收敛,必要时走「清空并重解析」
重建(backlog_reparse_service)。
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "tt21c8d9e0f1a2"
down_revision = "s19a0b1c2d3e4"
branch_labels = None
depends_on = None
_TABLE = "transfer_movement_ledger"
_NATURAL_KEY = "uq_transfer_movement_ledger_natural_key"
_NATURAL_KEY_COLUMNS = (
"source_code", "record_kind", "doc_no", "line_no", "line_seq", "in_out_flag",
"carton_id", "lot_no", "external_doc_no", "external_line_no",
)
def upgrade() -> None:
"""加两列(NOT NULL + server_default '',存量行回填空串)并扩自然键唯一约束。"""
op.add_column(_TABLE, sa.Column("external_doc_no", sa.String(64), nullable=False, server_default=""))
op.add_column(_TABLE, sa.Column("external_line_no", sa.String(32), nullable=False, server_default=""))
op.drop_constraint(_NATURAL_KEY, _TABLE, type_="unique")
op.create_unique_constraint(_NATURAL_KEY, _TABLE, list(_NATURAL_KEY_COLUMNS))
def downgrade() -> None:
"""回退:恢复 8 成分唯一约束并删两列(外部身份列数据随列删除,不留残档)。"""
op.drop_constraint(_NATURAL_KEY, _TABLE, type_="unique")
op.create_unique_constraint(
_NATURAL_KEY, _TABLE,
["source_code", "record_kind", "doc_no", "line_no", "line_seq", "in_out_flag",
"carton_id", "lot_no"],
)
op.drop_column(_TABLE, "external_line_no")
op.drop_column(_TABLE, "external_doc_no")