feat(integration-connector): 新增集成连接器管理后台,支持关键字段拆列配置

This commit is contained in:
hugo committed 2026-09-04 02:16:41 +08:00
1 parent bf30cddc4a
commit 1269e04116
28 files changed
+2909 -155

No files matched your search

@@ -0,0 +1,385 @@
"""订单明细身份、项次及 OT 生命周期契约的一次性硬切换。"""
from __future__ import annotations
import copy
from alembic import op
import sqlalchemy as sa
revision = 'iw1a2b3c4d5e'
down_revision = 'if1b2c3d4e5i'
branch_labels = None
depends_on = None
def _i(): return sa.inspect(op.get_bind())
def _tables(): return set(_i().get_table_names())
def _cols(t): return {x['name'] for x in _i().get_columns(t)}
def _drop_uq(t, n):
if n in {x.get('name') for x in _i().get_unique_constraints(t)}: op.drop_constraint(n, t, type_='unique')
def _drop_idx(t, n):
if n in {x.get('name') for x in _i().get_indexes(t)}: op.drop_index(n, table_name=t)
def _drop_column_with_dependencies(t, column):
"""按实际库结构先解除列级外键/索引,再删除已退役的 OT 投影列。"""
if column not in _cols(t):
return
with op.batch_alter_table(t) as b:
for fk in _i().get_foreign_keys(t):
if column in (fk.get('constrained_columns') or []) and fk.get('name'):
b.drop_constraint(fk['name'], type_='foreignkey')
for index in _i().get_indexes(t):
if column in (index.get('column_names') or []) and index.get('name'):
b.drop_index(index['name'])
b.drop_column(column)
def _clean_task_step_payloads():
"""删除 OT JSON 中已迁移的业务事实,仅保留 UI/解析摘要。"""
if 'shipping_order_tasks' not in _tables() or 'step_payload_json' not in _cols('shipping_order_tasks'):
return
table = sa.table('shipping_order_tasks', sa.column('id', sa.Integer()), sa.column('step_payload_json', sa.JSON()))
removed = {
'field_conflicts', 'process_field_gate', 'inventory_rpa_skipped',
'last_inventory_rpa_runtime', 'line_inventory_candidates',
'candidate_inventory_prep', 'line_inventory_resolutions',
'forced_match_source_code', 'current_match_projection',
'resolved_ok_source_codes', 'multi_source_excel_block',
'inventory_source_resolution', 'rpa_inventory_source', 'export_meta',
'invalidated_from_stage', 'last_conflict_resolve_idempotency_key',
'last_notice_edit_idempotency',
}
bind = op.get_bind()
for row in bind.execute(sa.select(table.c.id, table.c.step_payload_json)).all():
payload = row.step_payload_json
if not isinstance(payload, dict):
continue
cleaned = {key: value for key, value in payload.items() if key not in removed}
if cleaned != payload:
bind.execute(table.update().where(table.c.id == row.id).values(step_payload_json=cleaned or None))
_OT_COLUMNS = {
'order_data_version': sa.Column('order_data_version', sa.Integer(), nullable=False, server_default='1'),
'current_order_extraction_id': sa.Column('current_order_extraction_id', sa.Integer(), nullable=True),
'order_snapshot_id': sa.Column('order_snapshot_id', sa.Integer(), nullable=True),
'active_inventory_candidate_set_id': sa.Column('active_inventory_candidate_set_id', sa.Integer(), nullable=True),
'step_payload_json': sa.Column('step_payload_json', sa.JSON(), nullable=True),
'active_process_execution_id': sa.Column('active_process_execution_id', sa.Integer(), nullable=True),
}
_TASK_FKS = {
'shipping_order_snapshots': ('task_id', 'shipping_order_tasks'), 'shipping_order_review_events': ('task_id', 'shipping_order_tasks'),
'shipping_order_review_confirmed_revisions': ('task_id', 'shipping_order_tasks'), 'shipping_order_review_wave_lines': ('task_id', 'shipping_order_tasks'),
'shipping_order_review_wave_idempotency': ('task_id', 'shipping_order_tasks'), 'shipping_order_review_line_decisions': ('task_id', 'shipping_order_tasks'),
'shipping_inventory_candidate_sets': ('task_id', 'shipping_order_tasks'), 'shipping_process_executions': ('task_id', 'shipping_order_tasks'),
'shipping_process_gates': ('task_id', 'shipping_order_tasks'), 'shipping_inventory_preparation_attempts': ('task_id', 'shipping_order_tasks'),
'shipping_notice_reservations': ('task_id', 'shipping_order_tasks'), 'shipping_notice_inventory_verifications': ('task_id', 'shipping_order_tasks'),
'shipping_task_inventory_links': ('task_id', 'shipping_order_tasks'), 'shipping_temporary_inventory_sessions': ('task_id', 'shipping_order_tasks'),
'shipping_task_events': ('task_id', 'shipping_order_tasks'),
'shipping_notice_line_inventory_matches': ('task_id', 'shipping_order_tasks'), 'shipping_task_field_conflicts': ('task_id', 'shipping_order_tasks'),
'shipping_order_extractions': ('task_id', 'shipping_order_tasks'), 'shipping_order_intakes': ('consumed_task_id', 'shipping_order_tasks'),
'shipping_order_candidates': ('consumed_task_id', 'shipping_order_tasks'),
}
def _repoint(t, c, target):
if t not in _tables(): return
fks = [x for x in _i().get_foreign_keys(t) if c in (x.get('constrained_columns') or [])]
with op.batch_alter_table(t) as b:
for fk in fks:
if fk.get('name'): b.drop_constraint(fk['name'], type_='foreignkey')
b.create_foreign_key(f'fk_{t}_{c}_order_task', target, [c], ['id'], ondelete='CASCADE')
def upgrade() -> None:
tables = _tables()
_clean_task_step_payloads()
# Notice 的库存确认人/时间是旧的单头运行投影;正式确认事实由
# PreparationAttempt/SourceAttempt 与 GateAttempt 承载。
if 'shipping_notices' in tables:
for n in (
'inventory_connector_type',
'active_inventory_candidate_set_id',
'active_process_execution_id',
'inventory_snapshot_id',
'inventory_source_confirmed_by',
'inventory_source_confirmed_at',
'inventory_lines_json',
'match_status',
'shortage_json',
'line_results_json',
'inventory_source_code',
'inventory_source_status',
'inventory_source_method',
'inventory_source_config_version',
'inventory_routing_fingerprint',
'inventory_rpa_consumed_run_no',
):
_drop_column_with_dependencies('shipping_notices', n)
if 'shipping_order_tasks' in tables:
existing = _cols('shipping_order_tasks')
with op.batch_alter_table('shipping_order_tasks') as b:
for n, c in _OT_COLUMNS.items():
if n not in existing: b.add_column(c)
for n in (
'inventory_source_code', 'inventory_connector_type', 'inventory_source_status',
'inventory_source_method', 'inventory_source_config_version',
'inventory_routing_fingerprint', 'inventory_snapshot_id',
):
if n in existing: b.drop_column(n)
for n in (
'customer_id', 'customer_resolution_status', 'customer_resolution_method',
'customer_identity_fingerprint', 'customer_confirmed_by', 'customer_confirmed_at',
'pending_human_reason',
):
_drop_column_with_dependencies('shipping_order_tasks', n)
# 已部署环境可能在本迁移到达 head 后仍残留历史 OT 投影列(例如旧分支
# 曾先执行过迁移、再补充模型字段)。这里再次按实际 schema 幂等清理,
# 确保“模型无字段、数据库也无字段”最终一致,而不依赖迁移执行时序。
for n in (
'customer_name_snapshot', 'customer_short_code_snapshot',
'destination_code', 'destination_city', 'destination_country', 'warehouse_hint',
'inventory_source_code', 'inventory_connector_type', 'inventory_source_status',
'inventory_source_method', 'inventory_source_config_version',
'inventory_routing_fingerprint', 'inventory_snapshot_id',
'inventory_lines_json', 'match_status', 'shortage_json', 'line_results_json',
):
_drop_column_with_dependencies('shipping_order_tasks', n)
cols = _cols('shipping_order_tasks')
if 'shipping_notice_id' in cols:
fks = [x for x in _i().get_foreign_keys('shipping_order_tasks') if 'shipping_notice_id' in (x.get('constrained_columns') or [])]
with op.batch_alter_table('shipping_order_tasks') as b:
for fk in fks:
if fk.get('name'): b.drop_constraint(fk['name'], type_='foreignkey')
b.drop_column('shipping_notice_id')
# 订单/通知项次及身份硬切换(旧身份数据不回填)。
if 'shipping_order_lines' in tables:
c = _cols('shipping_order_lines')
with op.batch_alter_table('shipping_order_lines') as b:
if 'line_key' in c: b.drop_column('line_key')
if 'draft_line_id' not in c: b.add_column(sa.Column('draft_line_id', sa.String(128), nullable=True))
if 'line_no' not in c: b.add_column(sa.Column('line_no', sa.Integer(), nullable=True))
op.execute(sa.text('''WITH n AS (SELECT id, ROW_NUMBER() OVER (PARTITION BY extraction_id ORDER BY position,id) x FROM shipping_order_lines) UPDATE shipping_order_lines l SET line_no=n.x FROM n WHERE l.id=n.id'''))
with op.batch_alter_table('shipping_order_lines') as b:
b.alter_column('line_no', nullable=False, existing_type=sa.Integer())
if 'uq_shipping_order_lines_line_no' not in {x.get('name') for x in _i().get_unique_constraints('shipping_order_lines')}: b.create_unique_constraint('uq_shipping_order_lines_line_no', ['extraction_id','line_no'])
for t in ('shipping_order_review_suggestions','shipping_order_review_line_decisions'):
if t in tables:
c=_cols(t)
with op.batch_alter_table(t) as b:
if 'line_key' in c and 'draft_line_id' not in c: b.alter_column('line_key', new_column_name='draft_line_id')
elif 'line_key' in c: b.drop_column('line_key')
if 'shipping_order_snapshot_lines' in tables:
with op.batch_alter_table('shipping_order_snapshot_lines') as b:
if 'line_no' in _cols('shipping_order_snapshot_lines'): b.alter_column('line_no', existing_type=sa.String(64), type_=sa.Integer(), postgresql_using='line_no::integer')
op.execute(sa.text('''WITH n AS (SELECT id, ROW_NUMBER() OVER (PARTITION BY snapshot_id ORDER BY position,id) x FROM shipping_order_snapshot_lines) UPDATE shipping_order_snapshot_lines l SET line_no=n.x FROM n WHERE l.id=n.id'''))
if 'shipping_notice_lines' in tables:
c=_cols('shipping_notice_lines')
with op.batch_alter_table('shipping_notice_lines') as b:
if 'line_key' in c: b.drop_column('line_key')
if 'line_no' not in c: b.add_column(sa.Column('line_no', sa.Integer(), nullable=True))
if 'inventory_source_code' not in c: b.add_column(sa.Column('inventory_source_code', sa.String(64), nullable=True))
if 'inventory_file_id' not in c: b.add_column(sa.Column('inventory_file_id', sa.Integer(), nullable=True))
if 'inventory_warehouse_id' not in c: b.add_column(sa.Column('inventory_warehouse_id', sa.String(64), nullable=True))
op.execute(sa.text('''WITH n AS (SELECT id, ROW_NUMBER() OVER (PARTITION BY notice_id ORDER BY position,id) x FROM shipping_notice_lines) UPDATE shipping_notice_lines l SET line_no=n.x FROM n WHERE l.id=n.id'''))
with op.batch_alter_table('shipping_notice_lines') as b:
b.alter_column('line_no', nullable=False, existing_type=sa.Integer())
if 'uq_shipping_notice_lines_line_no' not in {x.get('name') for x in _i().get_unique_constraints('shipping_notice_lines')}: b.create_unique_constraint('uq_shipping_notice_lines_line_no', ['notice_id','line_no'])
if 'fk_shipping_notice_lines_inventory_file' not in {x.get('name') for x in _i().get_foreign_keys('shipping_notice_lines')}:
b.create_foreign_key('fk_shipping_notice_lines_inventory_file', 'shipping_inventory_files', ['inventory_file_id'], ['id'], ondelete='SET NULL')
existing_indexes = {x.get('name') for x in _i().get_indexes('shipping_notice_lines')}
if 'ix_shipping_notice_lines_inventory_source_code' not in existing_indexes:
b.create_index('ix_shipping_notice_lines_inventory_source_code', ['inventory_source_code'])
if 'ix_shipping_notice_lines_inventory_file_id' not in existing_indexes:
b.create_index('ix_shipping_notice_lines_inventory_file_id', ['inventory_file_id'])
if 'ix_shipping_notice_lines_inventory_warehouse_id' not in existing_indexes:
b.create_index('ix_shipping_notice_lines_inventory_warehouse_id', ['inventory_warehouse_id'])
if 'shipping_notices' in tables and 'inventory_warehouse_id' in _cols('shipping_notices'):
with op.batch_alter_table('shipping_notices') as b:
b.drop_column('inventory_warehouse_id')
if 'shipping_order_review_wave_lines' in tables:
c=_cols('shipping_order_review_wave_lines'); _drop_uq('shipping_order_review_wave_lines','uq_shipping_review_wave_lines_case_line'); op.execute(sa.text('DELETE FROM shipping_order_review_wave_lines'))
existing_fks = {x.get('name') for x in _i().get_foreign_keys('shipping_order_review_wave_lines')}
has_snapshot_line_fk = any('snapshot_line_id' in (x.get('constrained_columns') or []) for x in _i().get_foreign_keys('shipping_order_review_wave_lines'))
existing_uqs = {x.get('name') for x in _i().get_unique_constraints('shipping_order_review_wave_lines')}
with op.batch_alter_table('shipping_order_review_wave_lines') as b:
if 'line_key' in c: b.drop_column('line_key')
if 'snapshot_line_id' not in c: b.add_column(sa.Column('snapshot_line_id', sa.Integer(), nullable=False))
if not has_snapshot_line_fk and 'fk_shipping_review_wave_lines_snapshot_line' not in existing_fks:
b.create_foreign_key('fk_shipping_review_wave_lines_snapshot_line','shipping_order_snapshot_lines',['snapshot_line_id'],['id'],ondelete='CASCADE')
if 'uq_shipping_review_wave_lines_case_snapshot_line' not in existing_uqs:
b.create_unique_constraint('uq_shipping_review_wave_lines_case_snapshot_line',['review_case_id','snapshot_line_id'])
if 'shipping_order_review_wave_idempotency' in tables:
c=_cols('shipping_order_review_wave_idempotency')
with op.batch_alter_table('shipping_order_review_wave_idempotency') as b:
if 'line_keys_json' in c and 'snapshot_line_ids_json' not in c: b.alter_column('line_keys_json',new_column_name='snapshot_line_ids_json')
if 'line_keys_hash' in c and 'snapshot_line_ids_hash' not in c: b.alter_column('line_keys_hash',new_column_name='snapshot_line_ids_hash')
if 'shipping_notice_line_inventory_matches' in tables:
c=_cols('shipping_notice_line_inventory_matches'); op.execute(sa.text('DELETE FROM shipping_notice_line_inventory_matches')); _drop_idx('shipping_notice_line_inventory_matches','uq_shipping_notice_line_inv_match_current'); _drop_uq('shipping_notice_line_inventory_matches','uq_shipping_notice_line_inv_match_task_line_snap')
existing_fks = {x.get('name') for x in _i().get_foreign_keys('shipping_notice_line_inventory_matches')}
has_snapshot_line_fk = any('snapshot_line_id' in (x.get('constrained_columns') or []) for x in _i().get_foreign_keys('shipping_notice_line_inventory_matches'))
existing_uqs = {x.get('name') for x in _i().get_unique_constraints('shipping_notice_line_inventory_matches')}
with op.batch_alter_table('shipping_notice_line_inventory_matches') as b:
if 'line_key' in c: b.drop_column('line_key')
if 'line_no' not in c: b.add_column(sa.Column('line_no', sa.Integer(), nullable=True))
if 'snapshot_line_id' not in c: b.add_column(sa.Column('snapshot_line_id',sa.Integer(),nullable=False))
else: b.alter_column('snapshot_line_id',nullable=False,existing_type=sa.Integer())
if not has_snapshot_line_fk and 'fk_shipping_notice_line_inventory_matches_snapshot_line' not in existing_fks:
b.create_foreign_key('fk_shipping_notice_line_inventory_matches_snapshot_line','shipping_order_snapshot_lines',['snapshot_line_id'],['id'],ondelete='CASCADE')
if 'uq_shipping_notice_line_inv_match_task_snapshot_line_snap' not in existing_uqs:
b.create_unique_constraint('uq_shipping_notice_line_inv_match_task_snapshot_line_snap',['task_id','snapshot_line_id','inventory_snapshot_id'])
if 'uq_shipping_notice_line_inv_match_current' not in {x.get('name') for x in _i().get_indexes('shipping_notice_line_inventory_matches')}:
b.create_index('uq_shipping_notice_line_inv_match_current',['task_id','snapshot_line_id'],unique=True,postgresql_where=sa.text('is_current IS TRUE'))
op.execute(sa.text("""
UPDATE shipping_notice_line_inventory_matches m
SET line_no = COALESCE(sl.line_no, m.line_index + 1, 1)
FROM shipping_order_snapshot_lines sl
WHERE m.snapshot_line_id = sl.id
AND m.line_no IS NULL
"""))
with op.batch_alter_table('shipping_notice_line_inventory_matches') as b:
b.alter_column('line_no', nullable=False, existing_type=sa.Integer(), server_default='1')
# shipping_task_events.task_id 记录正式 ShippingOrderTask.id;部分旧环境
# 的外键错误指向 shipping_notices,导致确认建单写审计事件时触发 FK 违反。
if 'shipping_task_events' in tables and 'shipping_order_tasks' in tables:
event_fk = next(
(
fk for fk in _i().get_foreign_keys('shipping_task_events')
if tuple(fk.get('constrained_columns') or []) == ('task_id',)
),
None,
)
if not event_fk or event_fk.get('referred_table') != 'shipping_order_tasks':
old_fk_name = str(event_fk.get('name') or 'shipping_task_events_task_id_fkey') if event_fk else None
if old_fk_name:
with op.batch_alter_table('shipping_task_events') as b:
b.drop_constraint(old_fk_name, type_='foreignkey')
invalid_count = op.get_bind().execute(sa.text(
"""
SELECT COUNT(*)
FROM shipping_task_events e
WHERE NOT EXISTS (
SELECT 1 FROM shipping_order_tasks t WHERE t.id = e.task_id
)
"""
)).scalar_one()
if int(invalid_count or 0):
raise RuntimeError(
'shipping_task_events contains rows whose task_id is not a '
'shipping_order_tasks.id; repair those audit rows before migration'
)
with op.batch_alter_table('shipping_task_events') as b:
b.create_foreign_key(
'fk_shipping_task_events_task_id_order_task',
'shipping_order_tasks', ['task_id'], ['id'], ondelete='CASCADE',
)
bind=op.get_bind()
if 'shipping_excel_templates' in tables:
t=sa.table('shipping_excel_templates',sa.column('id',sa.Integer()),sa.column('definition_json',sa.JSON()))
def rw(v):
if isinstance(v,dict):
r={k:rw(x) for k,x in v.items()}
if r.get('source_kind') == 'system_fact' and r.get('source_key') == 'export_sequence':
r['source_key'] = 'notice_line_no'
return r
return [rw(x) for x in v] if isinstance(v,list) else v
for row in bind.execute(sa.select(t.c.id,t.c.definition_json)).all():
v=rw(row.definition_json)
if v!=row.definition_json: bind.execute(t.update().where(t.c.id==row.id).values(definition_json=v))
if 'shipping_order_schema_versions' in tables:
t=sa.table('shipping_order_schema_versions',sa.column('id',sa.Integer()),sa.column('definition_json',sa.JSON()))
for row in bind.execute(sa.select(t.c.id,t.c.definition_json)).all():
v=copy.deepcopy(row.definition_json)
if isinstance(v,dict):
# line_no 是系统项次标准字段,必须保留;这里只移除已废弃的派生规则配置。
v.pop('derivation_rules',None); v.pop('derivation_rules_checksum',None)
if v!=row.definition_json: bind.execute(t.update().where(t.c.id==row.id).values(definition_json=v))
if 'shipping_order_fields' in tables:
# line_no 已硬切换为系统生成整数项次;纠偏旧资产种子遗留的 string 类型。
op.execute(sa.text("""
UPDATE shipping_order_fields
SET value_type = 'integer', updated_at = CURRENT_TIMESTAMP
WHERE field_code = 'line_no'
AND scope = 'line'
AND asset_kind = 'system_standard'
"""))
if 'shipping_order_tasks' in tables:
with op.batch_alter_table('shipping_order_tasks') as b:
for n,c in _OT_COLUMNS.items():
pass
if 'lifecycle_status' not in _cols('shipping_order_tasks'): b.add_column(sa.Column('lifecycle_status',sa.String(16),nullable=False,server_default='active'))
for n, typ in (('current_step', sa.String(64)), ('review_status', sa.String(32)), ('pending_human_reason', sa.String(64))):
if n not in _cols('shipping_order_tasks'): b.add_column(sa.Column(n, typ, nullable=True))
for n in ('deleted_at','voided_at','archived_at'):
if n not in _cols('shipping_order_tasks'): b.add_column(sa.Column(n,sa.DateTime(),nullable=True))
for n in ('deletion_reason','void_reason'):
if n not in _cols('shipping_order_tasks'): b.add_column(sa.Column(n,sa.Text(),nullable=True))
for n in ('deleted_by_id','voided_by_id','archived_by_id'):
if n not in _cols('shipping_order_tasks'): b.add_column(sa.Column(n,sa.Integer(),nullable=True))
if 'lifecycle_status' not in _cols('shipping_order_tasks'):
b.create_check_constraint('ck_shipping_order_tasks_lifecycle_status', "lifecycle_status IN ('active', 'voided', 'archived')")
existing_fks = {x.get('name') for x in _i().get_foreign_keys('shipping_order_tasks')}
for name, column in (
('fk_shipping_order_tasks_deleted_by', 'deleted_by_id'),
('fk_shipping_order_tasks_voided_by', 'voided_by_id'),
('fk_shipping_order_tasks_archived_by', 'archived_by_id'),
):
if name not in existing_fks:
b.create_foreign_key(name, 'users', [column], ['id'])
obsolete_cols = {
'customer_name_snapshot', 'customer_short_code_snapshot',
'destination_code', 'destination_city', 'destination_country', 'warehouse_hint',
'inventory_lines_json', 'match_status', 'shortage_json', 'line_results_json',
} & _cols('shipping_order_tasks')
if obsolete_cols:
with op.batch_alter_table('shipping_order_tasks') as b:
for column in sorted(obsolete_cols):
b.drop_column(column)
if 'shipping_notices' in tables:
_drop_idx('shipping_notices', 'ix_shipping_notices_current_step')
_drop_idx('shipping_notices', 'ix_shipping_notices_upload_status')
_drop_idx('shipping_notices', 'ix_shipping_notices_order_snapshot_id')
_drop_idx('shipping_notices', 'ix_shipping_tasks_order_snapshot_id')
obsolete_notice_cols = {
'export_file_path', 'export_file_name', 'export_version', 'freight_ref_no',
'upload_status', 'upload_mode', 'upload_attempt', 'idempotency_key',
'upload_started_at', 'upload_finished_at', 'upload_error_code',
'upload_error_message', 'upload_receipt_json',
'current_step', 'review_status', 'step_payload_json', 'pending_human_reason', 'error_message',
'customer_id', 'customer_name_snapshot', 'customer_short_code_snapshot',
'customer_resolution_status', 'customer_resolution_method', 'customer_identity_fingerprint',
'customer_confirmed_by', 'customer_confirmed_at',
'destination_code', 'destination_city', 'destination_country', 'warehouse_hint',
'parse_confidence', 'order_data_version', 'current_order_extraction_id',
'order_snapshot_id', 'raw_content', 'source_file_name', 'source_file_type', 'source_content_hash',
'business_fingerprint', 'fingerprint_version', 'content_fingerprint', 'content_fingerprint_version',
'batch_index', 'batch_total',
} & _cols('shipping_notices')
for column in sorted(obsolete_notice_cols):
_drop_column_with_dependencies('shipping_notices', column)
if 'shipping_order_tasks' in tables:
_drop_idx('shipping_order_tasks', 'ix_shipping_tasks_order_snapshot_id')
_drop_idx('shipping_order_tasks', 'ix_shipping_order_tasks_order_snapshot_id')
_drop_uq('shipping_order_tasks', 'uq_shipping_order_tasks_order_snapshot_id')
# 统一所有履约事实的 task_id 外键目标;旧通知表中的孤儿数据不做猜测回填。
for table, (column, target) in _TASK_FKS.items():
if table not in _tables():
continue
# 不同历史表的任务关联列名并不统一;列不存在时跳过该映射,避免生成无效 SQL。
if column not in _cols(table):
continue
# 已被发货通知引用的快照不能作为孤儿删除,否则会触发外键冲突。
keep_referenced = (
" AND NOT EXISTS (SELECT 1 FROM shipping_notices sn WHERE sn.order_task_id = t.task_id)"
if table == 'shipping_order_snapshots' and 'shipping_notices' in _tables()
else ''
)
op.execute(sa.text(
f'DELETE FROM {table} t WHERE t.{column} IS NOT NULL AND NOT EXISTS '
f'(SELECT 1 FROM shipping_order_tasks ot WHERE ot.id = t.{column})'
f'{keep_referenced}'
))
_repoint(table, column, target)
if 'shipping_order_review_cases' in _tables():
_repoint('shipping_order_review_cases', 'confirmed_task_id', 'shipping_order_tasks')
def downgrade() -> None:
raise RuntimeError('order line identity contract is intentionally irreversible')
@@ -0,0 +1,43 @@
"""split integration connector columns
Revision ID: ix1a2b3c4d5e
Revises: iy1a2b3c4d5e
Create Date: 2026-09-01 09:00:00.000000
用途:把集成连接器"真正强类型的关键字段"从 JSON 拆成独立列,JSON 保留作兜底。
ClientInstance:endpoint(连接地址:REST=接口地址,SOAP=WSDL 地址)/ timeout_seconds;
InterfaceDefinition:http_method / request_path;
Binding:context_source_code。
依赖:ic1a2b3c4d5f 建表;不新建表,仅加列。
逻辑:SOAP 只需 WSDL(其内已含服务端点),故合一为 endpoint 字段;列可为空(存量数据
回填后由应用层拼回 JSON);不删 JSON,保证兼容层运行时零改动。
"""
from alembic import op
import sqlalchemy as sa
revision = 'ix1a2b3c4d5e'
down_revision = 'iy1a2b3c4d5e'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""在三张连接器表上新增关键字段列(nullable:存量数据回填后走兼容层)。"""
op.add_column('integration_client_instances', sa.Column('endpoint', sa.String(length=512), nullable=True))
op.add_column('integration_client_instances', sa.Column('timeout_seconds', sa.Integer(), nullable=True))
op.add_column('integration_interface_definitions', sa.Column('http_method', sa.String(length=16), nullable=True))
op.add_column('integration_interface_definitions', sa.Column('request_path', sa.String(length=512), nullable=True))
op.add_column('integration_bindings', sa.Column('context_source_code', sa.String(length=64), nullable=True))
def downgrade() -> None:
"""回滚:删除新增列(JSON 兜底仍在,数据不丢)。"""
op.drop_column('integration_bindings', 'context_source_code')
op.drop_column('integration_interface_definitions', 'request_path')
op.drop_column('integration_interface_definitions', 'http_method')
op.drop_column('integration_client_instances', 'timeout_seconds')
op.drop_column('integration_client_instances', 'endpoint')
@@ -0,0 +1,125 @@
"""收敛客户确认主链并删除已退役的订单角色匹配表。"""
from __future__ import annotations
from alembic import op
import sqlalchemy as sa
revision = 'iy1a2b3c4d5e'
down_revision = 'iw1a2b3c4d5e'
branch_labels = None
depends_on = None
def _columns(table_name: str) -> set[str]:
"""返回表当前列名,支持工作区迁移的幂等升级。"""
return {item['name'] for item in sa.inspect(op.get_bind()).get_columns(table_name)}
def upgrade() -> None:
"""补齐当前主链字段后删除已无生产读写方的旧角色匹配表。"""
# [STEP 1] 合并原 35d4 任务进度补列。
with op.batch_alter_table('shipping_order_tasks') as batch:
columns = _columns('shipping_order_tasks')
if 'current_step' not in columns:
batch.add_column(sa.Column('current_step', sa.String(length=64), nullable=True))
if 'review_status' not in columns:
batch.add_column(sa.Column('review_status', sa.String(length=32), nullable=True))
# [STEP 2] 合并原 ix1 客户 Resolution 确认字段升级。
if 'shipping_customer_shadow_resolutions' in set(sa.inspect(op.get_bind()).get_table_names()):
columns = _columns('shipping_customer_shadow_resolutions')
with op.batch_alter_table('shipping_customer_shadow_resolutions') as batch:
constraints = {
item.get('name')
for item in sa.inspect(op.get_bind()).get_check_constraints('shipping_customer_shadow_resolutions')
}
if 'ck_shipping_customer_shadow_status' in constraints:
batch.drop_constraint('ck_shipping_customer_shadow_status', type_='check')
batch.create_check_constraint(
'ck_shipping_customer_shadow_status',
"status IN ('unique_candidate', 'ambiguous', 'unmatched', 'failed', 'confirmed')",
)
if 'confirmed_customer_id' not in columns:
batch.add_column(sa.Column('confirmed_customer_id', sa.Integer(), nullable=True))
batch.create_foreign_key(
'fk_shipping_customer_resolution_confirmed_customer',
'shipping_customers', ['confirmed_customer_id'], ['id'],
)
if 'confirmation_method' not in columns:
batch.add_column(sa.Column('confirmation_method', sa.String(length=32), nullable=True))
if 'confirmation_reason' not in columns:
batch.add_column(sa.Column('confirmation_reason', sa.String(length=500), nullable=True))
if 'confirmed_by_id' not in columns:
batch.add_column(sa.Column('confirmed_by_id', sa.Integer(), nullable=True))
batch.create_foreign_key('fk_shipping_customer_resolution_confirmed_by', 'users', ['confirmed_by_id'], ['id'])
if 'confirmed_at' not in columns:
batch.add_column(sa.Column('confirmed_at', sa.DateTime(), nullable=True))
# [STEP 3] 旧表物理删除。
bind = op.get_bind()
if 'shipping_order_customer_matches' in set(sa.inspect(bind).get_table_names()):
op.drop_table('shipping_order_customer_matches')
def downgrade() -> None:
"""恢复旧表空结构并回退本迁移合并的新增字段;不恢复已删除数据。"""
op.create_table(
'shipping_order_customer_matches',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('extraction_id', sa.Integer(), nullable=False),
sa.Column('role', sa.String(length=16), nullable=False),
sa.Column('raw_name', sa.Text(), nullable=True),
sa.Column('normalized_name', sa.String(length=500), nullable=True),
sa.Column('source_system', sa.String(length=64), nullable=True),
sa.Column('external_code', sa.String(length=128), nullable=True),
sa.Column('identity_fingerprint', sa.String(length=64), nullable=True),
sa.Column('identity_rule_version', sa.String(length=32), nullable=True),
sa.Column('identity_components_json', sa.JSON(), nullable=False),
sa.Column('status', sa.String(length=32), nullable=False),
sa.Column('customer_id', sa.Integer(), nullable=True),
sa.Column('site_id', sa.Integer(), nullable=True),
sa.Column('customer_name_snapshot', sa.String(length=200), nullable=True),
sa.Column('customer_short_code_snapshot', sa.String(length=6), nullable=True),
sa.Column('candidates_json', sa.JSON(), nullable=False),
sa.Column('resolution_method', sa.String(length=32), nullable=True),
sa.Column('confirmation_reason', sa.Text(), nullable=True),
sa.Column('confirmed_by_id', sa.Integer(), nullable=True),
sa.Column('confirmed_at', sa.DateTime(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.CheckConstraint("role IN ('bill_to', 'ship_to')", name='ck_shipping_order_customer_matches_role'),
sa.CheckConstraint(
"status IN ('unmatched', 'unique_candidate', 'ambiguous', 'confirmed')",
name='ck_shipping_order_customer_matches_status',
),
sa.ForeignKeyConstraint(['customer_id'], ['shipping_customers.id']),
sa.ForeignKeyConstraint(['confirmed_by_id'], ['users.id']),
sa.ForeignKeyConstraint(['extraction_id'], ['shipping_order_extractions.id'], ondelete='CASCADE'),
sa.ForeignKeyConstraint(['site_id'], ['shipping_customer_sites.id']),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('extraction_id', 'role', name='uq_shipping_order_customer_matches_extraction_role'),
)
op.create_index('ix_shipping_order_customer_matches_extraction_id', 'shipping_order_customer_matches', ['extraction_id'])
op.create_index('ix_shipping_order_customer_matches_customer_role', 'shipping_order_customer_matches', ['customer_id', 'role'])
op.create_index('ix_shipping_order_customer_matches_identity_fingerprint', 'shipping_order_customer_matches', ['identity_fingerprint'])
if 'shipping_customer_shadow_resolutions' in set(sa.inspect(op.get_bind()).get_table_names()):
with op.batch_alter_table('shipping_customer_shadow_resolutions') as batch:
for name in (
'fk_shipping_customer_resolution_confirmed_by',
'fk_shipping_customer_resolution_confirmed_customer',
):
try:
batch.drop_constraint(name, type_='foreignkey')
except Exception:
pass
columns = _columns('shipping_customer_shadow_resolutions')
for name in ('confirmed_at', 'confirmed_by_id', 'confirmation_reason', 'confirmation_method', 'confirmed_customer_id'):
if name in columns:
batch.drop_column(name)
with op.batch_alter_table('shipping_order_tasks') as batch:
columns = _columns('shipping_order_tasks')
for name in ('review_status', 'current_step'):
if name in columns:
batch.drop_column(name)