dataflows.py 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614
  1. import logging
  2. from typing import Dict, List, Optional, Any, Union
  3. from datetime import datetime
  4. import json
  5. from app.core.llm.llm_service import llm_sql
  6. from app.core.graph.graph_operations import (
  7. connect_graph,
  8. create_or_get_node,
  9. get_node,
  10. relationship_exists,
  11. )
  12. from app.core.meta_data import translate_and_parse, get_formatted_time
  13. from app import db
  14. from sqlalchemy import text
  15. logger = logging.getLogger(__name__)
  16. class DataFlowService:
  17. """数据流服务类,处理数据流相关的业务逻辑"""
  18. @staticmethod
  19. def get_dataflows(
  20. page: int = 1,
  21. page_size: int = 10,
  22. search: str = '',
  23. ) -> Dict[str, Any]:
  24. """
  25. 获取数据流列表
  26. Args:
  27. page: 页码
  28. page_size: 每页大小
  29. search: 搜索关键词
  30. Returns:
  31. 包含数据流列表和分页信息的字典
  32. """
  33. try:
  34. # 从图数据库查询数据流列表
  35. skip_count = (page - 1) * page_size
  36. # 构建搜索条件
  37. where_clause = ""
  38. params: Dict[str, Union[int, str]] = {
  39. 'skip': skip_count,
  40. 'limit': page_size,
  41. }
  42. if search:
  43. where_clause = (
  44. "WHERE n.name_zh CONTAINS $search OR "
  45. "n.description CONTAINS $search"
  46. )
  47. params['search'] = search
  48. # 查询数据流列表
  49. query = f"""
  50. MATCH (n:DataFlow)
  51. {where_clause}
  52. RETURN n, id(n) as node_id
  53. ORDER BY n.created_at DESC
  54. SKIP $skip
  55. LIMIT $limit
  56. """
  57. # 获取Neo4j驱动(如果连接失败会抛出ConnectionError异常)
  58. try:
  59. with connect_graph().session() as session:
  60. list_result = session.run(query, params).data()
  61. # 查询总数
  62. count_query = f"""
  63. MATCH (n:DataFlow)
  64. {where_clause}
  65. RETURN count(n) as total
  66. """
  67. count_params = {'search': search} if search else {}
  68. count_result = session.run(
  69. count_query, count_params).single()
  70. total = count_result['total'] if count_result else 0
  71. except Exception as e:
  72. # 确保 driver 被正确关闭,避免资源泄漏 - 这里不再需要手动关闭
  73. # driver,因为connect_graph可能返回单例或新实例。如果是新实例,
  74. # 我们没有引用它去关闭;若connect_graph每次返回新实例且需要关闭,
  75. # 之前的代码是对的。如果connect_graph返回单例,则不应关闭。
  76. # 用户反馈:The driver.close() call prematurely closes a shared
  77. # driver instance,所以直接使用 session,并不关闭 driver。
  78. logger.error(f"查询数据流失败: {str(e)}")
  79. raise e
  80. # 格式化结果
  81. dataflows = []
  82. for record in list_result:
  83. node = record['n']
  84. dataflow = dict(node)
  85. dataflow['id'] = record['node_id'] # 使用查询返回的node_id
  86. dataflows.append(dataflow)
  87. return {
  88. 'list': dataflows,
  89. 'pagination': {
  90. 'page': page,
  91. 'page_size': page_size,
  92. 'total': total,
  93. 'total_pages': (total + page_size - 1) // page_size
  94. }
  95. }
  96. except Exception as e:
  97. logger.error(f"获取数据流列表失败: {str(e)}")
  98. raise e
  99. @staticmethod
  100. def get_dataflow_by_id(dataflow_id: int) -> Optional[Dict[str, Any]]:
  101. """
  102. 根据ID获取数据流详情
  103. Args:
  104. dataflow_id: 数据流ID
  105. Returns:
  106. 数据流详情字典,如果不存在则返回None
  107. """
  108. try:
  109. # 从Neo4j获取DataFlow节点的所有属性
  110. neo4j_query = """
  111. MATCH (n:DataFlow)
  112. WHERE id(n) = $dataflow_id
  113. RETURN n, id(n) as node_id
  114. """
  115. with connect_graph().session() as session:
  116. neo4j_result = session.run(
  117. neo4j_query, dataflow_id=dataflow_id).data()
  118. if not neo4j_result:
  119. logger.warning(f"未找到ID为 {dataflow_id} 的DataFlow节点")
  120. return None
  121. record = neo4j_result[0]
  122. node = record['n']
  123. # 将节点属性转换为字典
  124. dataflow = dict(node)
  125. dataflow['id'] = record['node_id']
  126. # 处理 script_requirement:如果是JSON字符串,解析为对象
  127. script_requirement_str = dataflow.get('script_requirement', '')
  128. if script_requirement_str:
  129. try:
  130. # 尝试解析JSON字符串
  131. script_requirement_obj = json.loads(
  132. script_requirement_str)
  133. dataflow['script_requirement'] = script_requirement_obj
  134. logger.debug(
  135. "成功解析script_requirement: %s",
  136. script_requirement_obj,
  137. )
  138. except (json.JSONDecodeError, TypeError) as e:
  139. logger.warning(f"script_requirement解析失败,保持原值: {e}")
  140. # 保持原值(字符串)
  141. dataflow['script_requirement'] = script_requirement_str
  142. else:
  143. # 如果为空,设置为None
  144. dataflow['script_requirement'] = None
  145. logger.info(
  146. "成功获取DataFlow详情,ID: %s, 名称: %s",
  147. dataflow_id,
  148. dataflow.get('name_zh'),
  149. )
  150. return dataflow
  151. except Exception as e:
  152. logger.error(f"获取数据流详情失败: {str(e)}")
  153. raise e
  154. @staticmethod
  155. def create_dataflow(data: Dict[str, Any]) -> Dict[str, Any]:
  156. """
  157. 创建新的数据流
  158. Args:
  159. data: 数据流配置数据
  160. Returns:
  161. 创建的数据流信息
  162. """
  163. try:
  164. # 验证必填字段
  165. required_fields = ['name_zh', 'describe']
  166. for field in required_fields:
  167. if field not in data:
  168. raise ValueError(f"缺少必填字段: {field}")
  169. dataflow_name = data['name_zh']
  170. # 使用LLM翻译名称生成英文名
  171. try:
  172. result_list = translate_and_parse(dataflow_name)
  173. name_en = (
  174. result_list[0]
  175. if result_list
  176. else dataflow_name.lower().replace(' ', '_')
  177. )
  178. except Exception as e:
  179. logger.warning(f"翻译失败,使用默认英文名: {str(e)}")
  180. name_en = dataflow_name.lower().replace(' ', '_')
  181. # 处理 script_requirement,将其转换为 JSON 字符串
  182. script_requirement = data.get('script_requirement', None)
  183. if script_requirement is not None:
  184. # 如果是字典或列表,转换为 JSON 字符串
  185. if isinstance(script_requirement, (dict, list)):
  186. script_requirement_str = json.dumps(
  187. script_requirement, ensure_ascii=False)
  188. else:
  189. # 如果已经是字符串,直接使用
  190. script_requirement_str = str(script_requirement)
  191. else:
  192. script_requirement_str = ''
  193. # 准备节点数据
  194. node_data = {
  195. 'name_zh': dataflow_name,
  196. 'name_en': name_en,
  197. 'category': data.get('category', ''),
  198. 'organization': data.get('organization', ''),
  199. 'leader': data.get('leader', ''),
  200. 'frequency': data.get('frequency', ''),
  201. 'tag': data.get('tag', ''),
  202. 'describe': data.get('describe', ''),
  203. 'status': data.get('status', 'inactive'),
  204. 'update_mode': data.get('update_mode', 'append'),
  205. 'script_type': data.get('script_type', 'python'),
  206. 'script_requirement': script_requirement_str,
  207. 'created_at': get_formatted_time(),
  208. 'updated_at': get_formatted_time()
  209. }
  210. # 创建或获取数据流节点
  211. dataflow_id = get_node('DataFlow', name=dataflow_name)
  212. if dataflow_id:
  213. raise ValueError(f"数据流 '{dataflow_name}' 已存在")
  214. dataflow_id = create_or_get_node('DataFlow', **node_data)
  215. # 处理标签关系
  216. tag_id = data.get('tag')
  217. if tag_id is not None:
  218. try:
  219. DataFlowService._handle_tag_relationship(
  220. dataflow_id, tag_id)
  221. except Exception as e:
  222. logger.warning(f"处理标签关系时出错: {str(e)}")
  223. # 成功创建图数据库节点后,写入PG数据库
  224. try:
  225. DataFlowService._save_to_pg_database(
  226. data, dataflow_name, name_en)
  227. logger.info(f"数据流信息已写入PG数据库: {dataflow_name}")
  228. # PG数据库记录成功写入后,在neo4j图数据库中创建script关系
  229. try:
  230. DataFlowService._handle_script_relationships(
  231. data, dataflow_name, name_en)
  232. logger.info(f"脚本关系创建成功: {dataflow_name}")
  233. except Exception as script_error:
  234. logger.warning(f"创建脚本关系失败: {str(script_error)}")
  235. except Exception as pg_error:
  236. logger.error(f"写入PG数据库失败: {str(pg_error)}")
  237. # 注意:这里可以选择回滚图数据库操作,但目前保持图数据库数据
  238. # 在实际应用中,可能需要考虑分布式事务
  239. # 返回创建的数据流信息
  240. # 查询创建的节点获取完整信息
  241. query = (
  242. "MATCH (n:DataFlow {name_zh: $name_zh}) "
  243. "RETURN n, id(n) as node_id"
  244. )
  245. with connect_graph().session() as session:
  246. id_result = session.run(query, name_zh=dataflow_name).single()
  247. if id_result:
  248. dataflow_node = id_result['n']
  249. node_id = id_result['node_id']
  250. # 将节点属性转换为字典
  251. result = dict(dataflow_node)
  252. result['id'] = node_id
  253. else:
  254. # 如果查询失败,返回基本信息
  255. result = {
  256. 'id': (
  257. dataflow_id
  258. if isinstance(dataflow_id, int)
  259. else None
  260. ),
  261. 'name_zh': dataflow_name,
  262. 'name_en': name_en,
  263. 'created_at': get_formatted_time(),
  264. }
  265. logger.info(f"创建数据流成功: {dataflow_name}")
  266. return result
  267. except Exception as e:
  268. logger.error(f"创建数据流失败: {str(e)}")
  269. raise e
  270. @staticmethod
  271. def _save_to_pg_database(
  272. data: Dict[str, Any],
  273. script_name: str,
  274. name_en: str,
  275. ):
  276. """
  277. 将脚本信息保存到PG数据库
  278. Args:
  279. data: 包含脚本信息的数据
  280. script_name: 脚本名称
  281. name_en: 英文名称
  282. """
  283. try:
  284. # 提取脚本相关信息
  285. # 处理 script_requirement,确保保存为 JSON 字符串
  286. script_requirement_raw = data.get('script_requirement', None)
  287. # 用于保存从 script_requirement 中提取的 rule
  288. rule_from_requirement = ''
  289. if script_requirement_raw is not None:
  290. # 如果是字典,提取 rule 字段
  291. if isinstance(script_requirement_raw, dict):
  292. rule_from_requirement = script_requirement_raw.get(
  293. 'rule', '')
  294. script_requirement = json.dumps(
  295. script_requirement_raw, ensure_ascii=False)
  296. elif isinstance(script_requirement_raw, list):
  297. script_requirement = json.dumps(
  298. script_requirement_raw, ensure_ascii=False)
  299. else:
  300. # 如果已经是字符串,尝试解析以提取 rule
  301. script_requirement = str(script_requirement_raw)
  302. try:
  303. parsed_req = json.loads(script_requirement)
  304. if isinstance(parsed_req, dict):
  305. rule_from_requirement = parsed_req.get('rule', '')
  306. except (json.JSONDecodeError, TypeError):
  307. pass
  308. else:
  309. script_requirement = ''
  310. # 处理 script_content:优先使用前端传入的值,如果为空则使用从 script_requirement 提取的 rule
  311. script_content = data.get('script_content', '')
  312. if not script_content and rule_from_requirement:
  313. script_content = rule_from_requirement
  314. logger.info(
  315. "script_content为空,使用从script_requirement提取的rule: %s",
  316. rule_from_requirement,
  317. )
  318. # 安全处理 source_table 和 target_table(避免 None 值导致的 'in' 操作错误)
  319. source_table_raw = data.get('source_table') or ''
  320. source_table = (
  321. source_table_raw.split(':')[-1]
  322. if ':' in source_table_raw
  323. else source_table_raw
  324. )
  325. target_table_raw = data.get('target_table') or ''
  326. target_table = (
  327. target_table_raw.split(':')[-1]
  328. if ':' in target_table_raw
  329. else (target_table_raw or name_en)
  330. )
  331. script_type = data.get('script_type', 'python')
  332. user_name = data.get('created_by', 'system')
  333. target_dt_column = data.get('target_dt_column', '')
  334. # 验证必需字段
  335. if not target_table:
  336. target_table = name_en
  337. if not script_name:
  338. raise ValueError("script_name不能为空")
  339. # 构建插入SQL
  340. insert_sql = text(
  341. """
  342. INSERT INTO dags.data_transform_scripts
  343. (source_table, target_table, script_name, script_type,
  344. script_requirement, script_content, user_name, create_time,
  345. update_time, target_dt_column)
  346. VALUES
  347. (:source_table, :target_table, :script_name, :script_type,
  348. :script_requirement, :script_content, :user_name,
  349. :create_time, :update_time, :target_dt_column)
  350. ON CONFLICT (target_table, script_name)
  351. DO UPDATE SET
  352. source_table = EXCLUDED.source_table,
  353. script_type = EXCLUDED.script_type,
  354. script_requirement = EXCLUDED.script_requirement,
  355. script_content = EXCLUDED.script_content,
  356. user_name = EXCLUDED.user_name,
  357. update_time = EXCLUDED.update_time,
  358. target_dt_column = EXCLUDED.target_dt_column
  359. """
  360. )
  361. # 准备参数
  362. current_time = datetime.now()
  363. params = {
  364. 'source_table': source_table,
  365. 'target_table': target_table,
  366. 'script_name': script_name,
  367. 'script_type': script_type,
  368. 'script_requirement': script_requirement,
  369. 'script_content': script_content,
  370. 'user_name': user_name,
  371. 'create_time': current_time,
  372. 'update_time': current_time,
  373. 'target_dt_column': target_dt_column
  374. }
  375. # 执行插入操作
  376. db.session.execute(insert_sql, params)
  377. # 新增:保存到task_list表
  378. try:
  379. # 1. 解析script_requirement并构建详细的任务描述
  380. task_description_md = script_requirement
  381. try:
  382. # 尝试解析JSON
  383. try:
  384. req_json = json.loads(script_requirement)
  385. except (json.JSONDecodeError, TypeError):
  386. req_json = None
  387. if isinstance(req_json, dict):
  388. # 1. 从script_requirement中提取rule字段作为request_content_str
  389. request_content_str = req_json.get('rule', '')
  390. # 2. 从script_requirement中提取source_table和
  391. # target_table字段信息
  392. source_table_ids = req_json.get('source_table', [])
  393. target_table_ids = req_json.get('target_table', [])
  394. # 确保是列表格式
  395. if not isinstance(source_table_ids, list):
  396. source_table_ids = [
  397. source_table_ids] if source_table_ids else []
  398. if not isinstance(target_table_ids, list):
  399. target_table_ids = [
  400. target_table_ids] if target_table_ids else []
  401. # 合并所有BusinessDomain ID
  402. all_bd_ids = source_table_ids + target_table_ids
  403. # 4. 从data参数中提取update_mode
  404. update_mode = data.get('update_mode', 'append')
  405. # 生成Business Domain DDLs
  406. source_ddls = []
  407. target_ddls = []
  408. data_source_info = None
  409. if all_bd_ids:
  410. try:
  411. with connect_graph().session() as session:
  412. # 处理source tables
  413. for bd_id in source_table_ids:
  414. ddl_info = (
  415. DataFlowService
  416. ._generate_businessdomain_ddl(
  417. session,
  418. bd_id,
  419. is_target=False,
  420. )
  421. )
  422. if ddl_info:
  423. source_ddls.append(ddl_info['ddl'])
  424. # 3. 如果BELONGS_TO关系连接的是
  425. # "数据资源",获取数据源信息
  426. if (
  427. ddl_info.get('data_source')
  428. and not data_source_info
  429. ):
  430. data_source_info = ddl_info[
  431. 'data_source'
  432. ]
  433. # 处理target tables(5. 目标表缺省要有create_time字段)
  434. for bd_id in target_table_ids:
  435. ddl_info = (
  436. DataFlowService
  437. ._generate_businessdomain_ddl(
  438. session,
  439. bd_id,
  440. is_target=True,
  441. update_mode=update_mode,
  442. )
  443. )
  444. if ddl_info:
  445. target_ddls.append(ddl_info['ddl'])
  446. # 同样检查BELONGS_TO关系,获取数据源信息
  447. if (
  448. ddl_info.get('data_source')
  449. and not data_source_info
  450. ):
  451. data_source_info = ddl_info[
  452. 'data_source'
  453. ]
  454. except Exception as neo_e:
  455. logger.error(
  456. f"获取BusinessDomain DDL失败: {str(neo_e)}")
  457. # 构建Markdown格式的任务描述
  458. task_desc_parts = [f"# Task: {script_name}\n"]
  459. # 添加数据源信息
  460. if data_source_info:
  461. task_desc_parts.append("## Data Source")
  462. task_desc_parts.append(
  463. f"- **Type**: "
  464. f"{data_source_info.get('type', 'N/A')}"
  465. )
  466. task_desc_parts.append(
  467. f"- **Host**: "
  468. f"{data_source_info.get('host', 'N/A')}"
  469. )
  470. task_desc_parts.append(
  471. f"- **Port**: "
  472. f"{data_source_info.get('port', 'N/A')}"
  473. )
  474. task_desc_parts.append(
  475. f"- **Database**: "
  476. f"{data_source_info.get('database', 'N/A')}\n"
  477. )
  478. # 添加源表DDL
  479. if source_ddls:
  480. task_desc_parts.append("## Source Tables (DDL)")
  481. for ddl in source_ddls:
  482. task_desc_parts.append(f"```sql\n{ddl}\n```\n")
  483. # 添加目标表DDL
  484. if target_ddls:
  485. task_desc_parts.append("## Target Tables (DDL)")
  486. for ddl in target_ddls:
  487. task_desc_parts.append(f"```sql\n{ddl}\n```\n")
  488. # 添加更新模式说明
  489. task_desc_parts.append("## Update Mode")
  490. if update_mode == 'append':
  491. task_desc_parts.append("- **Mode**: Append (追加模式)")
  492. task_desc_parts.append(
  493. "- **Description**: 新数据将追加到目标表,不删除现有数据\n")
  494. else:
  495. task_desc_parts.append(
  496. "- **Mode**: Full Refresh (全量更新)")
  497. task_desc_parts.append(
  498. "- **Description**: 目标表将被清空后重新写入数据\n")
  499. # 添加请求内容(rule)
  500. if request_content_str:
  501. task_desc_parts.append("## Request Content")
  502. task_desc_parts.append(f"{request_content_str}\n")
  503. # 添加实施步骤(根据任务类型优化)
  504. task_desc_parts.append("## Implementation Steps")
  505. # 判断是否为远程数据源导入任务
  506. if data_source_info:
  507. # 从远程数据源导入数据的简化步骤
  508. task_desc_parts.append(
  509. "1. Create an n8n workflow to execute the "
  510. "data import task"
  511. )
  512. task_desc_parts.append(
  513. "2. Configure the workflow to call "
  514. "`import_resource_data.py` Python script"
  515. )
  516. task_desc_parts.append(
  517. "3. Pass the following parameters to the "
  518. "Python execution node:"
  519. )
  520. task_desc_parts.append(
  521. " - `--source-config`: JSON configuration "
  522. "for the remote data source"
  523. )
  524. task_desc_parts.append(
  525. " - `--target-table`: Target table name "
  526. "(data resource English name)"
  527. )
  528. task_desc_parts.append(
  529. f" - `--update-mode`: {update_mode}")
  530. task_desc_parts.append(
  531. "4. The Python script will automatically:")
  532. task_desc_parts.append(
  533. " - Connect to the remote data source")
  534. task_desc_parts.append(
  535. " - Extract data from the source table")
  536. task_desc_parts.append(
  537. f" - Write data to target table using "
  538. f"{update_mode} mode"
  539. )
  540. else:
  541. # 数据转换任务的完整步骤
  542. task_desc_parts.append(
  543. "1. Extract data from source tables as "
  544. "specified in the DDL"
  545. )
  546. task_desc_parts.append(
  547. "2. Apply transformation logic according "
  548. "to the rule:"
  549. )
  550. if request_content_str:
  551. task_desc_parts.append(
  552. f" - Rule: {request_content_str}")
  553. task_desc_parts.append(
  554. "3. Generate Python program to implement the "
  555. "data transformation logic"
  556. )
  557. task_desc_parts.append(
  558. f"4. Write transformed data to target table "
  559. f"using {update_mode} mode"
  560. )
  561. task_desc_parts.append(
  562. "5. Create an n8n workflow to schedule and "
  563. "execute the Python program"
  564. )
  565. task_description_md = "\n".join(task_desc_parts)
  566. except Exception as parse_e:
  567. logger.warning(f"解析任务描述详情失败,使用原始描述: {str(parse_e)}")
  568. task_description_md = script_requirement
  569. # 假设运行根目录为项目根目录,dataflows.py在app/core/data_flow/
  570. code_path = 'app/core/data_flow'
  571. task_insert_sql = text(
  572. "INSERT INTO public.task_list\n"
  573. "(task_name, task_description, status, code_name, "
  574. "code_path, create_by, create_time, update_time)\n"
  575. "VALUES\n"
  576. "(:task_name, :task_description, :status, :code_name, "
  577. ":code_path, :create_by, :create_time, :update_time)"
  578. )
  579. task_params = {
  580. 'task_name': script_name,
  581. 'task_description': task_description_md,
  582. 'status': 'pending',
  583. 'code_name': script_name,
  584. 'code_path': code_path,
  585. 'create_by': 'cursor',
  586. 'create_time': current_time,
  587. 'update_time': current_time
  588. }
  589. # 使用嵌套事务,确保task_list插入失败不影响主流程
  590. with db.session.begin_nested():
  591. db.session.execute(task_insert_sql, task_params)
  592. logger.info(f"成功将任务信息写入task_list表: task_name={script_name}")
  593. except Exception as task_error:
  594. # 记录错误但不中断主流程
  595. logger.error(f"写入task_list表失败: {str(task_error)}")
  596. # 如果要求必须成功写入任务列表,则这里应该raise task_error
  597. # raise task_error
  598. db.session.commit()
  599. logger.info(
  600. "成功将脚本信息写入PG数据库: target_table=%s, script_name=%s",
  601. target_table,
  602. script_name,
  603. )
  604. except Exception as e:
  605. db.session.rollback()
  606. logger.error(f"写入PG数据库失败: {str(e)}")
  607. raise e
  608. @staticmethod
  609. def _handle_children_relationships(dataflow_node, children_ids):
  610. """处理子节点关系"""
  611. logger.debug(
  612. "处理子节点关系,原始children_ids: %s, 类型: %s",
  613. children_ids,
  614. type(children_ids),
  615. )
  616. # 确保children_ids是列表格式
  617. if not isinstance(children_ids, (list, tuple)):
  618. if children_ids is not None:
  619. children_ids = [children_ids] # 如果是单个值,转换为列表
  620. logger.debug(f"将单个值转换为列表: {children_ids}")
  621. else:
  622. children_ids = [] # 如果是None,转换为空列表
  623. logger.debug("将None转换为空列表")
  624. for child_id in children_ids:
  625. try:
  626. # 查找子节点
  627. query = "MATCH (n) WHERE id(n) = $child_id RETURN n"
  628. with connect_graph().session() as session:
  629. result = session.run(query, child_id=child_id).data()
  630. if result:
  631. # 获取dataflow_node的ID
  632. dataflow_id = getattr(dataflow_node, 'identity', None)
  633. if dataflow_id is None:
  634. # 如果没有identity属性,从名称查询ID
  635. query_id = (
  636. "MATCH (n:DataFlow) WHERE n.name_zh = "
  637. "$name_zh RETURN id(n) as node_id"
  638. )
  639. id_result = session.run(
  640. query_id,
  641. name_zh=dataflow_node.get('name_zh'),
  642. ).single()
  643. dataflow_id = (
  644. id_result['node_id'] if id_result else None
  645. )
  646. # 创建关系 - 使用ID调用relationship_exists
  647. if dataflow_id and not relationship_exists(
  648. dataflow_id, 'child', child_id
  649. ):
  650. session.run(
  651. "MATCH (a), (b) WHERE id(a) = $dataflow_id "
  652. "AND id(b) = $child_id "
  653. "CREATE (a)-[:child]->(b)",
  654. dataflow_id=dataflow_id,
  655. child_id=child_id,
  656. )
  657. logger.info(
  658. f"创建子节点关系: {dataflow_id} -> {child_id}")
  659. except Exception as e:
  660. logger.warning(f"创建子节点关系失败 {child_id}: {str(e)}")
  661. @staticmethod
  662. def _handle_tag_relationship(dataflow_id, tag_id):
  663. """处理标签关系"""
  664. try:
  665. # 查找标签节点
  666. query = "MATCH (n:DataLabel) WHERE id(n) = $tag_id RETURN n"
  667. with connect_graph().session() as session:
  668. result = session.run(query, tag_id=tag_id).data()
  669. if result:
  670. # 创建关系 - 使用ID调用relationship_exists
  671. if dataflow_id and not relationship_exists(
  672. dataflow_id, 'LABEL', tag_id
  673. ):
  674. session.run(
  675. "MATCH (a), (b) WHERE id(a) = $dataflow_id "
  676. "AND id(b) = $tag_id "
  677. "CREATE (a)-[:LABEL]->(b)",
  678. dataflow_id=dataflow_id,
  679. tag_id=tag_id,
  680. )
  681. logger.info(f"创建标签关系: {dataflow_id} -> {tag_id}")
  682. except Exception as e:
  683. logger.warning(f"创建标签关系失败 {tag_id}: {str(e)}")
  684. @staticmethod
  685. def update_dataflow(
  686. dataflow_id: int,
  687. data: Dict[str, Any],
  688. ) -> Optional[Dict[str, Any]]:
  689. """
  690. 更新数据流
  691. Args:
  692. dataflow_id: 数据流ID
  693. data: 更新的数据
  694. Returns:
  695. 更新后的数据流信息,如果不存在则返回None
  696. """
  697. try:
  698. # 提取 tag 数组(不作为节点属性存储)
  699. tag_list = data.pop('tag', None)
  700. # 查找节点
  701. query = "MATCH (n:DataFlow) WHERE id(n) = $dataflow_id RETURN n"
  702. with connect_graph().session() as session:
  703. result = session.run(query, dataflow_id=dataflow_id).data()
  704. if not result:
  705. return None
  706. # 更新节点属性
  707. update_fields = []
  708. params: Dict[str, Any] = {'dataflow_id': dataflow_id}
  709. for key, value in data.items():
  710. if key not in ['id', 'created_at']: # 保护字段
  711. # 复杂对象序列化为 JSON 字符串
  712. if key in ['config', 'script_requirement']:
  713. if isinstance(value, dict):
  714. value = json.dumps(value, ensure_ascii=False)
  715. update_fields.append(f"n.{key} = ${key}")
  716. params[key] = value
  717. if update_fields:
  718. params['updated_at'] = get_formatted_time()
  719. update_fields.append("n.updated_at = $updated_at")
  720. update_query = f"""
  721. MATCH (n:DataFlow) WHERE id(n) = $dataflow_id
  722. SET {', '.join(update_fields)}
  723. RETURN n, id(n) as node_id
  724. """
  725. result = session.run(update_query, params).data()
  726. # 处理 tag 关系
  727. if tag_list is not None and isinstance(tag_list, list):
  728. # 先删除现有的 LABEL 关系
  729. delete_query = """
  730. MATCH (n:DataFlow)-[r:LABEL]->(:DataLabel)
  731. WHERE id(n) = $dataflow_id
  732. DELETE r
  733. """
  734. session.run(delete_query, dataflow_id=dataflow_id)
  735. logger.info(f"删除数据流 {dataflow_id} 的现有标签关系")
  736. # 为每个 tag 创建新的 LABEL 关系
  737. for tag_item in tag_list:
  738. tag_id = None
  739. if isinstance(tag_item, dict) and 'id' in tag_item:
  740. tag_id = int(tag_item['id'])
  741. elif isinstance(tag_item, (int, str)):
  742. try:
  743. tag_id = int(tag_item)
  744. except (ValueError, TypeError):
  745. pass
  746. if tag_id:
  747. DataFlowService._handle_tag_relationship(
  748. dataflow_id, tag_id
  749. )
  750. if result:
  751. node = result[0]['n']
  752. updated_dataflow = dict(node)
  753. # 使用查询返回的node_id
  754. updated_dataflow['id'] = result[0]['node_id']
  755. logger.info(f"更新数据流成功: ID={dataflow_id}")
  756. return updated_dataflow
  757. return None
  758. except Exception as e:
  759. logger.error(f"更新数据流失败: {str(e)}")
  760. raise e
  761. @staticmethod
  762. def delete_dataflow(dataflow_id: int) -> bool:
  763. """
  764. 删除数据流
  765. Args:
  766. dataflow_id: 数据流ID
  767. Returns:
  768. 删除是否成功
  769. """
  770. try:
  771. # 删除节点及其关系
  772. query = """
  773. MATCH (n:DataFlow) WHERE id(n) = $dataflow_id
  774. DETACH DELETE n
  775. RETURN count(n) as deleted_count
  776. """
  777. with connect_graph().session() as session:
  778. delete_result = session.run(
  779. query, dataflow_id=dataflow_id).single()
  780. result = delete_result['deleted_count'] if delete_result else 0
  781. if result and result > 0:
  782. logger.info(f"删除数据流成功: ID={dataflow_id}")
  783. return True
  784. return False
  785. except Exception as e:
  786. logger.error(f"删除数据流失败: {str(e)}")
  787. raise e
  788. @staticmethod
  789. def execute_dataflow(
  790. dataflow_id: int,
  791. params: Optional[Dict[str, Any]] = None,
  792. ) -> Dict[str, Any]:
  793. """
  794. 执行数据流
  795. Args:
  796. dataflow_id: 数据流ID
  797. params: 执行参数
  798. Returns:
  799. 执行结果信息
  800. """
  801. try:
  802. # 检查数据流是否存在
  803. query = "MATCH (n:DataFlow) WHERE id(n) = $dataflow_id RETURN n"
  804. with connect_graph().session() as session:
  805. result = session.run(query, dataflow_id=dataflow_id).data()
  806. if not result:
  807. raise ValueError(f"数据流不存在: ID={dataflow_id}")
  808. execution_id = (
  809. f"exec_{dataflow_id}_{int(datetime.now().timestamp())}"
  810. )
  811. # TODO: 这里应该实际执行数据流
  812. # 目前返回模拟结果
  813. result = {
  814. 'execution_id': execution_id,
  815. 'dataflow_id': dataflow_id,
  816. 'status': 'running',
  817. 'started_at': datetime.now().isoformat(),
  818. 'params': params or {},
  819. 'progress': 0
  820. }
  821. logger.info(
  822. "开始执行数据流: ID=%s, execution_id=%s",
  823. dataflow_id,
  824. execution_id,
  825. )
  826. return result
  827. except Exception as e:
  828. logger.error(f"执行数据流失败: {str(e)}")
  829. raise e
  830. @staticmethod
  831. def get_dataflow_status(dataflow_id: int) -> Dict[str, Any]:
  832. """
  833. 获取数据流执行状态
  834. Args:
  835. dataflow_id: 数据流ID
  836. Returns:
  837. 执行状态信息
  838. """
  839. try:
  840. # TODO: 这里应该查询实际的执行状态
  841. # 目前返回模拟状态
  842. query = "MATCH (n:DataFlow) WHERE id(n) = $dataflow_id RETURN n"
  843. with connect_graph().session() as session:
  844. result = session.run(query, dataflow_id=dataflow_id).data()
  845. if not result:
  846. raise ValueError(f"数据流不存在: ID={dataflow_id}")
  847. status = ['running', 'completed', 'failed', 'pending'][
  848. dataflow_id % 4
  849. ]
  850. return {
  851. 'dataflow_id': dataflow_id,
  852. 'status': status,
  853. 'progress': (
  854. 100
  855. if status == 'completed'
  856. else (dataflow_id * 10) % 100
  857. ),
  858. 'started_at': datetime.now().isoformat(),
  859. 'completed_at': (
  860. datetime.now().isoformat()
  861. if status == 'completed'
  862. else None
  863. ),
  864. 'error_message': (
  865. '执行过程中发生错误' if status == 'failed' else None
  866. ),
  867. }
  868. except Exception as e:
  869. logger.error(f"获取数据流状态失败: {str(e)}")
  870. raise e
  871. @staticmethod
  872. def get_dataflow_logs(
  873. dataflow_id: int,
  874. page: int = 1,
  875. page_size: int = 50,
  876. ) -> Dict[str, Any]:
  877. """
  878. 获取数据流执行日志
  879. Args:
  880. dataflow_id: 数据流ID
  881. page: 页码
  882. page_size: 每页大小
  883. Returns:
  884. 执行日志列表和分页信息
  885. """
  886. try:
  887. # TODO: 这里应该查询实际的执行日志
  888. # 目前返回模拟日志
  889. query = "MATCH (n:DataFlow) WHERE id(n) = $dataflow_id RETURN n"
  890. with connect_graph().session() as session:
  891. result = session.run(query, dataflow_id=dataflow_id).data()
  892. if not result:
  893. raise ValueError(f"数据流不存在: ID={dataflow_id}")
  894. mock_logs = [
  895. {
  896. 'id': i,
  897. 'timestamp': datetime.now().isoformat(),
  898. 'level': ['INFO', 'WARNING', 'ERROR'][i % 3],
  899. 'message': f'数据流执行日志消息 {i}',
  900. 'component': ['source', 'transform', 'target'][i % 3]
  901. }
  902. for i in range(1, 101)
  903. ]
  904. # 分页处理
  905. total = len(mock_logs)
  906. start = (page - 1) * page_size
  907. end = start + page_size
  908. logs = mock_logs[start:end]
  909. return {
  910. 'logs': logs,
  911. 'pagination': {
  912. 'page': page,
  913. 'page_size': page_size,
  914. 'total': total,
  915. 'total_pages': (total + page_size - 1) // page_size
  916. }
  917. }
  918. except Exception as e:
  919. logger.error(f"获取数据流日志失败: {str(e)}")
  920. raise e
  921. @staticmethod
  922. def create_script(request_data: Union[Dict[str, Any], str]) -> str:
  923. """
  924. 使用Deepseek模型生成SQL脚本
  925. Args:
  926. request_data: 包含input, output, request_content的请求数据字典,或JSON字符串
  927. Returns:
  928. 生成的SQL脚本内容
  929. """
  930. try:
  931. logger.info(f"开始处理脚本生成请求: {request_data}")
  932. logger.info(f"request_data类型: {type(request_data)}")
  933. # 类型检查和处理
  934. if isinstance(request_data, str):
  935. logger.warning(f"request_data是字符串,尝试解析为JSON: {request_data}")
  936. try:
  937. import json
  938. request_data = json.loads(request_data)
  939. except json.JSONDecodeError as e:
  940. raise ValueError(f"无法解析request_data为JSON: {str(e)}")
  941. if not isinstance(request_data, dict):
  942. raise ValueError(
  943. f"request_data必须是字典类型,实际类型: {type(request_data)}")
  944. # 1. 从传入的request_data中解析input, output, request_content内容
  945. input_data = request_data.get('input', '')
  946. output_data = request_data.get('output', '')
  947. request_content = request_data.get('request_data', '')
  948. # 如果request_content是HTML格式,提取纯文本
  949. if request_content and (
  950. request_content.startswith('<p>') or '<' in request_content
  951. ):
  952. # 简单的HTML标签清理
  953. import re
  954. request_content = re.sub(
  955. r'<[^>]+>', '', request_content).strip()
  956. if not input_data or not output_data or not request_content:
  957. raise ValueError(
  958. "缺少必要参数:input='{}', output='{}', "
  959. "request_content='{}' 不能为空".format(
  960. input_data,
  961. output_data,
  962. request_content[:100] if request_content else '',
  963. )
  964. )
  965. logger.info(
  966. "解析得到 - input: %s, output: %s, request_content: %s",
  967. input_data,
  968. output_data,
  969. request_content,
  970. )
  971. # 2. 解析input中的多个数据表并生成源表DDL
  972. source_tables_ddl = []
  973. input_tables = []
  974. if input_data:
  975. tables = [table.strip()
  976. for table in input_data.split(',') if table.strip()]
  977. for table in tables:
  978. ddl = DataFlowService._parse_table_and_get_ddl(
  979. table, 'input')
  980. if ddl:
  981. input_tables.append(table)
  982. source_tables_ddl.append(ddl)
  983. else:
  984. logger.warning(f"无法获取输入表 {table} 的DDL结构")
  985. # 3. 解析output中的数据表并生成目标表DDL
  986. target_table_ddl = ""
  987. if output_data:
  988. target_table_ddl = DataFlowService._parse_table_and_get_ddl(
  989. output_data.strip(), 'output')
  990. if not target_table_ddl:
  991. logger.warning(f"无法获取输出表 {output_data} 的DDL结构")
  992. # 4. 按照Deepseek-prompt.txt的框架构建提示语
  993. prompt_parts = []
  994. # 开场白 - 角色定义
  995. prompt_parts.append(
  996. "你是一名数据库工程师,正在构建一个PostgreSQL数据中的汇总逻辑。"
  997. "请为以下需求生成一段标准的 PostgreSQL SQL 脚本:"
  998. )
  999. # 动态生成源表部分(第1点)
  1000. for i, (table, ddl) in enumerate(
  1001. zip(input_tables, source_tables_ddl), 1
  1002. ):
  1003. table_name = table.split(':')[-1] if ':' in table else table
  1004. prompt_parts.append(f"{i}.有一个源表: {table_name},它的定义语句如下:")
  1005. prompt_parts.append(ddl)
  1006. prompt_parts.append("") # 添加空行分隔
  1007. # 动态生成目标表部分(第2点)
  1008. if target_table_ddl:
  1009. target_table_name = output_data.split(
  1010. ':')[-1] if ':' in output_data else output_data
  1011. next_index = len(input_tables) + 1
  1012. prompt_parts.append(
  1013. f"{next_index}.有一个目标表:{target_table_name},它的定义语句如下:")
  1014. prompt_parts.append(target_table_ddl)
  1015. prompt_parts.append("") # 添加空行分隔
  1016. # 动态生成处理逻辑部分(第3点)
  1017. next_index = (
  1018. len(input_tables) + 2
  1019. if target_table_ddl
  1020. else len(input_tables) + 1
  1021. )
  1022. prompt_parts.append(f"{next_index}.处理逻辑为:{request_content}")
  1023. prompt_parts.append("") # 添加空行分隔
  1024. # 固定的技术要求部分(第4-8点)
  1025. tech_requirements = [
  1026. (
  1027. f"{next_index + 1}.脚本应使用标准的 PostgreSQL 语法,"
  1028. "适合在 Airflow、Python 脚本、或调度系统中调用;"
  1029. ),
  1030. f"{next_index + 2}.无需使用 UPSERT 或 ON CONFLICT",
  1031. f"{next_index + 3}.请直接输出SQL,无需进行解释。",
  1032. (
  1033. f"{next_index + 4}.请给这段sql起个英文名,不少于三个英文单词,使用\"_\"分隔,"
  1034. "采用蛇形命名法。把sql的名字作为注释写在返回的sql中。"
  1035. ),
  1036. (
  1037. f"{next_index + 5}.生成的sql在向目标表插入数据的时候,向create_time字段写入当前日期"
  1038. "时间now(),不用处理update_time字段"
  1039. ),
  1040. ]
  1041. prompt_parts.extend(tech_requirements)
  1042. # 组合完整的提示语
  1043. full_prompt = "\n".join(prompt_parts)
  1044. logger.info(f"构建的完整提示语长度: {len(full_prompt)}")
  1045. logger.info(f"完整提示语内容: {full_prompt}")
  1046. # 5. 调用LLM生成SQL脚本
  1047. logger.info("开始调用Deepseek模型生成SQL脚本")
  1048. script_content = llm_sql(full_prompt)
  1049. if not script_content:
  1050. raise ValueError("Deepseek模型返回空内容")
  1051. # 确保返回的是文本格式
  1052. if not isinstance(script_content, str):
  1053. script_content = str(script_content)
  1054. logger.info(f"SQL脚本生成成功,内容长度: {len(script_content)}")
  1055. return script_content
  1056. except Exception as e:
  1057. logger.error(f"生成SQL脚本失败: {str(e)}")
  1058. raise e
  1059. @staticmethod
  1060. def _parse_table_and_get_ddl(table_str: str, table_type: str) -> str:
  1061. """
  1062. 解析表格式(A:B)并从Neo4j查询元数据生成DDL
  1063. Args:
  1064. table_str: 表格式字符串,格式为"label:name_en"
  1065. table_type: 表类型,用于日志记录(input/output)
  1066. Returns:
  1067. DDL格式的表结构字符串
  1068. """
  1069. try:
  1070. # 解析A:B格式
  1071. if ':' not in table_str:
  1072. logger.error(f"表格式错误,应为'label:name_en'格式: {table_str}")
  1073. return ""
  1074. parts = table_str.split(':', 1)
  1075. if len(parts) != 2:
  1076. logger.error(f"表格式解析失败: {table_str}")
  1077. return ""
  1078. label = parts[0].strip()
  1079. name_en = parts[1].strip()
  1080. if not label or not name_en:
  1081. logger.error(f"标签或英文名为空: label={label}, name_en={name_en}")
  1082. return ""
  1083. logger.info(f"开始查询{table_type}表: label={label}, name_en={name_en}")
  1084. # 从Neo4j查询节点及其关联的元数据
  1085. with connect_graph().session() as session:
  1086. # 查询节点及其关联的元数据
  1087. cypher = f"""
  1088. MATCH (n:{label} {{name_en: $name_en}})
  1089. OPTIONAL MATCH (n)-[:INCLUDES]->(m:DataMeta)
  1090. RETURN n, collect(m) as metadata
  1091. """
  1092. result = session.run(
  1093. cypher, # type: ignore[arg-type]
  1094. {'name_en': name_en},
  1095. )
  1096. record = result.single()
  1097. if not record:
  1098. logger.error(f"未找到节点: label={label}, name_en={name_en}")
  1099. return ""
  1100. node = record['n']
  1101. metadata = record['metadata']
  1102. logger.info(f"找到节点,关联元数据数量: {len(metadata)}")
  1103. # 生成DDL格式的表结构
  1104. ddl_lines = []
  1105. ddl_lines.append(f"CREATE TABLE {name_en} (")
  1106. if metadata:
  1107. column_definitions = []
  1108. for meta in metadata:
  1109. if meta: # 确保meta不为空
  1110. meta_props = dict(meta)
  1111. column_name = meta_props.get(
  1112. 'name_en',
  1113. meta_props.get('name_zh', 'unknown_column'),
  1114. )
  1115. data_type = meta_props.get(
  1116. 'data_type', 'VARCHAR(255)')
  1117. comment = meta_props.get('name_zh', '')
  1118. # 构建列定义
  1119. column_def = f" {column_name} {data_type}"
  1120. if comment:
  1121. column_def += f" COMMENT '{comment}'"
  1122. column_definitions.append(column_def)
  1123. if column_definitions:
  1124. ddl_lines.append(",\n".join(column_definitions))
  1125. else:
  1126. ddl_lines.append(
  1127. " id BIGINT PRIMARY KEY COMMENT '主键ID'")
  1128. else:
  1129. # 如果没有元数据,添加默认列
  1130. ddl_lines.append(
  1131. " id BIGINT PRIMARY KEY COMMENT '主键ID'")
  1132. ddl_lines.append(");")
  1133. # 添加表注释
  1134. node_props = dict(node)
  1135. table_comment = node_props.get(
  1136. 'name_zh', node_props.get('describe', name_en))
  1137. if table_comment and table_comment != name_en:
  1138. ddl_lines.append(
  1139. f"COMMENT ON TABLE {name_en} IS '{table_comment}';")
  1140. ddl_content = "\n".join(ddl_lines)
  1141. logger.info(f"{table_type}表DDL生成成功: {name_en}")
  1142. logger.debug(f"生成的DDL: {ddl_content}")
  1143. return ddl_content
  1144. except Exception as e:
  1145. logger.error(f"解析表格式和生成DDL失败: {str(e)}")
  1146. return ""
  1147. @staticmethod
  1148. def _generate_businessdomain_ddl(
  1149. session,
  1150. bd_id: int,
  1151. is_target: bool = False,
  1152. update_mode: str = 'append',
  1153. ) -> Optional[Dict[str, Any]]:
  1154. """
  1155. 根据BusinessDomain节点ID生成DDL
  1156. Args:
  1157. session: Neo4j session对象
  1158. bd_id: BusinessDomain节点ID
  1159. is_target: 是否为目标表(目标表需要添加create_time字段)
  1160. update_mode: 更新模式(append或full)
  1161. Returns:
  1162. 包含ddl和data_source信息的字典,如果节点不存在则返回None
  1163. """
  1164. try:
  1165. # 查询BusinessDomain节点、元数据、标签关系和数据源关系
  1166. cypher = """
  1167. MATCH (bd:BusinessDomain)
  1168. WHERE id(bd) = $bd_id
  1169. OPTIONAL MATCH (bd)-[:INCLUDES]->(m:DataMeta)
  1170. OPTIONAL MATCH (bd)-[:BELONGS_TO]->(label:DataLabel)
  1171. OPTIONAL MATCH (bd)-[:COME_FROM]->(ds:DataSource)
  1172. RETURN bd,
  1173. collect(DISTINCT m) as metadata,
  1174. label.name_zh as label_name,
  1175. ds.type as ds_type,
  1176. ds.host as ds_host,
  1177. ds.port as ds_port,
  1178. ds.database as ds_database
  1179. """
  1180. result = session.run(cypher, bd_id=bd_id).single()
  1181. if not result or not result['bd']:
  1182. logger.warning(f"未找到ID为 {bd_id} 的BusinessDomain节点")
  1183. return None
  1184. node = result['bd']
  1185. metadata = result['metadata']
  1186. label_name = result['label_name']
  1187. # 生成DDL
  1188. node_props = dict(node)
  1189. table_name = node_props.get('name_en', f'table_{bd_id}')
  1190. ddl_lines = []
  1191. ddl_lines.append(f"CREATE TABLE {table_name} (")
  1192. column_definitions = []
  1193. # 添加元数据列
  1194. if metadata:
  1195. for meta in metadata:
  1196. if meta:
  1197. meta_props = dict(meta)
  1198. column_name = meta_props.get(
  1199. 'name_en',
  1200. meta_props.get('name_zh', 'unknown_column'),
  1201. )
  1202. data_type = meta_props.get('data_type', 'VARCHAR(255)')
  1203. comment = meta_props.get('name_zh', '')
  1204. column_def = f" {column_name} {data_type}"
  1205. if comment:
  1206. column_def += f" COMMENT '{comment}'"
  1207. column_definitions.append(column_def)
  1208. # 如果没有元数据,添加默认主键
  1209. if not column_definitions:
  1210. column_definitions.append(
  1211. " id BIGINT PRIMARY KEY COMMENT '主键ID'")
  1212. # 5. 如果是目标表,添加create_time字段
  1213. if is_target:
  1214. column_definitions.append(
  1215. " create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP "
  1216. "COMMENT '数据创建时间'"
  1217. )
  1218. ddl_lines.append(",\n".join(column_definitions))
  1219. ddl_lines.append(");")
  1220. # 添加表注释
  1221. table_comment = node_props.get(
  1222. 'name_zh', node_props.get('describe', table_name))
  1223. if table_comment and table_comment != table_name:
  1224. ddl_lines.append(
  1225. f"COMMENT ON TABLE {table_name} IS '{table_comment}';")
  1226. ddl_content = "\n".join(ddl_lines)
  1227. # 3. 检查BELONGS_TO关系是否连接"数据资源",如果是则返回数据源信息
  1228. data_source = None
  1229. if label_name == '数据资源' and result['ds_type']:
  1230. data_source = {
  1231. 'type': result['ds_type'],
  1232. 'host': result['ds_host'],
  1233. 'port': result['ds_port'],
  1234. 'database': result['ds_database']
  1235. }
  1236. logger.info(f"获取到数据源信息: {data_source}")
  1237. logger.debug(
  1238. f"生成BusinessDomain DDL成功: {table_name}, is_target={is_target}")
  1239. return {
  1240. 'ddl': ddl_content,
  1241. 'table_name': table_name,
  1242. 'data_source': data_source
  1243. }
  1244. except Exception as e:
  1245. logger.error(f"生成BusinessDomain DDL失败,ID={bd_id}: {str(e)}")
  1246. return None
  1247. @staticmethod
  1248. def _handle_script_relationships(
  1249. data: Dict[str, Any],
  1250. dataflow_name: str,
  1251. name_en: str,
  1252. ):
  1253. """
  1254. 处理脚本关系,在Neo4j图数据库中创建从source_table到target_table之间的
  1255. DERIVED_FROM关系
  1256. Args:
  1257. data: 包含脚本信息的数据字典,应包含script_name, script_type,
  1258. schedule_status, source_table, target_table, update_mode
  1259. """
  1260. try:
  1261. # 从data中读取键值对
  1262. script_name = dataflow_name,
  1263. script_type = data.get('script_type', 'sql')
  1264. schedule_status = data.get('status', 'inactive')
  1265. source_table_full = data.get('source_table', '')
  1266. target_table_full = data.get('target_table', '')
  1267. update_mode = data.get('update_mode', 'full')
  1268. # 处理source_table和target_table的格式
  1269. source_table = source_table_full.split(
  1270. ':')[-1] if ':' in source_table_full else source_table_full
  1271. target_table = target_table_full.split(
  1272. ':')[-1] if ':' in target_table_full else target_table_full
  1273. source_label = source_table_full.split(
  1274. ':')[0] if ':' in source_table_full else source_table_full
  1275. target_label = target_table_full.split(
  1276. ':')[0] if ':' in target_table_full else target_table_full
  1277. # 验证必要字段
  1278. if not source_table or not target_table:
  1279. logger.warning(
  1280. "source_table或target_table为空,跳过关系创建: "
  1281. "source_table=%s, target_table=%s",
  1282. source_table,
  1283. target_table,
  1284. )
  1285. return
  1286. logger.info(f"开始创建脚本关系: {source_table} -> {target_table}")
  1287. with connect_graph().session() as session:
  1288. # 创建或获取source和target节点
  1289. create_nodes_query = f"""
  1290. MERGE (source:{source_label} {{name: $source_table}})
  1291. ON CREATE SET source.created_at = $created_at,
  1292. source.type = 'source'
  1293. WITH source
  1294. MERGE (target:{target_label} {{name: $target_table}})
  1295. ON CREATE SET target.created_at = $created_at,
  1296. target.type = 'target'
  1297. RETURN source, target, id(source) as source_id,
  1298. id(target) as target_id
  1299. """
  1300. # 执行创建节点的查询
  1301. result = session.run(
  1302. create_nodes_query, # type: ignore[arg-type]
  1303. {
  1304. 'source_table': source_table,
  1305. 'target_table': target_table,
  1306. 'created_at': get_formatted_time(),
  1307. },
  1308. ).single()
  1309. if result:
  1310. source_id = result['source_id']
  1311. target_id = result['target_id']
  1312. # 检查并创建关系
  1313. create_relationship_query = f"""
  1314. MATCH (source:{source_label}), (target:{target_label})
  1315. WHERE id(source) = $source_id AND id(target) = $target_id
  1316. AND NOT EXISTS((target)-[:DERIVED_FROM]->(source))
  1317. CREATE (target)-[r:DERIVED_FROM]->(source)
  1318. SET r.script_name = $script_name,
  1319. r.script_type = $script_type,
  1320. r.schedule_status = $schedule_status,
  1321. r.update_mode = $update_mode,
  1322. r.created_at = $created_at,
  1323. r.updated_at = $created_at
  1324. RETURN r
  1325. """
  1326. relationship_result = session.run(
  1327. create_relationship_query, # type: ignore[arg-type]
  1328. {
  1329. 'source_id': source_id,
  1330. 'target_id': target_id,
  1331. 'script_name': script_name,
  1332. 'script_type': script_type,
  1333. 'schedule_status': schedule_status,
  1334. 'update_mode': update_mode,
  1335. 'created_at': get_formatted_time(),
  1336. },
  1337. ).single()
  1338. if relationship_result:
  1339. logger.info(
  1340. "成功创建DERIVED_FROM关系: %s -> %s (script: %s)",
  1341. target_table,
  1342. source_table,
  1343. script_name,
  1344. )
  1345. else:
  1346. logger.info(
  1347. "DERIVED_FROM关系已存在: %s -> %s",
  1348. target_table,
  1349. source_table,
  1350. )
  1351. else:
  1352. logger.error(
  1353. "创建表节点失败: source_table=%s, target_table=%s",
  1354. source_table,
  1355. target_table,
  1356. )
  1357. except Exception as e:
  1358. logger.error(f"处理脚本关系失败: {str(e)}")
  1359. raise e
  1360. @staticmethod
  1361. def get_business_domain_list() -> List[Dict[str, Any]]:
  1362. """
  1363. 获取BusinessDomain节点列表
  1364. Returns:
  1365. BusinessDomain节点列表,每个节点包含 id, name_zh, name_en, tag
  1366. """
  1367. try:
  1368. logger.info("开始查询BusinessDomain节点列表")
  1369. with connect_graph().session() as session:
  1370. # 查询所有BusinessDomain节点及其BELONGS_TO关系指向的标签
  1371. query = """
  1372. MATCH (bd:BusinessDomain)
  1373. OPTIONAL MATCH (bd)-[:BELONGS_TO]->(label:DataLabel)
  1374. RETURN id(bd) as id,
  1375. bd.name_zh as name_zh,
  1376. bd.name_en as name_en,
  1377. label.name_zh as tag
  1378. ORDER BY bd.create_time DESC
  1379. """
  1380. result = session.run(query)
  1381. bd_list = []
  1382. for record in result:
  1383. bd_item = {
  1384. "id": record["id"],
  1385. "name_zh": record.get("name_zh", "") or "",
  1386. "name_en": record.get("name_en", "") or "",
  1387. "tag": record.get("tag", "") or "",
  1388. }
  1389. bd_list.append(bd_item)
  1390. logger.info(f"成功查询到 {len(bd_list)} 个BusinessDomain节点")
  1391. return bd_list
  1392. except Exception as e:
  1393. logger.error(f"查询BusinessDomain节点列表失败: {str(e)}")
  1394. raise e