feat(migration): 优化发货通知文档候选表的创建与索引补全逻辑

This commit is contained in:
hugo committed 2026-07-14 21:35:31 +08:00
1 parent bc86720744
commit 70f684b94a
1 file changed
+282 -201
@@ -4,6 +4,7 @@ backend/migrations/versions/d3e4f5a6b7c8_shipping_notice_documents_candidates.py
用途:阶段二——FileAsset 派生字段、ShippingNoticeDocument/Candidate 表、Task.source_candidate_id。
依赖:Alembic revision c2d3e4f5a6b7。
逻辑:EML 附件子资产挂 parent_asset_id;文档/候选支撑「一邮件多订单」识别(不创建 Task)。
升级幂等:本地若曾 create_all 已有 documents/candidates,则只补缺列/索引。
Revision ID: d3e4f5a6b7c8
Revises: c2d3e4f5a6b7
@@ -21,218 +22,298 @@ branch_labels = None
depends_on = None
def upgrade() -> None:
def _table_names(insp: sa.Inspector) -> set[str]:
"""返回当前 schema 下的表名集合。"""
return set(insp.get_table_names())
def _table_columns(insp: sa.Inspector, table_name: str) -> set[str]:
"""返回指定表的列名集合;表不存在时返回空集合。"""
if table_name not in _table_names(insp):
return set()
return {col["name"] for col in insp.get_columns(table_name)}
def _index_names(insp: sa.Inspector, table_name: str) -> set[str]:
"""返回指定表的索引名集合;表不存在时返回空集合。"""
if table_name not in _table_names(insp):
return set()
return {str(ix.get("name") or "") for ix in insp.get_indexes(table_name)}
def _fk_names(insp: sa.Inspector, table_name: str) -> set[str]:
"""返回指定表的外键约束名集合;表不存在时返回空集合。"""
if table_name not in _table_names(insp):
return set()
return {str(fk.get("name") or "") for fk in insp.get_foreign_keys(table_name)}
def _ensure_file_asset_derived_columns() -> None:
"""
为 file_assets 补齐派生附件字段与索引。
核心逻辑:列/外键/索引按存在性跳过,兼容 create_all 漂移库。
"""
# [STEP 1] 探测已有列与索引
bind = op.get_bind()
insp = sa.inspect(bind)
cols = _table_columns(insp, "file_assets")
indexes = _index_names(insp, "file_assets")
fks = _fk_names(insp, "file_assets")
# [STEP 2] 缺什么补什么
with op.batch_alter_table("file_assets", schema=None) as batch_op:
batch_op.add_column(sa.Column("parent_asset_id", sa.Integer(), nullable=True))
batch_op.add_column(
sa.Column("asset_role", sa.String(length=32), server_default="upload", nullable=False)
)
batch_op.add_column(sa.Column("source_attachment_key", sa.String(length=64), nullable=True))
batch_op.create_foreign_key(
"fk_file_assets_parent_asset_id",
"file_assets",
["parent_asset_id"],
["id"],
)
batch_op.create_index("ix_file_assets_parent_asset_id", ["parent_asset_id"], unique=False)
batch_op.create_index(
"ix_file_assets_parent_content_hash",
["parent_asset_id", "content_hash"],
unique=False,
)
batch_op.create_index(
"ix_file_assets_parent_attachment_key",
["parent_asset_id", "source_attachment_key"],
unique=False,
if "parent_asset_id" not in cols:
batch_op.add_column(sa.Column("parent_asset_id", sa.Integer(), nullable=True))
if "asset_role" not in cols:
batch_op.add_column(
sa.Column("asset_role", sa.String(length=32), server_default="upload", nullable=False)
)
if "source_attachment_key" not in cols:
batch_op.add_column(sa.Column("source_attachment_key", sa.String(length=64), nullable=True))
if "fk_file_assets_parent_asset_id" not in fks:
batch_op.create_foreign_key(
"fk_file_assets_parent_asset_id",
"file_assets",
["parent_asset_id"],
["id"],
)
if "ix_file_assets_parent_asset_id" not in indexes:
batch_op.create_index("ix_file_assets_parent_asset_id", ["parent_asset_id"], unique=False)
if "ix_file_assets_parent_content_hash" not in indexes:
batch_op.create_index(
"ix_file_assets_parent_content_hash",
["parent_asset_id", "content_hash"],
unique=False,
)
if "ix_file_assets_parent_attachment_key" not in indexes:
batch_op.create_index(
"ix_file_assets_parent_attachment_key",
["parent_asset_id", "source_attachment_key"],
unique=False,
)
def _ensure_shipping_notice_documents() -> None:
"""
确保 shipping_notice_documents 表及索引存在。
核心逻辑:表已存在则只补缺索引,避免 DuplicateTable。
"""
bind = op.get_bind()
insp = sa.inspect(bind)
if "shipping_notice_documents" not in _table_names(insp):
op.create_table(
"shipping_notice_documents",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("intake_id", sa.Integer(), nullable=False),
sa.Column("asset_id", sa.Integer(), nullable=True),
sa.Column("document_type", sa.String(length=32), nullable=False),
sa.Column("attachment_key", sa.String(length=64), nullable=False),
sa.Column("filename", sa.String(length=255), nullable=True),
sa.Column("content_hash", sa.String(length=64), nullable=True),
sa.Column("classification", sa.String(length=32), nullable=False),
sa.Column("parse_status", sa.String(length=32), nullable=False),
sa.Column("extracted_text", sa.Text(), nullable=True),
sa.Column("parse_warnings_json", sa.JSON(), nullable=True),
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.Column("updated_at", sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(["asset_id"], ["file_assets.id"]),
sa.ForeignKeyConstraint(["intake_id"], ["shipping_notice_intakes.id"]),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint(
"intake_id",
"attachment_key",
name="uq_shipping_notice_documents_intake_attachment_key",
),
)
op.create_table(
"shipping_notice_documents",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("intake_id", sa.Integer(), nullable=False),
sa.Column("asset_id", sa.Integer(), nullable=True),
sa.Column("document_type", sa.String(length=32), nullable=False),
sa.Column("attachment_key", sa.String(length=64), nullable=False),
sa.Column("filename", sa.String(length=255), nullable=True),
sa.Column("content_hash", sa.String(length=64), nullable=True),
sa.Column("classification", sa.String(length=32), nullable=False),
sa.Column("parse_status", sa.String(length=32), nullable=False),
sa.Column("extracted_text", sa.Text(), nullable=True),
sa.Column("parse_warnings_json", sa.JSON(), nullable=True),
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.Column("updated_at", sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(["asset_id"], ["file_assets.id"]),
sa.ForeignKeyConstraint(["intake_id"], ["shipping_notice_intakes.id"]),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint(
"intake_id",
"attachment_key",
name="uq_shipping_notice_documents_intake_attachment_key",
),
)
op.create_index(
"ix_shipping_notice_documents_intake_id",
"shipping_notice_documents",
["intake_id"],
unique=False,
)
op.create_index(
"ix_shipping_notice_documents_asset_id",
"shipping_notice_documents",
["asset_id"],
unique=False,
)
op.create_index(
"ix_shipping_notice_documents_content_hash",
"shipping_notice_documents",
["content_hash"],
unique=False,
)
op.create_index(
"ix_shipping_notice_documents_parse_status",
"shipping_notice_documents",
["parse_status"],
unique=False,
)
op.create_index(
"ix_shipping_notice_documents_created_at",
"shipping_notice_documents",
["created_at"],
unique=False,
)
insp = sa.inspect(bind)
indexes = _index_names(insp, "shipping_notice_documents")
desired = {
"ix_shipping_notice_documents_intake_id": ["intake_id"],
"ix_shipping_notice_documents_asset_id": ["asset_id"],
"ix_shipping_notice_documents_content_hash": ["content_hash"],
"ix_shipping_notice_documents_parse_status": ["parse_status"],
"ix_shipping_notice_documents_created_at": ["created_at"],
}
for name, cols in desired.items():
if name not in indexes:
op.create_index(name, "shipping_notice_documents", cols, unique=False)
op.create_table(
"shipping_notice_candidates",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("candidate_no", sa.String(length=64), nullable=False),
sa.Column("intake_id", sa.Integer(), nullable=False),
sa.Column("primary_document_id", sa.Integer(), nullable=False),
sa.Column("po_number", sa.String(length=128), nullable=True),
sa.Column("structured_result_json", sa.JSON(), nullable=True),
sa.Column("confidence", sa.Float(), nullable=True),
sa.Column(
"validation_status",
sa.String(length=32),
server_default="pending",
nullable=False,
),
sa.Column("conflicts_json", sa.JSON(), nullable=True),
sa.Column("selected", sa.Boolean(), server_default=sa.text("true"), nullable=False),
sa.Column("business_fingerprint", sa.String(length=64), nullable=True),
sa.Column("fingerprint_version", sa.String(length=32), nullable=True),
sa.Column("fingerprint_strength", sa.String(length=32), nullable=True),
sa.Column(
"duplicate_status",
sa.String(length=32),
server_default="unchecked",
nullable=False,
),
sa.Column("duplicate_matches_json", sa.JSON(), nullable=True),
sa.Column("duplicate_resolution", sa.String(length=32), nullable=True),
sa.Column("duplicate_resolution_reason", sa.Text(), nullable=True),
sa.Column("duplicate_target_task_no", sa.String(length=64), nullable=True),
sa.Column("duplicate_checked_at", sa.DateTime(), nullable=True),
sa.Column("consumed_task_id", sa.Integer(), nullable=True),
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.Column("updated_at", sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(["consumed_task_id"], ["shipping_tasks.id"]),
sa.ForeignKeyConstraint(["intake_id"], ["shipping_notice_intakes.id"]),
sa.ForeignKeyConstraint(["primary_document_id"], ["shipping_notice_documents.id"]),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint("candidate_no", name="uq_shipping_notice_candidates_candidate_no"),
sa.UniqueConstraint(
"intake_id",
"primary_document_id",
name="uq_shipping_notice_candidates_intake_primary_document",
),
)
op.create_index(
"ix_shipping_notice_candidates_intake_id",
"shipping_notice_candidates",
["intake_id"],
unique=False,
)
op.create_index(
"ix_shipping_notice_candidates_primary_document_id",
"shipping_notice_candidates",
["primary_document_id"],
unique=False,
)
op.create_index(
"ix_shipping_notice_candidates_po_number",
"shipping_notice_candidates",
["po_number"],
unique=False,
)
op.create_index(
"ix_shipping_notice_candidates_user_fingerprint",
"shipping_notice_candidates",
["business_fingerprint"],
unique=False,
)
op.create_index(
"ix_shipping_notice_candidates_duplicate_status",
"shipping_notice_candidates",
["duplicate_status"],
unique=False,
)
op.create_index(
"ix_shipping_notice_candidates_created_at",
"shipping_notice_candidates",
["created_at"],
unique=False,
)
def _ensure_shipping_notice_candidates() -> None:
"""
确保 shipping_notice_candidates 表及索引存在。
核心逻辑:表已存在则只补缺索引,避免 DuplicateTable。
"""
bind = op.get_bind()
insp = sa.inspect(bind)
if "shipping_notice_candidates" not in _table_names(insp):
op.create_table(
"shipping_notice_candidates",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("candidate_no", sa.String(length=64), nullable=False),
sa.Column("intake_id", sa.Integer(), nullable=False),
sa.Column("primary_document_id", sa.Integer(), nullable=False),
sa.Column("po_number", sa.String(length=128), nullable=True),
sa.Column("structured_result_json", sa.JSON(), nullable=True),
sa.Column("confidence", sa.Float(), nullable=True),
sa.Column(
"validation_status",
sa.String(length=32),
server_default="pending",
nullable=False,
),
sa.Column("conflicts_json", sa.JSON(), nullable=True),
sa.Column("selected", sa.Boolean(), server_default=sa.text("true"), nullable=False),
sa.Column("business_fingerprint", sa.String(length=64), nullable=True),
sa.Column("fingerprint_version", sa.String(length=32), nullable=True),
sa.Column("fingerprint_strength", sa.String(length=32), nullable=True),
sa.Column(
"duplicate_status",
sa.String(length=32),
server_default="unchecked",
nullable=False,
),
sa.Column("duplicate_matches_json", sa.JSON(), nullable=True),
sa.Column("duplicate_resolution", sa.String(length=32), nullable=True),
sa.Column("duplicate_resolution_reason", sa.Text(), nullable=True),
sa.Column("duplicate_target_task_no", sa.String(length=64), nullable=True),
sa.Column("duplicate_checked_at", sa.DateTime(), nullable=True),
sa.Column("consumed_task_id", sa.Integer(), nullable=True),
sa.Column("created_at", sa.DateTime(), nullable=True),
sa.Column("updated_at", sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(["consumed_task_id"], ["shipping_tasks.id"]),
sa.ForeignKeyConstraint(["intake_id"], ["shipping_notice_intakes.id"]),
sa.ForeignKeyConstraint(["primary_document_id"], ["shipping_notice_documents.id"]),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint("candidate_no", name="uq_shipping_notice_candidates_candidate_no"),
sa.UniqueConstraint(
"intake_id",
"primary_document_id",
name="uq_shipping_notice_candidates_intake_primary_document",
),
)
insp = sa.inspect(bind)
indexes = _index_names(insp, "shipping_notice_candidates")
desired = {
"ix_shipping_notice_candidates_intake_id": ["intake_id"],
"ix_shipping_notice_candidates_primary_document_id": ["primary_document_id"],
"ix_shipping_notice_candidates_po_number": ["po_number"],
"ix_shipping_notice_candidates_user_fingerprint": ["business_fingerprint"],
"ix_shipping_notice_candidates_duplicate_status": ["duplicate_status"],
"ix_shipping_notice_candidates_created_at": ["created_at"],
}
for name, cols in desired.items():
if name not in indexes:
op.create_index(name, "shipping_notice_candidates", cols, unique=False)
def _ensure_task_source_candidate() -> None:
"""
为 shipping_tasks 补齐 source_candidate_id 及外键/索引。
核心逻辑:列已存在则跳过,兼容部分应用过的漂移库。
"""
bind = op.get_bind()
insp = sa.inspect(bind)
cols = _table_columns(insp, "shipping_tasks")
indexes = _index_names(insp, "shipping_tasks")
fks = _fk_names(insp, "shipping_tasks")
with op.batch_alter_table("shipping_tasks", schema=None) as batch_op:
batch_op.add_column(sa.Column("source_candidate_id", sa.Integer(), nullable=True))
batch_op.create_foreign_key(
"fk_shipping_tasks_source_candidate_id",
"shipping_notice_candidates",
["source_candidate_id"],
["id"],
)
batch_op.create_index(
"ix_shipping_tasks_source_candidate_id",
["source_candidate_id"],
unique=False,
)
if "source_candidate_id" not in cols:
batch_op.add_column(sa.Column("source_candidate_id", sa.Integer(), nullable=True))
if "fk_shipping_tasks_source_candidate_id" not in fks:
batch_op.create_foreign_key(
"fk_shipping_tasks_source_candidate_id",
"shipping_notice_candidates",
["source_candidate_id"],
["id"],
)
if "ix_shipping_tasks_source_candidate_id" not in indexes:
batch_op.create_index(
"ix_shipping_tasks_source_candidate_id",
["source_candidate_id"],
unique=False,
)
def upgrade() -> None:
"""
应用阶段二 documents/candidates 结构;对已存在对象幂等跳过。
核心逻辑:先补 FileAsset 派生字段,再建/补齐 Document·Candidate,最后挂 Task 外键。
"""
_ensure_file_asset_derived_columns()
_ensure_shipping_notice_documents()
_ensure_shipping_notice_candidates()
_ensure_task_source_candidate()
def downgrade() -> None:
"""回滚阶段二结构;表/列不存在时依赖调用方环境保证对称。"""
bind = op.get_bind()
insp = sa.inspect(bind)
task_cols = _table_columns(insp, "shipping_tasks")
task_indexes = _index_names(insp, "shipping_tasks")
task_fks = _fk_names(insp, "shipping_tasks")
with op.batch_alter_table("shipping_tasks", schema=None) as batch_op:
batch_op.drop_index("ix_shipping_tasks_source_candidate_id")
batch_op.drop_constraint("fk_shipping_tasks_source_candidate_id", type_="foreignkey")
batch_op.drop_column("source_candidate_id")
if "ix_shipping_tasks_source_candidate_id" in task_indexes:
batch_op.drop_index("ix_shipping_tasks_source_candidate_id")
if "fk_shipping_tasks_source_candidate_id" in task_fks:
batch_op.drop_constraint("fk_shipping_tasks_source_candidate_id", type_="foreignkey")
if "source_candidate_id" in task_cols:
batch_op.drop_column("source_candidate_id")
op.drop_index("ix_shipping_notice_candidates_created_at", table_name="shipping_notice_candidates")
op.drop_index(
"ix_shipping_notice_candidates_duplicate_status",
table_name="shipping_notice_candidates",
)
op.drop_index(
"ix_shipping_notice_candidates_user_fingerprint",
table_name="shipping_notice_candidates",
)
op.drop_index("ix_shipping_notice_candidates_po_number", table_name="shipping_notice_candidates")
op.drop_index(
"ix_shipping_notice_candidates_primary_document_id",
table_name="shipping_notice_candidates",
)
op.drop_index("ix_shipping_notice_candidates_intake_id", table_name="shipping_notice_candidates")
op.drop_table("shipping_notice_candidates")
if "shipping_notice_candidates" in _table_names(insp):
cand_indexes = _index_names(insp, "shipping_notice_candidates")
for name in (
"ix_shipping_notice_candidates_created_at",
"ix_shipping_notice_candidates_duplicate_status",
"ix_shipping_notice_candidates_user_fingerprint",
"ix_shipping_notice_candidates_po_number",
"ix_shipping_notice_candidates_primary_document_id",
"ix_shipping_notice_candidates_intake_id",
):
if name in cand_indexes:
op.drop_index(name, table_name="shipping_notice_candidates")
op.drop_table("shipping_notice_candidates")
op.drop_index("ix_shipping_notice_documents_created_at", table_name="shipping_notice_documents")
op.drop_index("ix_shipping_notice_documents_parse_status", table_name="shipping_notice_documents")
op.drop_index("ix_shipping_notice_documents_content_hash", table_name="shipping_notice_documents")
op.drop_index("ix_shipping_notice_documents_asset_id", table_name="shipping_notice_documents")
op.drop_index("ix_shipping_notice_documents_intake_id", table_name="shipping_notice_documents")
op.drop_table("shipping_notice_documents")
insp = sa.inspect(bind)
if "shipping_notice_documents" in _table_names(insp):
doc_indexes = _index_names(insp, "shipping_notice_documents")
for name in (
"ix_shipping_notice_documents_created_at",
"ix_shipping_notice_documents_parse_status",
"ix_shipping_notice_documents_content_hash",
"ix_shipping_notice_documents_asset_id",
"ix_shipping_notice_documents_intake_id",
):
if name in doc_indexes:
op.drop_index(name, table_name="shipping_notice_documents")
op.drop_table("shipping_notice_documents")
insp = sa.inspect(bind)
fa_cols = _table_columns(insp, "file_assets")
fa_indexes = _index_names(insp, "file_assets")
fa_fks = _fk_names(insp, "file_assets")
with op.batch_alter_table("file_assets", schema=None) as batch_op:
batch_op.drop_index("ix_file_assets_parent_attachment_key")
batch_op.drop_index("ix_file_assets_parent_content_hash")
batch_op.drop_index("ix_file_assets_parent_asset_id")
batch_op.drop_constraint("fk_file_assets_parent_asset_id", type_="foreignkey")
batch_op.drop_column("source_attachment_key")
batch_op.drop_column("asset_role")
batch_op.drop_column("parent_asset_id")
if "ix_file_assets_parent_attachment_key" in fa_indexes:
batch_op.drop_index("ix_file_assets_parent_attachment_key")
if "ix_file_assets_parent_content_hash" in fa_indexes:
batch_op.drop_index("ix_file_assets_parent_content_hash")
if "ix_file_assets_parent_asset_id" in fa_indexes:
batch_op.drop_index("ix_file_assets_parent_asset_id")
if "fk_file_assets_parent_asset_id" in fa_fks:
batch_op.drop_constraint("fk_file_assets_parent_asset_id", type_="foreignkey")
if "source_attachment_key" in fa_cols:
batch_op.drop_column("source_attachment_key")
if "asset_role" in fa_cols:
batch_op.drop_column("asset_role")
if "parent_asset_id" in fa_cols:
batch_op.drop_column("parent_asset_id")