""" 将所有模板与两个输入字段关联 - 线索信息 (clue_info) - 被核查人员工作基本情况线索 (target_basic_info_clue) """ import pymysql import os import sys import time import random from datetime import datetime # 设置输出编码为UTF-8 if sys.platform == 'win32': import io sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8') # 数据库连接配置 DB_CONFIG = { 'host': os.getenv('DB_HOST', '152.136.177.240'), 'port': int(os.getenv('DB_PORT', 5012)), 'user': os.getenv('DB_USER', 'finyx'), 'password': os.getenv('DB_PASSWORD', '6QsGK6MpePZDE57Z'), 'database': os.getenv('DB_NAME', 'finyx'), 'charset': 'utf8mb4' } TENANT_ID = 615873064429507639 CREATED_BY = 655162080928945152 UPDATED_BY = 655162080928945152 def generate_id(): """生成ID""" timestamp = int(time.time() * 1000) random_part = random.randint(100000, 999999) return timestamp * 1000 + random_part def get_input_field_ids(conn): """获取两个输入字段的ID""" cursor = conn.cursor(pymysql.cursors.DictCursor) field_codes = ['clue_info', 'target_basic_info_clue'] cursor.execute(""" SELECT id, name, filed_code FROM f_polic_field WHERE tenant_id = %s AND filed_code IN (%s, %s) AND field_type = 1 AND state = 1 """, (TENANT_ID, field_codes[0], field_codes[1])) fields = cursor.fetchall() field_map = {field['filed_code']: field for field in fields} result = {} for code in field_codes: if code in field_map: result[code] = field_map[code] else: print(f"[WARN] 未找到字段: {code}") return result def get_all_templates(conn): """获取所有启用的模板""" cursor = conn.cursor(pymysql.cursors.DictCursor) cursor.execute(""" SELECT id, name FROM f_polic_file_config WHERE tenant_id = %s AND state = 1 ORDER BY name """, (TENANT_ID,)) return cursor.fetchall() def get_existing_relations(conn, template_id, field_ids): """获取模板与字段的现有关联关系""" cursor = conn.cursor() if not field_ids: return set() placeholders = ','.join(['%s'] * len(field_ids)) cursor.execute(f""" SELECT filed_id FROM f_polic_file_field WHERE tenant_id = %s AND file_id = %s AND filed_id IN ({placeholders}) AND state = 1 """, [TENANT_ID, template_id] + list(field_ids)) return {row[0] for row in cursor.fetchall()} def create_relation(conn, template_id, field_id): """创建模板与字段的关联关系""" cursor = conn.cursor() current_time = datetime.now() # 检查是否已存在 cursor.execute(""" SELECT id FROM f_polic_file_field WHERE tenant_id = %s AND file_id = %s AND filed_id = %s """, (TENANT_ID, template_id, field_id)) if cursor.fetchone(): return False # 已存在,不需要创建 # 创建新关联 relation_id = generate_id() cursor.execute(""" INSERT INTO f_polic_file_field (id, tenant_id, file_id, filed_id, created_time, created_by, updated_time, updated_by, state) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, 1) """, ( relation_id, TENANT_ID, template_id, field_id, current_time, CREATED_BY, current_time, UPDATED_BY )) return True # 创建成功 def main(): """主函数""" print("="*80) print("将所有模板与输入字段关联") print("="*80) try: conn = pymysql.connect(**DB_CONFIG) print("[OK] 数据库连接成功\n") except Exception as e: print(f"[ERROR] 数据库连接失败: {e}") return try: # 1. 获取输入字段ID print("1. 获取输入字段ID...") input_fields = get_input_field_ids(conn) if len(input_fields) != 2: print(f"[ERROR] 未找到所有输入字段,只找到: {list(input_fields.keys())}") return field_ids = [field['id'] for field in input_fields.values()] print(f" 找到字段:") for code, field in input_fields.items(): print(f" - {field['name']} ({code}): ID={field['id']}") print() # 2. 获取所有模板 print("2. 获取所有启用的模板...") templates = get_all_templates(conn) print(f" 找到 {len(templates)} 个模板\n") # 3. 为每个模板创建关联关系 print("3. 创建关联关系...") created_count = 0 existing_count = 0 error_count = 0 for template in templates: template_id = template['id'] template_name = template['name'] # 获取现有关联 existing_relations = get_existing_relations(conn, template_id, field_ids) # 为每个字段创建关联(如果不存在) for field_code, field_info in input_fields.items(): field_id = field_info['id'] if field_id in existing_relations: existing_count += 1 continue try: if create_relation(conn, template_id, field_id): created_count += 1 print(f" [OK] {template_name} <- {field_info['name']} ({field_code})") else: existing_count += 1 except Exception as e: error_count += 1 print(f" [ERROR] {template_name} <- {field_info['name']}: {e}") # 提交事务 conn.commit() # 4. 统计结果 print("\n" + "="*80) print("执行结果") print("="*80) print(f"模板总数: {len(templates)}") print(f"字段总数: {len(input_fields)}") print(f"预期关联数: {len(templates) * len(input_fields)}") print(f"新创建关联: {created_count}") print(f"已存在关联: {existing_count}") print(f"错误数量: {error_count}") print(f"实际关联数: {created_count + existing_count}") if error_count == 0: print("\n[OK] 所有关联关系已成功创建或已存在") else: print(f"\n[WARN] 有 {error_count} 个关联关系创建失败") except Exception as e: conn.rollback() print(f"\n[ERROR] 执行过程中发生错误: {e}") import traceback traceback.print_exc() finally: conn.close() print("\n数据库连接已关闭") if __name__ == '__main__': main()