feat(integration-connector): 新增集成连接器管理后台,支持关键字段拆列配置
This commit is contained in:
1 parent
bf30cddc4a
commit
1269e04116
28 files changed
+2909
-155
No files matched your search
@@ -43,6 +43,7 @@ def _serialize_client(client) -> dict:
|
||||
return {
|
||||
'id': client.id, 'code': client.code, 'name': client.name,
|
||||
'connector_type': client.connector_type, 'environment': client.environment,
|
||||
'endpoint': client.endpoint, 'timeout_seconds': client.timeout_seconds,
|
||||
'config_json': client.config_json or {}, 'credential_ref_code': client.credential_ref_code,
|
||||
'enabled': client.enabled,
|
||||
}
|
||||
@@ -52,6 +53,7 @@ def _serialize_interface(iface) -> dict:
|
||||
return {
|
||||
'id': iface.id, 'code': iface.code, 'name': iface.name,
|
||||
'client_instance_code': iface.client_instance_code, 'connector_type': iface.connector_type,
|
||||
'http_method': iface.http_method, 'request_path': iface.request_path,
|
||||
'request_spec_json': iface.request_spec_json or {}, 'input_schema_json': iface.input_schema_json or {},
|
||||
'response_mapping_json': iface.response_mapping_json or {}, 'output_schema_json': iface.output_schema_json or {},
|
||||
'version': iface.version, 'status': iface.status, 'enabled': iface.enabled,
|
||||
@@ -62,6 +64,7 @@ def _serialize_binding(binding) -> dict:
|
||||
return {
|
||||
'id': binding.id, 'capability': binding.capability,
|
||||
'context_selector_json': binding.context_selector_json or {},
|
||||
'context_source_code': binding.context_source_code,
|
||||
'client_instance_code': binding.client_instance_code,
|
||||
'interface_definition_code': binding.interface_definition_code,
|
||||
'mapping_version': binding.mapping_version, 'priority': binding.priority,
|
||||
@@ -146,6 +149,8 @@ def create_client_instance():
|
||||
client = IntegrationClientInstance(
|
||||
code=str(body['code']).strip(), name=str(body['name']).strip(),
|
||||
connector_type=connector_type, environment=str(body.get('environment') or 'prod').strip(),
|
||||
endpoint=(str(body.get('endpoint') or '').strip() or None),
|
||||
timeout_seconds=(int(body['timeout_seconds']) if body.get('timeout_seconds') is not None else None),
|
||||
config_json=body.get('config_json') or {},
|
||||
credential_ref_code=body.get('credential_ref_code'),
|
||||
enabled=bool(body.get('enabled', True)),
|
||||
@@ -177,6 +182,39 @@ def delete_client_instance(code):
|
||||
return ok({'deleted': True})
|
||||
|
||||
|
||||
@integration_connector_bp.route('/client-instances/<code>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_client_instance(code):
|
||||
"""更新客户端实例(code 不变;可改名称/连接配置/凭据引用/启停)。"""
|
||||
client = IntegrationClientInstance.query.filter_by(code=code).first()
|
||||
if client is None:
|
||||
raise NotFoundError('client instance not found', code='INTEGRATION.CLIENT_INSTANCE_NOT_FOUND')
|
||||
body = request.get_json(silent=True) or {}
|
||||
connector_type = str(body.get('connector_type') or client.connector_type)
|
||||
if connector_type not in VALID_CONNECTOR_TYPES:
|
||||
raise ValidationError('invalid connector_type', details={'allowed': list(VALID_CONNECTOR_TYPES)})
|
||||
if body.get('name') is not None:
|
||||
_require(body.get('name'), 'name')
|
||||
client.name = str(body['name']).strip()
|
||||
if body.get('connector_type') is not None:
|
||||
client.connector_type = connector_type
|
||||
if body.get('environment') is not None:
|
||||
client.environment = str(body['environment']).strip()
|
||||
if 'endpoint' in body:
|
||||
client.endpoint = str(body.get('endpoint') or '').strip() or None
|
||||
if 'timeout_seconds' in body:
|
||||
client.timeout_seconds = int(body['timeout_seconds']) if body.get('timeout_seconds') is not None else None
|
||||
if 'config_json' in body:
|
||||
client.config_json = body.get('config_json') or {}
|
||||
if 'credential_ref_code' in body:
|
||||
client.credential_ref_code = body.get('credential_ref_code')
|
||||
if 'enabled' in body:
|
||||
client.enabled = bool(body.get('enabled', True))
|
||||
from app import db
|
||||
db.session.commit()
|
||||
return ok(_serialize_client(client))
|
||||
|
||||
|
||||
# ---- 接口定义 ----
|
||||
|
||||
@integration_connector_bp.route('/interface-definitions', methods=['GET'])
|
||||
@@ -202,6 +240,8 @@ def create_interface_definition():
|
||||
iface = IntegrationInterfaceDefinition(
|
||||
code=code, name=str(body.get('name') or code).strip(),
|
||||
client_instance_code=body['client_instance_code'], connector_type=connector_type,
|
||||
http_method=(str(body.get('http_method') or '').strip().upper() or None),
|
||||
request_path=(str(body.get('request_path') or '').strip() or None),
|
||||
request_spec_json=body.get('request_spec_json') or {},
|
||||
input_schema_json=body.get('input_schema_json') or {},
|
||||
response_mapping_json=body.get('response_mapping_json') or {},
|
||||
@@ -215,6 +255,46 @@ def create_interface_definition():
|
||||
return ok(_serialize_interface(iface), status=201)
|
||||
|
||||
|
||||
@integration_connector_bp.route('/interface-definitions/<code>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_interface_definition(code):
|
||||
"""更新接口定义(code 不变;可改模板/入参/回传/出参 Schema、状态、启停)。"""
|
||||
iface = IntegrationInterfaceDefinition.query.filter_by(code=code).first()
|
||||
if iface is None:
|
||||
raise NotFoundError('interface definition not found', code='INTEGRATION.INTERFACE_NOT_FOUND')
|
||||
body = request.get_json(silent=True) or {}
|
||||
if body.get('name') is not None:
|
||||
_require(body.get('name'), 'name')
|
||||
iface.name = str(body['name']).strip()
|
||||
if body.get('client_instance_code') is not None:
|
||||
_require(body.get('client_instance_code'), 'client_instance_code')
|
||||
iface.client_instance_code = body['client_instance_code']
|
||||
if body.get('connector_type') is not None:
|
||||
connector_type = str(body['connector_type'])
|
||||
if connector_type not in VALID_CONNECTOR_TYPES:
|
||||
raise ValidationError('invalid connector_type', details={'allowed': list(VALID_CONNECTOR_TYPES)})
|
||||
iface.connector_type = connector_type
|
||||
if 'http_method' in body:
|
||||
iface.http_method = str(body.get('http_method') or '').strip().upper() or None
|
||||
if 'request_path' in body:
|
||||
iface.request_path = str(body.get('request_path') or '').strip() or None
|
||||
for json_field in ('request_spec_json', 'input_schema_json', 'response_mapping_json', 'output_schema_json'):
|
||||
if json_field in body:
|
||||
setattr(iface, json_field, body.get(json_field) or {})
|
||||
if body.get('version') is not None:
|
||||
iface.version = int(body.get('version') or 1)
|
||||
if body.get('status') is not None:
|
||||
status = str(body['status'])
|
||||
if status not in VALID_STATUSES:
|
||||
raise ValidationError('invalid status', details={'allowed': list(VALID_STATUSES)})
|
||||
iface.status = status
|
||||
if 'enabled' in body:
|
||||
iface.enabled = bool(body.get('enabled', True))
|
||||
from app import db
|
||||
db.session.commit()
|
||||
return ok(_serialize_interface(iface))
|
||||
|
||||
|
||||
# ---- Binding ----
|
||||
|
||||
@integration_connector_bp.route('/bindings', methods=['GET'])
|
||||
@@ -237,6 +317,7 @@ def create_binding():
|
||||
binding = IntegrationBinding(
|
||||
capability=body['capability'],
|
||||
context_selector_json=body.get('context_selector_json') or {},
|
||||
context_source_code=(str(body.get('context_source_code') or '').strip() or None),
|
||||
client_instance_code=body['client_instance_code'],
|
||||
interface_definition_code=body['interface_definition_code'],
|
||||
mapping_version=int(body.get('mapping_version') or 1),
|
||||
@@ -250,6 +331,48 @@ def create_binding():
|
||||
return ok(_serialize_binding(binding), status=201)
|
||||
|
||||
|
||||
@integration_connector_bp.route('/bindings/<int:binding_id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_binding(binding_id):
|
||||
"""更新绑定(capability 不变;可改 context 选择器、客户端/接口、映射版本、优先级、环境、生效区间、状态)。"""
|
||||
from app import db
|
||||
binding = db.session.get(IntegrationBinding, binding_id)
|
||||
if binding is None:
|
||||
raise NotFoundError('binding not found', code='INTEGRATION.BINDING_NOT_FOUND')
|
||||
body = request.get_json(silent=True) or {}
|
||||
if body.get('capability') is not None:
|
||||
_require(body.get('capability'), 'capability')
|
||||
binding.capability = body['capability']
|
||||
if 'context_selector_json' in body:
|
||||
binding.context_selector_json = body.get('context_selector_json') or {}
|
||||
if 'context_source_code' in body:
|
||||
binding.context_source_code = str(body.get('context_source_code') or '').strip() or None
|
||||
if body.get('client_instance_code') is not None:
|
||||
_require(body.get('client_instance_code'), 'client_instance_code')
|
||||
binding.client_instance_code = body['client_instance_code']
|
||||
if body.get('interface_definition_code') is not None:
|
||||
_require(body.get('interface_definition_code'), 'interface_definition_code')
|
||||
binding.interface_definition_code = body['interface_definition_code']
|
||||
if body.get('mapping_version') is not None:
|
||||
binding.mapping_version = int(body.get('mapping_version') or 1)
|
||||
if body.get('priority') is not None:
|
||||
binding.priority = int(body.get('priority') or 0)
|
||||
if body.get('environment') is not None:
|
||||
binding.environment = str(body['environment']).strip()
|
||||
if body.get('effective_from') is not None:
|
||||
binding.effective_from = body['effective_from'] or None
|
||||
if body.get('effective_to') is not None:
|
||||
binding.effective_to = body['effective_to'] or None
|
||||
if body.get('status') is not None:
|
||||
status = str(body['status'])
|
||||
if status not in VALID_STATUSES:
|
||||
raise ValidationError('invalid status', details={'allowed': list(VALID_STATUSES)})
|
||||
binding.status = status
|
||||
from app import db
|
||||
db.session.commit()
|
||||
return ok(_serialize_binding(binding))
|
||||
|
||||
|
||||
# ---- 凭据引用 ----
|
||||
|
||||
@integration_connector_bp.route('/credential-references', methods=['GET'])
|
||||
@@ -280,6 +403,28 @@ def create_credential_reference():
|
||||
return ok(_serialize_credential(cred), status=201)
|
||||
|
||||
|
||||
@integration_connector_bp.route('/credential-references/<code>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_credential_reference(code):
|
||||
"""更新凭据引用(code 不变;可改 secret_ref/provider/type/status)。只存引用,永不回显明文。"""
|
||||
cred = IntegrationCredentialReference.query.filter_by(code=code).first()
|
||||
if cred is None:
|
||||
raise NotFoundError('credential reference not found', code='INTEGRATION.CREDENTIAL_NOT_FOUND')
|
||||
body = request.get_json(silent=True) or {}
|
||||
if body.get('secret_ref') is not None:
|
||||
_require(body.get('secret_ref'), 'secret_ref')
|
||||
cred.secret_ref = str(body['secret_ref']).strip()
|
||||
if body.get('secret_provider') is not None:
|
||||
cred.secret_provider = str(body['secret_provider']).strip()
|
||||
if body.get('credential_type') is not None:
|
||||
cred.credential_type = str(body['credential_type']).strip()
|
||||
if body.get('status') is not None:
|
||||
cred.status = str(body['status']).strip()
|
||||
from app import db
|
||||
db.session.commit()
|
||||
return ok(_serialize_credential(cred))
|
||||
|
||||
|
||||
# ---- 连接测试 ----
|
||||
|
||||
@integration_connector_bp.route('/client-instances/<code>/test', methods=['POST'])
|
||||
|
||||
@@ -84,6 +84,10 @@ class IntegrationClientInstance(Base):
|
||||
name: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
connector_type: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
environment: Mapped[str] = mapped_column(String(16), nullable=False, default='prod', server_default='prod')
|
||||
# 关键强类型字段独立列(JSON 保留作兜底;兼容层 binding.py 拼回 dict)。
|
||||
# endpoint = 连接地址:REST 为接口基地址,SOAP 为 WSDL 地址(WSDL 内含服务端点)。
|
||||
endpoint: Mapped[Optional[str]] = mapped_column(String(512), nullable=True)
|
||||
timeout_seconds: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||
config_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
credential_ref_code: Mapped[Optional[str]] = mapped_column(
|
||||
ForeignKey('integration_credential_references.code'), nullable=True,
|
||||
@@ -119,6 +123,9 @@ class IntegrationInterfaceDefinition(Base):
|
||||
ForeignKey('integration_client_instances.code'), nullable=False,
|
||||
)
|
||||
connector_type: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
# 关键强类型字段独立列(JSON 保留作兜底)。
|
||||
http_method: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
|
||||
request_path: Mapped[Optional[str]] = mapped_column(String(512), nullable=True)
|
||||
request_spec_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
input_schema_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
response_mapping_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
@@ -153,6 +160,8 @@ class IntegrationBinding(Base):
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
capability: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
context_selector_json: Mapped[dict[str, Any]] = mapped_column(CONTEXT_SELECTOR_JSON, nullable=False, default=dict)
|
||||
# 最常用的 context 匹配键独立列(JSON 保留作兜底)。
|
||||
context_source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
client_instance_code: Mapped[str] = mapped_column(
|
||||
ForeignKey('integration_client_instances.code'), nullable=False,
|
||||
)
|
||||
|
||||
@@ -89,6 +89,25 @@ def resolve_binding(capability: str, context: dict, environment: str, *, now: da
|
||||
iface = IntegrationInterfaceDefinition.query.filter_by(code=row.interface_definition_code).first()
|
||||
if client is None or iface is None:
|
||||
raise BindingNotFoundError(capability=capability)
|
||||
|
||||
# 兼容层:把独立列拼回 dict,供 engine/mapping/transport 无感消费。
|
||||
# 优先列值,缺失回退 JSON(config_json / request_spec_json / context_selector_json)。
|
||||
config = dict(client.config_json or {})
|
||||
if client.endpoint is not None:
|
||||
config['endpoint'] = client.endpoint
|
||||
if client.timeout_seconds is not None:
|
||||
config['timeout_seconds'] = client.timeout_seconds
|
||||
|
||||
request_spec = dict(iface.request_spec_json or {})
|
||||
if iface.http_method is not None:
|
||||
request_spec['method'] = iface.http_method
|
||||
if iface.request_path is not None:
|
||||
request_spec['path'] = iface.request_path
|
||||
|
||||
selector = dict(row.context_selector_json or {})
|
||||
if row.context_source_code is not None and 'source_code' not in selector:
|
||||
selector['source_code'] = row.context_source_code
|
||||
|
||||
return BindingSnapshot(
|
||||
capability=row.capability,
|
||||
context_selector=selector,
|
||||
@@ -98,8 +117,8 @@ def resolve_binding(capability: str, context: dict, environment: str, *, now: da
|
||||
interface_version=iface.version,
|
||||
mapping_version=row.mapping_version,
|
||||
credential_ref_code=client.credential_ref_code,
|
||||
config=client.config_json or {},
|
||||
request_spec=iface.request_spec_json or {},
|
||||
config=config,
|
||||
request_spec=request_spec,
|
||||
response_mapping=iface.response_mapping_json or {},
|
||||
output_schema=iface.output_schema_json or {},
|
||||
)
|
||||
@@ -19,10 +19,11 @@ class SoapTransport:
|
||||
|
||||
def call(self, *, client: dict, interface: dict, request: dict) -> dict[str, Any]:
|
||||
config = client.get('config_json') or {}
|
||||
endpoint = str(config.get('endpoint') or '').strip()
|
||||
wsdl = str(config.get('wsdl') or '').strip()
|
||||
if not endpoint or not wsdl:
|
||||
raise TransportNotFrozenError('SOAP contract not frozen (missing endpoint/wsdl)')
|
||||
# SOAP 只需一个连接地址(WSDL):WSDL 已含服务端点,不需单独的 REST 式 endpoint。
|
||||
# 该地址存于 config['endpoint'](语义即连接地址);timeout 与 REST 同语义。
|
||||
wsdl = str(config.get('endpoint') or '').strip()
|
||||
if not wsdl:
|
||||
raise TransportNotFrozenError('SOAP contract not frozen (missing wsdl/endpoint)')
|
||||
|
||||
# 真实 SOAP 调用(zeep.Client(action=...,构造请求体、解析响应))待 WSDL 冻结后落地。
|
||||
# 真实 SOAP 调用(zeep.Client(timeout=int(config.get('timeout_seconds') or 60), ...)) 待 WSDL 冻结后落地。
|
||||
raise NotImplementedError('SOAP implementation pending frozen WSDL')
|
||||
@@ -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)
|
||||
@@ -144,3 +144,147 @@ def test_client_instance_test_connection(app, client, admin_headers, fake_gatewa
|
||||
response = client.post(f"{API_PREFIX}/client-instances/CLI-A/test", headers=admin_headers)
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()["data"]["ok"] is True
|
||||
|
||||
|
||||
def test_update_client_instance(app, client, admin_headers):
|
||||
"""PUT /client-instances/<code> → 200,更新 name/config/enabled。"""
|
||||
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "CLI-U", "name": "old", "connector_type": "rest", "environment": "prod",
|
||||
"config_json": {"endpoint": "https://old.invalid"},
|
||||
})
|
||||
response = client.put(f"{API_PREFIX}/client-instances/CLI-U", headers=admin_headers, json={
|
||||
"name": "new", "config_json": {"endpoint": "https://new.invalid"}, "enabled": False,
|
||||
})
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()["data"]["name"] == "new"
|
||||
assert response.get_json()["data"]["enabled"] is False
|
||||
assert response.get_json()["data"]["config_json"] == {"endpoint": "https://new.invalid"}
|
||||
|
||||
|
||||
def test_update_interface_definition(app, client, admin_headers):
|
||||
"""PUT /interface-definitions/<code> → 200,更新模板/回传映射/状态。"""
|
||||
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "CLI-I", "name": "cli", "connector_type": "rest", "environment": "prod",
|
||||
"config_json": {},
|
||||
})
|
||||
client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={
|
||||
"code": "IF-U", "name": "iface", "client_instance_code": "CLI-I", "connector_type": "rest",
|
||||
"request_spec_json": {"path": "/v1/old"}, "status": "draft",
|
||||
})
|
||||
response = client.put(f"{API_PREFIX}/interface-definitions/IF-U", headers=admin_headers, json={
|
||||
"request_spec_json": {"path": "/v1/new"}, "response_mapping_json": {"qty": "data.quantity"},
|
||||
"status": "published",
|
||||
})
|
||||
assert response.status_code == 200
|
||||
data = response.get_json()["data"]
|
||||
assert data["status"] == "published"
|
||||
assert data["request_spec_json"] == {"path": "/v1/new"}
|
||||
|
||||
|
||||
def test_update_binding(app, client, admin_headers):
|
||||
"""PUT /bindings/<id> → 200,更新映射版本/优先级/状态。"""
|
||||
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "CLI-B", "name": "cli", "connector_type": "rest", "environment": "prod",
|
||||
"config_json": {},
|
||||
})
|
||||
client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={
|
||||
"code": "IF-B", "name": "iface", "client_instance_code": "CLI-B", "connector_type": "rest",
|
||||
})
|
||||
created = client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={
|
||||
"capability": "in_transit_transfer.query_inventory", "client_instance_code": "CLI-B",
|
||||
"interface_definition_code": "IF-B", "status": "draft",
|
||||
})
|
||||
binding_id = created.get_json()["data"]["id"]
|
||||
response = client.put(f"{API_PREFIX}/bindings/{binding_id}", headers=admin_headers, json={
|
||||
"priority": 5, "mapping_version": 2, "status": "published",
|
||||
})
|
||||
assert response.status_code == 200
|
||||
data = response.get_json()["data"]
|
||||
assert data["priority"] == 5
|
||||
assert data["mapping_version"] == 2
|
||||
assert data["status"] == "published"
|
||||
|
||||
|
||||
def test_update_credential_reference(app, client, admin_headers):
|
||||
"""PUT /credential-references/<code> → 200,更新 secret_ref/status,且不回显明文。"""
|
||||
client.post(f"{API_PREFIX}/credential-references", headers=admin_headers, json={
|
||||
"code": "CRED-U", "secret_ref": "IN_TRANSIT_ERP_PASSWORD",
|
||||
})
|
||||
response = client.put(f"{API_PREFIX}/credential-references/CRED-U", headers=admin_headers, json={
|
||||
"secret_ref": "IN_TRANSIT_ERP_PASSWORD_ROTATED", "status": "rotating",
|
||||
})
|
||||
assert response.status_code == 200
|
||||
data = response.get_json()["data"]
|
||||
assert data["secret_ref"] == "IN_TRANSIT_ERP_PASSWORD_ROTATED"
|
||||
assert data["status"] == "rotating"
|
||||
assert "secret" not in str(data).lower() or data.get("secret") is None
|
||||
|
||||
|
||||
def test_client_instance_split_columns(app, client, admin_headers):
|
||||
"""POST /client-instances 写 endpoint/timeout_seconds 独立列,config_json 仅存扩展。"""
|
||||
created = client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "CLI-COL", "name": "col client", "connector_type": "soap", "environment": "prod",
|
||||
"endpoint": "https://erp.invalid/wsdl", "timeout_seconds": 90,
|
||||
"config_json": {"headers": {"X-Tenant": "A"}},
|
||||
})
|
||||
assert created.status_code == 201
|
||||
data = created.get_json()["data"]
|
||||
assert data["endpoint"] == "https://erp.invalid/wsdl"
|
||||
assert data["timeout_seconds"] == 90
|
||||
assert data["config_json"] == {"headers": {"X-Tenant": "A"}}
|
||||
|
||||
updated = client.put(f"{API_PREFIX}/client-instances/CLI-COL", headers=admin_headers, json={
|
||||
"endpoint": "https://erp2.invalid/wsdl", "timeout_seconds": 120,
|
||||
})
|
||||
assert updated.status_code == 200
|
||||
assert updated.get_json()["data"]["endpoint"] == "https://erp2.invalid/wsdl"
|
||||
assert updated.get_json()["data"]["timeout_seconds"] == 120
|
||||
|
||||
|
||||
def test_interface_definition_split_columns(app, client, admin_headers):
|
||||
"""POST/PUT /interface-definitions 写 http_method/request_path 独立列。"""
|
||||
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "CLI-IF", "name": "cli", "connector_type": "rest", "environment": "prod",
|
||||
"endpoint": "https://erp.invalid",
|
||||
})
|
||||
created = client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={
|
||||
"code": "IF-COL", "name": "iface", "client_instance_code": "CLI-IF", "connector_type": "rest",
|
||||
"http_method": "post", "request_path": "/transfer/{invoice_no}",
|
||||
"request_spec_json": {"template": {"qty": "{quantity}"}},
|
||||
})
|
||||
assert created.status_code == 201
|
||||
data = created.get_json()["data"]
|
||||
assert data["http_method"] == "POST"
|
||||
assert data["request_path"] == "/transfer/{invoice_no}"
|
||||
|
||||
updated = client.put(f"{API_PREFIX}/interface-definitions/IF-COL", headers=admin_headers, json={
|
||||
"http_method": "get", "request_path": "/inventory/{invoice_no}",
|
||||
})
|
||||
assert updated.status_code == 200
|
||||
assert updated.get_json()["data"]["http_method"] == "GET"
|
||||
assert updated.get_json()["data"]["request_path"] == "/inventory/{invoice_no}"
|
||||
|
||||
|
||||
def test_binding_split_columns(app, client, admin_headers):
|
||||
"""POST/PUT /bindings 写 context_source_code 独立列并回显。"""
|
||||
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "CLI-BC", "name": "cli", "connector_type": "rest", "environment": "prod",
|
||||
"endpoint": "https://erp.invalid",
|
||||
})
|
||||
client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={
|
||||
"code": "IF-BC", "name": "iface", "client_instance_code": "CLI-BC", "connector_type": "rest",
|
||||
})
|
||||
created = client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={
|
||||
"capability": "in_transit_transfer.query_inventory",
|
||||
"client_instance_code": "CLI-BC", "interface_definition_code": "IF-BC",
|
||||
"context_source_code": "DBS-AWSBI", "status": "published",
|
||||
})
|
||||
assert created.status_code == 201
|
||||
data = created.get_json()["data"]
|
||||
assert data["context_source_code"] == "DBS-AWSBI"
|
||||
|
||||
updated = client.put(f"{API_PREFIX}/bindings/{data['id']}", headers=admin_headers, json={
|
||||
"context_source_code": "CRANE-SZ",
|
||||
})
|
||||
assert updated.status_code == 200
|
||||
assert updated.get_json()["data"]["context_source_code"] == "CRANE-SZ"
|
||||
@@ -1,7 +1,7 @@
|
||||
"""tests/services/integration_connector/test_migration.py
|
||||
|
||||
用途:验证 Integration Connector 迁移可独立升级与回滚,且正确链在当前 head 之后。
|
||||
依赖:Alembic Operations、SQLAlchemy SQLite、ic1a2b3c4d5f 迁移。
|
||||
依赖:Alembic Operations、SQLAlchemy SQLite、ic1a2b3c4d5f / ix1a2b3c4d5e 迁移。
|
||||
逻辑:空库升级后 5 张表(含索引/约束)存在;回滚后全部删除;down_revision 指向既有 head。
|
||||
"""
|
||||
|
||||
@@ -14,6 +14,8 @@ import sqlalchemy as sa
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
EXPECTED_TABLES = {
|
||||
'integration_credential_references',
|
||||
@@ -23,11 +25,13 @@ EXPECTED_TABLES = {
|
||||
'integration_calls',
|
||||
}
|
||||
|
||||
VERSIONS_DIR = Path(__file__).parents[3] / 'migrations' / 'versions'
|
||||
|
||||
def _load_migration():
|
||||
"""加载连接器框架建表迁移。"""
|
||||
path = Path(__file__).parents[3] / 'migrations' / 'versions' / 'ic1a2b3c4d5f_add_integration_connector.py'
|
||||
spec = importlib.util.spec_from_file_location('integration_connector_migration', path)
|
||||
|
||||
def _load_migration(name: str, filename: str):
|
||||
"""加载指定迁移模块。"""
|
||||
path = VERSIONS_DIR / filename
|
||||
spec = importlib.util.spec_from_file_location(name, path)
|
||||
assert spec is not None and spec.loader is not None
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
@@ -35,8 +39,8 @@ def _load_migration():
|
||||
|
||||
|
||||
def test_migration_chains_after_head():
|
||||
"""新迁移必须挂接在既有链 head it1a2b3c4d5e 之后。"""
|
||||
migration = _load_migration()
|
||||
"""建表迁移必须挂接在既有链 head it1a2b3c4d5e 之后。"""
|
||||
migration = _load_migration('integration_connector_migration', 'ic1a2b3c4d5f_add_integration_connector.py')
|
||||
assert migration.revision == 'ic1a2b3c4d5f'
|
||||
assert migration.down_revision == 'it1a2b3c4d5e'
|
||||
|
||||
@@ -44,21 +48,39 @@ def test_migration_chains_after_head():
|
||||
def test_integration_connector_migration_round_trip():
|
||||
"""空库升级后 5 表存在;回滚后全部删除。"""
|
||||
engine = sa.create_engine('sqlite:///:memory:')
|
||||
base = _load_migration('integration_connector_migration', 'ic1a2b3c4d5f_add_integration_connector.py')
|
||||
split = _load_migration('integration_connector_columns_migration', 'ix1a2b3c4d5e_split_integration_connector_columns.py')
|
||||
with engine.begin() as connection:
|
||||
context = MigrationContext.configure(connection)
|
||||
operations = Operations(context)
|
||||
migration = _load_migration()
|
||||
migration.op = operations
|
||||
base.op = operations
|
||||
split.op = operations
|
||||
|
||||
migration.upgrade()
|
||||
base.upgrade()
|
||||
split.upgrade()
|
||||
tables = set(sa.inspect(connection).get_table_names())
|
||||
assert EXPECTED_TABLES.issubset(tables)
|
||||
|
||||
inspector = sa.inspect(connection)
|
||||
client_cols = {item['name'] for item in inspector.get_columns('integration_client_instances')}
|
||||
assert 'credential_ref_code' in client_cols
|
||||
assert 'endpoint' in client_cols
|
||||
assert 'timeout_seconds' in client_cols
|
||||
iface_cols = {item['name'] for item in inspector.get_columns('integration_interface_definitions')}
|
||||
assert 'http_method' in iface_cols
|
||||
assert 'request_path' in iface_cols
|
||||
binding_cols = {item['name'] for item in inspector.get_columns('integration_bindings')}
|
||||
assert 'context_source_code' in binding_cols
|
||||
binding_indexes = {item['name'] for item in inspector.get_indexes('integration_bindings')}
|
||||
assert 'ix_integration_bindings_cap_env_status' in binding_indexes
|
||||
|
||||
migration.downgrade()
|
||||
split.downgrade()
|
||||
base.downgrade()
|
||||
assert EXPECTED_TABLES.isdisjoint(set(sa.inspect(connection).get_table_names()))
|
||||
|
||||
|
||||
def test_split_migration_chains_after_create():
|
||||
"""拆列迁移必须挂接在 ic1a2b3c4d5e 之后(down_revision=iy1a2b3c4d5e)。"""
|
||||
split = _load_migration('integration_connector_columns_migration', 'ix1a2b3c4d5e_split_integration_connector_columns.py')
|
||||
assert split.revision == 'ix1a2b3c4d5e'
|
||||
assert split.down_revision == 'iy1a2b3c4d5e'
|
||||
@@ -84,7 +84,7 @@ def test_rest_fail_closed_without_endpoint():
|
||||
|
||||
|
||||
def test_soap_fail_closed_without_wsdl():
|
||||
"""SOAP 无 wsdl/endpoint 时 fail-closed 抛 TransportNotFrozenError。"""
|
||||
"""SOAP 无 wsdl 时 fail-closed 抛 TransportNotFrozenError(SOAP 只需 wsdl,不需 endpoint)。"""
|
||||
transport = SoapTransport()
|
||||
with pytest.raises(TransportNotFrozenError):
|
||||
transport.call(
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
"""
|
||||
backend/tests/test_integration_connector_columns_migration.py
|
||||
|
||||
用途:验证集成连接器"关键字段拆列"迁移的版本链与新增/回滚列清单。
|
||||
依赖:新增迁移模块、pytest monkeypatch。
|
||||
逻辑:拦截 add_column/drop_column,确认三个表各加/删目标列;确认 down_revision 承接当前 head。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
MIGRATION_REV = "ix1a2b3c4d5e_split_integration_connector_columns"
|
||||
|
||||
COLUMN_TARGETS: list[tuple[str, str]] = [
|
||||
("integration_client_instances", "endpoint"),
|
||||
("integration_client_instances", "timeout_seconds"),
|
||||
("integration_interface_definitions", "http_method"),
|
||||
("integration_interface_definitions", "request_path"),
|
||||
("integration_bindings", "context_source_code"),
|
||||
]
|
||||
|
||||
|
||||
def test_integration_connector_column_migration_adds_columns(monkeypatch):
|
||||
"""迁移应承接 head iy1a2b3c4d5e,并对三张表加关键字段列。"""
|
||||
import importlib
|
||||
|
||||
module = importlib.import_module(f"migrations.versions.{MIGRATION_REV}")
|
||||
add_calls: list[tuple[str, str]] = []
|
||||
drop_calls: list[tuple[str, str]] = []
|
||||
|
||||
def capture_add(table_name: str, column: Any, **_: Any) -> None:
|
||||
add_calls.append((table_name, getattr(column, "name", column)))
|
||||
|
||||
def capture_drop(table_name: str, column_name: Any, **_: Any) -> None:
|
||||
drop_calls.append((table_name, getattr(column_name, "name", column_name)))
|
||||
|
||||
monkeypatch.setattr(module.op, "add_column", capture_add)
|
||||
monkeypatch.setattr(module.op, "drop_column", capture_drop)
|
||||
|
||||
module.upgrade()
|
||||
assert module.down_revision == "iy1a2b3c4d5e"
|
||||
for target in COLUMN_TARGETS:
|
||||
assert target in add_calls
|
||||
|
||||
module.downgrade()
|
||||
for target in COLUMN_TARGETS:
|
||||
assert target in drop_calls
|
||||
Reference in new issue
Block a user