def align_records(cobol_records: list[dict], java_records: list[dict], key_field: str = "CUST-ID") -> list[tuple]: """对齐COBOL和Java记录 Args: cobol_records: COBOL输出记录列表 java_records: Java输出记录列表 key_field: 用于对齐的关键字段名(默认为"CUST-ID") Returns: 对齐结果列表,每个元素为 (cobol_record, java_record, status) status: "MATCHED", "MISSING_IN_SPARK", "EXTRA_IN_SPARK" """ if not cobol_records and not java_records: return [] # 智能关键字段推断:如果默认key_field不存在,尝试推断 effective_key = key_field if cobol_records: sample_record = cobol_records[0] if effective_key not in sample_record: # 尝试常见的关键字段名 common_keys = ["ID", "CUST-ID", "EMP-ID", "KEY", "CODE", "NO"] for k in common_keys: if k in sample_record: effective_key = k break def _by(records, kf): d = {} for r in records: key = str(r.get(kf, "__NONE__")) d.setdefault(key, []).append(r) return d c_by = _by(cobol_records, effective_key) j_by = _by(java_records, effective_key) pairs = [] all_keys = set(c_by) | set(j_by) for k in sorted(all_keys): c_items = c_by.get(k, []) j_items = j_by.get(k, []) for i in range(max(len(c_items), len(j_items))): c = c_items[i] if i < len(c_items) else None j = j_items[i] if i < len(j_items) else None if c and j: pairs.append((c, j, "MATCHED")) elif c: pairs.append((c, None, "MISSING_IN_SPARK")) else: pairs.append((None, j, "EXTRA_IN_SPARK")) return pairs