dataflows.py 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081
  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_client, llm_sql
  6. from app.core.graph.graph_operations import connect_graph, create_or_get_node, get_node, relationship_exists
  7. from app.core.meta_data import translate_and_parse, get_formatted_time
  8. from py2neo import Relationship
  9. from app import db
  10. from sqlalchemy import text
  11. logger = logging.getLogger(__name__)
  12. class DataFlowService:
  13. """数据流服务类,处理数据流相关的业务逻辑"""
  14. @staticmethod
  15. def get_dataflows(page: int = 1, page_size: int = 10, search: str = '') -> Dict[str, Any]:
  16. """
  17. 获取数据流列表
  18. Args:
  19. page: 页码
  20. page_size: 每页大小
  21. search: 搜索关键词
  22. Returns:
  23. 包含数据流列表和分页信息的字典
  24. """
  25. try:
  26. # 从图数据库查询数据流列表
  27. skip_count = (page - 1) * page_size
  28. # 构建搜索条件
  29. where_clause = ""
  30. params: Dict[str, Union[int, str]] = {'skip': skip_count, 'limit': page_size}
  31. if search:
  32. where_clause = "WHERE n.name_zh CONTAINS $search OR n.description CONTAINS $search"
  33. params['search'] = search
  34. # 查询数据流列表
  35. query = f"""
  36. MATCH (n:DataFlow)
  37. {where_clause}
  38. RETURN n, id(n) as node_id
  39. ORDER BY n.created_at DESC
  40. SKIP $skip
  41. LIMIT $limit
  42. """
  43. # 获取Neo4j驱动(如果连接失败会抛出ConnectionError异常)
  44. try:
  45. with connect_graph().session() as session:
  46. list_result = session.run(query, params).data()
  47. # 查询总数
  48. count_query = f"""
  49. MATCH (n:DataFlow)
  50. {where_clause}
  51. RETURN count(n) as total
  52. """
  53. count_params = {'search': search} if search else {}
  54. count_result = session.run(count_query, count_params).single()
  55. total = count_result['total'] if count_result else 0
  56. except Exception as e:
  57. # 确保 driver 被正确关闭,避免资源泄漏 - 这里不再需要手动关闭driver,因为connect_graph返回的可能是单例或新实例,
  58. # 但如果是新实例,我们没有引用它去关闭。如果connect_graph设计为每次返回新实例且需要关闭,
  59. # 那么之前的代码是对的。如果connect_graph返回单例,则不应关闭。
  60. # 根据用户反馈:The driver.close() call prematurely closes a shared driver instance.
  61. # 所以我们直接使用 session,并不关闭 driver。
  62. logger.error(f"查询数据流失败: {str(e)}")
  63. raise e
  64. # 格式化结果
  65. dataflows = []
  66. for record in list_result:
  67. node = record['n']
  68. dataflow = dict(node)
  69. dataflow['id'] = record['node_id'] # 使用查询返回的node_id
  70. dataflows.append(dataflow)
  71. return {
  72. 'list': dataflows,
  73. 'pagination': {
  74. 'page': page,
  75. 'page_size': page_size,
  76. 'total': total,
  77. 'total_pages': (total + page_size - 1) // page_size
  78. }
  79. }
  80. except Exception as e:
  81. logger.error(f"获取数据流列表失败: {str(e)}")
  82. raise e
  83. @staticmethod
  84. def get_dataflow_by_id(dataflow_id: int) -> Optional[Dict[str, Any]]:
  85. """
  86. 根据ID获取数据流详情
  87. Args:
  88. dataflow_id: 数据流ID
  89. Returns:
  90. 数据流详情字典,如果不存在则返回None
  91. """
  92. try:
  93. # 从Neo4j获取基本信息
  94. neo4j_query = """
  95. MATCH (n:DataFlow)
  96. WHERE id(n) = $dataflow_id
  97. OPTIONAL MATCH (n)-[:LABEL]-(la:DataLabel)
  98. RETURN n, id(n) as node_id,
  99. collect(DISTINCT {id: id(la), name: la.name}) as tags
  100. """
  101. with connect_graph().session() as session:
  102. neo4j_result = session.run(neo4j_query, dataflow_id=dataflow_id).data()
  103. if not neo4j_result:
  104. return None
  105. record = neo4j_result[0]
  106. node = record['n']
  107. dataflow = dict(node)
  108. dataflow['id'] = record['node_id']
  109. dataflow['tags'] = record['tags']
  110. # 从PostgreSQL获取额外信息
  111. pg_query = """
  112. SELECT
  113. source_table,
  114. target_table,
  115. script_name,
  116. script_type,
  117. script_requirement,
  118. script_content,
  119. user_name,
  120. create_time,
  121. update_time,
  122. target_dt_column
  123. FROM dags.data_transform_scripts
  124. WHERE script_name = :script_name
  125. """
  126. with db.engine.connect() as conn:
  127. pg_result = conn.execute(text(pg_query), {"script_name": dataflow.get('name_zh')}).fetchone()
  128. if pg_result:
  129. # 将PostgreSQL数据添加到结果中
  130. dataflow.update({
  131. 'source_table': pg_result.source_table,
  132. 'target_table': pg_result.target_table,
  133. 'script_type': pg_result.script_type,
  134. 'script_requirement': pg_result.script_requirement,
  135. 'script_content': pg_result.script_content,
  136. 'created_by': pg_result.user_name,
  137. 'pg_created_at': pg_result.create_time,
  138. 'pg_updated_at': pg_result.update_time,
  139. 'target_dt_column': pg_result.target_dt_column
  140. })
  141. return dataflow
  142. except Exception as e:
  143. logger.error(f"获取数据流详情失败: {str(e)}")
  144. raise e
  145. @staticmethod
  146. def create_dataflow(data: Dict[str, Any]) -> Dict[str, Any]:
  147. """
  148. 创建新的数据流
  149. Args:
  150. data: 数据流配置数据
  151. Returns:
  152. 创建的数据流信息
  153. """
  154. try:
  155. # 验证必填字段
  156. required_fields = ['name_zh', 'describe']
  157. for field in required_fields:
  158. if field not in data:
  159. raise ValueError(f"缺少必填字段: {field}")
  160. dataflow_name = data['name_zh']
  161. # 使用LLM翻译名称生成英文名
  162. try:
  163. result_list = translate_and_parse(dataflow_name)
  164. name_en = result_list[0] if result_list else dataflow_name.lower().replace(' ', '_')
  165. except Exception as e:
  166. logger.warning(f"翻译失败,使用默认英文名: {str(e)}")
  167. name_en = dataflow_name.lower().replace(' ', '_')
  168. # 准备节点数据
  169. node_data = {
  170. 'name_zh': dataflow_name,
  171. 'name_en': name_en,
  172. 'category': data.get('category', ''),
  173. 'organization': data.get('organization', ''),
  174. 'leader': data.get('leader', ''),
  175. 'frequency': data.get('frequency', ''),
  176. 'tag': data.get('tag', ''),
  177. 'describe': data.get('describe', ''),
  178. 'status': data.get('status', 'inactive'),
  179. 'update_mode': data.get('update_mode', 'append'),
  180. 'created_at': get_formatted_time(),
  181. 'updated_at': get_formatted_time()
  182. }
  183. # 创建或获取数据流节点
  184. dataflow_id = get_node('DataFlow', name=dataflow_name)
  185. if dataflow_id:
  186. raise ValueError(f"数据流 '{dataflow_name}' 已存在")
  187. dataflow_id = create_or_get_node('DataFlow', **node_data)
  188. # 处理标签关系
  189. tag_id = data.get('tag')
  190. if tag_id is not None:
  191. try:
  192. DataFlowService._handle_tag_relationship(dataflow_id, tag_id)
  193. except Exception as e:
  194. logger.warning(f"处理标签关系时出错: {str(e)}")
  195. # 成功创建图数据库节点后,写入PG数据库
  196. try:
  197. DataFlowService._save_to_pg_database(data, dataflow_name, name_en)
  198. logger.info(f"数据流信息已写入PG数据库: {dataflow_name}")
  199. # PG数据库记录成功写入后,在neo4j图数据库中创建script关系
  200. try:
  201. DataFlowService._handle_script_relationships(data,dataflow_name,name_en)
  202. logger.info(f"脚本关系创建成功: {dataflow_name}")
  203. except Exception as script_error:
  204. logger.warning(f"创建脚本关系失败: {str(script_error)}")
  205. except Exception as pg_error:
  206. logger.error(f"写入PG数据库失败: {str(pg_error)}")
  207. # 注意:这里可以选择回滚图数据库操作,但目前保持图数据库数据
  208. # 在实际应用中,可能需要考虑分布式事务
  209. # 返回创建的数据流信息
  210. # 查询创建的节点获取完整信息
  211. query = "MATCH (n:DataFlow {name_zh: $name_zh}) RETURN n, id(n) as node_id"
  212. with connect_graph().session() as session:
  213. id_result = session.run(query, name_zh=dataflow_name).single()
  214. if id_result:
  215. dataflow_node = id_result['n']
  216. node_id = id_result['node_id']
  217. # 将节点属性转换为字典
  218. result = dict(dataflow_node)
  219. result['id'] = node_id
  220. else:
  221. # 如果查询失败,返回基本信息
  222. result = {
  223. 'id': dataflow_id if isinstance(dataflow_id, int) else None,
  224. 'name_zh': dataflow_name,
  225. 'name_en': name_en,
  226. 'created_at': get_formatted_time()
  227. }
  228. logger.info(f"创建数据流成功: {dataflow_name}")
  229. return result
  230. except Exception as e:
  231. logger.error(f"创建数据流失败: {str(e)}")
  232. raise e
  233. @staticmethod
  234. def _save_to_pg_database(data: Dict[str, Any], script_name: str, name_en: str):
  235. """
  236. 将脚本信息保存到PG数据库
  237. Args:
  238. data: 包含脚本信息的数据
  239. script_name: 脚本名称
  240. name_en: 英文名称
  241. """
  242. try:
  243. # 提取脚本相关信息
  244. script_requirement = data.get('script_requirement', '')
  245. script_content = data.get('script_content', '')
  246. # 安全处理 source_table 和 target_table(避免 None 值导致的 'in' 操作错误)
  247. source_table_raw = data.get('source_table') or ''
  248. source_table = source_table_raw.split(':')[-1] if ':' in source_table_raw else source_table_raw
  249. target_table_raw = data.get('target_table') or ''
  250. target_table = target_table_raw.split(':')[-1] if ':' in target_table_raw else (target_table_raw or name_en)
  251. script_type = data.get('script_type', 'python')
  252. user_name = data.get('created_by', 'system')
  253. target_dt_column = data.get('target_dt_column', '')
  254. # 验证必需字段
  255. if not target_table:
  256. target_table = name_en
  257. if not script_name:
  258. raise ValueError("script_name不能为空")
  259. # 构建插入SQL
  260. insert_sql = text("""
  261. INSERT INTO dags.data_transform_scripts
  262. (source_table, target_table, script_name, script_type, script_requirement,
  263. script_content, user_name, create_time, update_time, target_dt_column)
  264. VALUES
  265. (:source_table, :target_table, :script_name, :script_type, :script_requirement,
  266. :script_content, :user_name, :create_time, :update_time, :target_dt_column)
  267. ON CONFLICT (target_table, script_name)
  268. DO UPDATE SET
  269. source_table = EXCLUDED.source_table,
  270. script_type = EXCLUDED.script_type,
  271. script_requirement = EXCLUDED.script_requirement,
  272. script_content = EXCLUDED.script_content,
  273. user_name = EXCLUDED.user_name,
  274. update_time = EXCLUDED.update_time,
  275. target_dt_column = EXCLUDED.target_dt_column
  276. """)
  277. # 准备参数
  278. current_time = datetime.now()
  279. params = {
  280. 'source_table': source_table,
  281. 'target_table': target_table,
  282. 'script_name': script_name,
  283. 'script_type': script_type,
  284. 'script_requirement': script_requirement,
  285. 'script_content': script_content,
  286. 'user_name': user_name,
  287. 'create_time': current_time,
  288. 'update_time': current_time,
  289. 'target_dt_column': target_dt_column
  290. }
  291. # 执行插入操作
  292. db.session.execute(insert_sql, params)
  293. # 新增:保存到task_list表
  294. try:
  295. # 1. 解析script_requirement并构建详细的任务描述
  296. task_description_md = script_requirement
  297. try:
  298. # 尝试解析JSON
  299. import json
  300. try:
  301. req_json = json.loads(script_requirement)
  302. except (json.JSONDecodeError, TypeError):
  303. req_json = None
  304. if isinstance(req_json, dict):
  305. # 提取字段
  306. business_domains = []
  307. bd_str = req_json.get('business_domain', '')
  308. if bd_str:
  309. business_domains = [d.strip() for d in bd_str.split(',') if d.strip()]
  310. data_source = req_json.get('data_source', '')
  311. request_content_str = req_json.get('request_content', '')
  312. # 生成Business Domain DDLs
  313. domain_ddls = []
  314. if business_domains:
  315. try:
  316. with connect_graph().session() as session:
  317. for domain in business_domains:
  318. # 查询BusinessDomain节点及元数据
  319. # 尝试匹配name, name_zh, name_en
  320. cypher = """
  321. MATCH (n:BusinessDomain)
  322. WHERE n.name = $name OR n.name_zh = $name OR n.name_en = $name
  323. OPTIONAL MATCH (n)-[:INCLUDES]->(m:DataMeta)
  324. RETURN n, collect(m) as metadata
  325. """
  326. result = session.run(cypher, name=domain).single()
  327. if result:
  328. node = result['n']
  329. metadata = result['metadata']
  330. # 生成DDL
  331. node_props = dict(node)
  332. # 优先使用英文名作为表名,如果没有则使用拼音或原始名称
  333. table_name = node_props.get('name_en', domain)
  334. ddl_lines = []
  335. ddl_lines.append(f"CREATE TABLE {table_name} (")
  336. if metadata:
  337. column_definitions = []
  338. for meta in metadata:
  339. if meta:
  340. meta_props = dict(meta)
  341. column_name = meta_props.get('name_en', meta_props.get('name_zh', 'unknown_column'))
  342. data_type = meta_props.get('data_type', 'VARCHAR(255)')
  343. comment = meta_props.get('name_zh', '')
  344. column_def = f" {column_name} {data_type}"
  345. if comment:
  346. column_def += f" COMMENT '{comment}'"
  347. column_definitions.append(column_def)
  348. if column_definitions:
  349. ddl_lines.append(",\n".join(column_definitions))
  350. else:
  351. ddl_lines.append(" id BIGINT PRIMARY KEY COMMENT '主键ID'")
  352. else:
  353. ddl_lines.append(" id BIGINT PRIMARY KEY COMMENT '主键ID'")
  354. ddl_lines.append(");")
  355. table_comment = node_props.get('name_zh', node_props.get('describe', table_name))
  356. if table_comment and table_comment != table_name:
  357. ddl_lines.append(f"COMMENT ON TABLE {table_name} IS '{table_comment}';")
  358. domain_ddls.append("\n".join(ddl_lines))
  359. except Exception as neo_e:
  360. logger.error(f"获取BusinessDomain DDL失败: {str(neo_e)}")
  361. # 构建Markdown格式
  362. task_desc_parts = [f"# Task: {script_name}\n"]
  363. if data_source:
  364. task_desc_parts.append(f"## Data Source\n{data_source}\n")
  365. if domain_ddls:
  366. task_desc_parts.append("## Business Domain Structures (DDL)")
  367. for ddl in domain_ddls:
  368. task_desc_parts.append(f"```sql\n{ddl}\n```\n")
  369. task_desc_parts.append(f"## Request Content\n{request_content_str}\n")
  370. task_desc_parts.append("## Implementation Steps")
  371. task_desc_parts.append("1. Generate a Python program to implement the logic.")
  372. task_desc_parts.append("2. Generate an n8n workflow to schedule and execute the Python program.")
  373. task_description_md = "\n".join(task_desc_parts)
  374. except Exception as parse_e:
  375. logger.warning(f"解析任务描述详情失败,使用原始描述: {str(parse_e)}")
  376. task_description_md = script_requirement
  377. # 假设运行根目录为项目根目录,dataflows.py在app/core/data_flow/
  378. code_path = 'app/core/data_flow'
  379. task_insert_sql = text("""
  380. INSERT INTO public.task_list
  381. (task_name, task_description, status, code_name, code_path, create_by, create_time, update_time)
  382. VALUES
  383. (:task_name, :task_description, :status, :code_name, :code_path, :create_by, :create_time, :update_time)
  384. """)
  385. task_params = {
  386. 'task_name': script_name,
  387. 'task_description': task_description_md,
  388. 'status': 'pending',
  389. 'code_name': script_name,
  390. 'code_path': code_path,
  391. 'create_by': 'cursor',
  392. 'create_time': current_time,
  393. 'update_time': current_time
  394. }
  395. # 使用嵌套事务,确保task_list插入失败不影响主流程
  396. with db.session.begin_nested():
  397. db.session.execute(task_insert_sql, task_params)
  398. logger.info(f"成功将任务信息写入task_list表: task_name={script_name}")
  399. except Exception as task_error:
  400. # 记录错误但不中断主流程
  401. logger.error(f"写入task_list表失败: {str(task_error)}")
  402. # 如果要求必须成功写入任务列表,则这里应该raise task_error
  403. # raise task_error
  404. db.session.commit()
  405. logger.info(f"成功将脚本信息写入PG数据库: target_table={target_table}, script_name={script_name}")
  406. except Exception as e:
  407. db.session.rollback()
  408. logger.error(f"写入PG数据库失败: {str(e)}")
  409. raise e
  410. @staticmethod
  411. def _handle_children_relationships(dataflow_node, children_ids):
  412. """处理子节点关系"""
  413. logger.debug(f"处理子节点关系,原始children_ids: {children_ids}, 类型: {type(children_ids)}")
  414. # 确保children_ids是列表格式
  415. if not isinstance(children_ids, (list, tuple)):
  416. if children_ids is not None:
  417. children_ids = [children_ids] # 如果是单个值,转换为列表
  418. logger.debug(f"将单个值转换为列表: {children_ids}")
  419. else:
  420. children_ids = [] # 如果是None,转换为空列表
  421. logger.debug("将None转换为空列表")
  422. for child_id in children_ids:
  423. try:
  424. # 查找子节点
  425. query = "MATCH (n) WHERE id(n) = $child_id RETURN n"
  426. with connect_graph().session() as session:
  427. result = session.run(query, child_id=child_id).data()
  428. if result:
  429. child_node = result[0]['n']
  430. # 获取dataflow_node的ID
  431. dataflow_id = getattr(dataflow_node, 'identity', None)
  432. if dataflow_id is None:
  433. # 如果没有identity属性,从名称查询ID
  434. query_id = "MATCH (n:DataFlow) WHERE n.name_zh = $name_zh RETURN id(n) as node_id"
  435. id_result = session.run(query_id, name_zh=dataflow_node.get('name_zh')).single()
  436. dataflow_id = id_result['node_id'] if id_result else None
  437. # 创建关系 - 使用ID调用relationship_exists
  438. if dataflow_id and not relationship_exists(dataflow_id, 'child', child_id):
  439. session.run("MATCH (a), (b) WHERE id(a) = $dataflow_id AND id(b) = $child_id CREATE (a)-[:child]->(b)",
  440. dataflow_id=dataflow_id, child_id=child_id)
  441. logger.info(f"创建子节点关系: {dataflow_id} -> {child_id}")
  442. except Exception as e:
  443. logger.warning(f"创建子节点关系失败 {child_id}: {str(e)}")
  444. @staticmethod
  445. def _handle_tag_relationship(dataflow_id, tag_id):
  446. """处理标签关系"""
  447. try:
  448. # 查找标签节点
  449. query = "MATCH (n:DataLabel) WHERE id(n) = $tag_id RETURN n"
  450. with connect_graph().session() as session:
  451. result = session.run(query, tag_id=tag_id).data()
  452. if result:
  453. tag_node = result[0]['n']
  454. # 创建关系 - 使用ID调用relationship_exists
  455. if dataflow_id and not relationship_exists(dataflow_id, 'LABEL', tag_id):
  456. session.run("MATCH (a), (b) WHERE id(a) = $dataflow_id AND id(b) = $tag_id CREATE (a)-[:LABEL]->(b)",
  457. dataflow_id=dataflow_id, tag_id=tag_id)
  458. logger.info(f"创建标签关系: {dataflow_id} -> {tag_id}")
  459. except Exception as e:
  460. logger.warning(f"创建标签关系失败 {tag_id}: {str(e)}")
  461. @staticmethod
  462. def update_dataflow(dataflow_id: int, data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
  463. """
  464. 更新数据流
  465. Args:
  466. dataflow_id: 数据流ID
  467. data: 更新的数据
  468. Returns:
  469. 更新后的数据流信息,如果不存在则返回None
  470. """
  471. try:
  472. # 查找节点
  473. query = "MATCH (n:DataFlow) WHERE id(n) = $dataflow_id RETURN n"
  474. with connect_graph().session() as session:
  475. result = session.run(query, dataflow_id=dataflow_id).data()
  476. if not result:
  477. return None
  478. # 更新节点属性
  479. update_fields = []
  480. params: Dict[str, Any] = {'dataflow_id': dataflow_id}
  481. for key, value in data.items():
  482. if key not in ['id', 'created_at']: # 保护字段
  483. if key == 'config' and isinstance(value, dict):
  484. value = json.dumps(value, ensure_ascii=False)
  485. update_fields.append(f"n.{key} = ${key}")
  486. params[key] = value
  487. if update_fields:
  488. params['updated_at'] = get_formatted_time()
  489. update_fields.append("n.updated_at = $updated_at")
  490. update_query = f"""
  491. MATCH (n:DataFlow) WHERE id(n) = $dataflow_id
  492. SET {', '.join(update_fields)}
  493. RETURN n, id(n) as node_id
  494. """
  495. result = session.run(update_query, params).data()
  496. if result:
  497. node = result[0]['n']
  498. updated_dataflow = dict(node)
  499. updated_dataflow['id'] = result[0]['node_id'] # 使用查询返回的node_id
  500. logger.info(f"更新数据流成功: ID={dataflow_id}")
  501. return updated_dataflow
  502. return None
  503. except Exception as e:
  504. logger.error(f"更新数据流失败: {str(e)}")
  505. raise e
  506. @staticmethod
  507. def delete_dataflow(dataflow_id: int) -> bool:
  508. """
  509. 删除数据流
  510. Args:
  511. dataflow_id: 数据流ID
  512. Returns:
  513. 删除是否成功
  514. """
  515. try:
  516. # 删除节点及其关系
  517. query = """
  518. MATCH (n:DataFlow) WHERE id(n) = $dataflow_id
  519. DETACH DELETE n
  520. RETURN count(n) as deleted_count
  521. """
  522. with connect_graph().session() as session:
  523. delete_result = session.run(query, dataflow_id=dataflow_id).single()
  524. result = delete_result['deleted_count'] if delete_result else 0
  525. if result and result > 0:
  526. logger.info(f"删除数据流成功: ID={dataflow_id}")
  527. return True
  528. return False
  529. except Exception as e:
  530. logger.error(f"删除数据流失败: {str(e)}")
  531. raise e
  532. @staticmethod
  533. def execute_dataflow(dataflow_id: int, params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
  534. """
  535. 执行数据流
  536. Args:
  537. dataflow_id: 数据流ID
  538. params: 执行参数
  539. Returns:
  540. 执行结果信息
  541. """
  542. try:
  543. # 检查数据流是否存在
  544. query = "MATCH (n:DataFlow) WHERE id(n) = $dataflow_id RETURN n"
  545. with connect_graph().session() as session:
  546. result = session.run(query, dataflow_id=dataflow_id).data()
  547. if not result:
  548. raise ValueError(f"数据流不存在: ID={dataflow_id}")
  549. execution_id = f"exec_{dataflow_id}_{int(datetime.now().timestamp())}"
  550. # TODO: 这里应该实际执行数据流
  551. # 目前返回模拟结果
  552. result = {
  553. 'execution_id': execution_id,
  554. 'dataflow_id': dataflow_id,
  555. 'status': 'running',
  556. 'started_at': datetime.now().isoformat(),
  557. 'params': params or {},
  558. 'progress': 0
  559. }
  560. logger.info(f"开始执行数据流: ID={dataflow_id}, execution_id={execution_id}")
  561. return result
  562. except Exception as e:
  563. logger.error(f"执行数据流失败: {str(e)}")
  564. raise e
  565. @staticmethod
  566. def get_dataflow_status(dataflow_id: int) -> Dict[str, Any]:
  567. """
  568. 获取数据流执行状态
  569. Args:
  570. dataflow_id: 数据流ID
  571. Returns:
  572. 执行状态信息
  573. """
  574. try:
  575. # TODO: 这里应该查询实际的执行状态
  576. # 目前返回模拟状态
  577. query = "MATCH (n:DataFlow) WHERE id(n) = $dataflow_id RETURN n"
  578. with connect_graph().session() as session:
  579. result = session.run(query, dataflow_id=dataflow_id).data()
  580. if not result:
  581. raise ValueError(f"数据流不存在: ID={dataflow_id}")
  582. status = ['running', 'completed', 'failed', 'pending'][dataflow_id % 4]
  583. return {
  584. 'dataflow_id': dataflow_id,
  585. 'status': status,
  586. 'progress': 100 if status == 'completed' else (dataflow_id * 10) % 100,
  587. 'started_at': datetime.now().isoformat(),
  588. 'completed_at': datetime.now().isoformat() if status == 'completed' else None,
  589. 'error_message': '执行过程中发生错误' if status == 'failed' else None
  590. }
  591. except Exception as e:
  592. logger.error(f"获取数据流状态失败: {str(e)}")
  593. raise e
  594. @staticmethod
  595. def get_dataflow_logs(dataflow_id: int, page: int = 1, page_size: int = 50) -> Dict[str, Any]:
  596. """
  597. 获取数据流执行日志
  598. Args:
  599. dataflow_id: 数据流ID
  600. page: 页码
  601. page_size: 每页大小
  602. Returns:
  603. 执行日志列表和分页信息
  604. """
  605. try:
  606. # TODO: 这里应该查询实际的执行日志
  607. # 目前返回模拟日志
  608. query = "MATCH (n:DataFlow) WHERE id(n) = $dataflow_id RETURN n"
  609. with connect_graph().session() as session:
  610. result = session.run(query, dataflow_id=dataflow_id).data()
  611. if not result:
  612. raise ValueError(f"数据流不存在: ID={dataflow_id}")
  613. mock_logs = [
  614. {
  615. 'id': i,
  616. 'timestamp': datetime.now().isoformat(),
  617. 'level': ['INFO', 'WARNING', 'ERROR'][i % 3],
  618. 'message': f'数据流执行日志消息 {i}',
  619. 'component': ['source', 'transform', 'target'][i % 3]
  620. }
  621. for i in range(1, 101)
  622. ]
  623. # 分页处理
  624. total = len(mock_logs)
  625. start = (page - 1) * page_size
  626. end = start + page_size
  627. logs = mock_logs[start:end]
  628. return {
  629. 'logs': logs,
  630. 'pagination': {
  631. 'page': page,
  632. 'page_size': page_size,
  633. 'total': total,
  634. 'total_pages': (total + page_size - 1) // page_size
  635. }
  636. }
  637. except Exception as e:
  638. logger.error(f"获取数据流日志失败: {str(e)}")
  639. raise e
  640. @staticmethod
  641. def create_script(request_data: Union[Dict[str, Any], str]) -> str:
  642. """
  643. 使用Deepseek模型生成SQL脚本
  644. Args:
  645. request_data: 包含input, output, request_content的请求数据字典,或JSON字符串
  646. Returns:
  647. 生成的SQL脚本内容
  648. """
  649. try:
  650. logger.info(f"开始处理脚本生成请求: {request_data}")
  651. logger.info(f"request_data类型: {type(request_data)}")
  652. # 类型检查和处理
  653. if isinstance(request_data, str):
  654. logger.warning(f"request_data是字符串,尝试解析为JSON: {request_data}")
  655. try:
  656. import json
  657. request_data = json.loads(request_data)
  658. except json.JSONDecodeError as e:
  659. raise ValueError(f"无法解析request_data为JSON: {str(e)}")
  660. if not isinstance(request_data, dict):
  661. raise ValueError(f"request_data必须是字典类型,实际类型: {type(request_data)}")
  662. # 1. 从传入的request_data中解析input, output, request_content内容
  663. input_data = request_data.get('input', '')
  664. output_data = request_data.get('output', '')
  665. request_content = request_data.get('request_data', '')
  666. # 如果request_content是HTML格式,提取纯文本
  667. if request_content and (request_content.startswith('<p>') or '<' in request_content):
  668. # 简单的HTML标签清理
  669. import re
  670. request_content = re.sub(r'<[^>]+>', '', request_content).strip()
  671. if not input_data or not output_data or not request_content:
  672. raise ValueError(f"缺少必要参数:input='{input_data}', output='{output_data}', request_content='{request_content[:100] if request_content else ''}' 不能为空")
  673. logger.info(f"解析得到 - input: {input_data}, output: {output_data}, request_content: {request_content}")
  674. # 2. 解析input中的多个数据表并生成源表DDL
  675. source_tables_ddl = []
  676. input_tables = []
  677. if input_data:
  678. tables = [table.strip() for table in input_data.split(',') if table.strip()]
  679. for table in tables:
  680. ddl = DataFlowService._parse_table_and_get_ddl(table, 'input')
  681. if ddl:
  682. input_tables.append(table)
  683. source_tables_ddl.append(ddl)
  684. else:
  685. logger.warning(f"无法获取输入表 {table} 的DDL结构")
  686. # 3. 解析output中的数据表并生成目标表DDL
  687. target_table_ddl = ""
  688. if output_data:
  689. target_table_ddl = DataFlowService._parse_table_and_get_ddl(output_data.strip(), 'output')
  690. if not target_table_ddl:
  691. logger.warning(f"无法获取输出表 {output_data} 的DDL结构")
  692. # 4. 按照Deepseek-prompt.txt的框架构建提示语
  693. prompt_parts = []
  694. # 开场白 - 角色定义
  695. prompt_parts.append("你是一名数据库工程师,正在构建一个PostgreSQL数据中的汇总逻辑。请为以下需求生成一段标准的 PostgreSQL SQL 脚本:")
  696. # 动态生成源表部分(第1点)
  697. for i, (table, ddl) in enumerate(zip(input_tables, source_tables_ddl), 1):
  698. table_name = table.split(':')[-1] if ':' in table else table
  699. prompt_parts.append(f"{i}.有一个源表: {table_name},它的定义语句如下:")
  700. prompt_parts.append(ddl)
  701. prompt_parts.append("") # 添加空行分隔
  702. # 动态生成目标表部分(第2点)
  703. if target_table_ddl:
  704. target_table_name = output_data.split(':')[-1] if ':' in output_data else output_data
  705. next_index = len(input_tables) + 1
  706. prompt_parts.append(f"{next_index}.有一个目标表:{target_table_name},它的定义语句如下:")
  707. prompt_parts.append(target_table_ddl)
  708. prompt_parts.append("") # 添加空行分隔
  709. # 动态生成处理逻辑部分(第3点)
  710. next_index = len(input_tables) + 2 if target_table_ddl else len(input_tables) + 1
  711. prompt_parts.append(f"{next_index}.处理逻辑为:{request_content}")
  712. prompt_parts.append("") # 添加空行分隔
  713. # 固定的技术要求部分(第4-8点)
  714. tech_requirements = [
  715. f"{next_index + 1}.脚本应使用标准的 PostgreSQL 语法,适合在 Airflow、Python 脚本、或调度系统中调用;",
  716. f"{next_index + 2}.无需使用 UPSERT 或 ON CONFLICT",
  717. f"{next_index + 3}.请直接输出SQL,无需进行解释。",
  718. f"{next_index + 4}.请给这段sql起个英文名,不少于三个英文单词,使用\"_\"分隔,采用蛇形命名法。把sql的名字作为注释写在返回的sql中。",
  719. f"{next_index + 5}.生成的sql在向目标表插入数据的时候,向create_time字段写入当前日期时间now(),不用处理update_time字段"
  720. ]
  721. prompt_parts.extend(tech_requirements)
  722. # 组合完整的提示语
  723. full_prompt = "\n".join(prompt_parts)
  724. logger.info(f"构建的完整提示语长度: {len(full_prompt)}")
  725. logger.info(f"完整提示语内容: {full_prompt}")
  726. # 5. 调用LLM生成SQL脚本
  727. logger.info("开始调用Deepseek模型生成SQL脚本")
  728. script_content = llm_sql(full_prompt)
  729. if not script_content:
  730. raise ValueError("Deepseek模型返回空内容")
  731. # 确保返回的是文本格式
  732. if not isinstance(script_content, str):
  733. script_content = str(script_content)
  734. logger.info(f"SQL脚本生成成功,内容长度: {len(script_content)}")
  735. return script_content
  736. except Exception as e:
  737. logger.error(f"生成SQL脚本失败: {str(e)}")
  738. raise e
  739. @staticmethod
  740. def _parse_table_and_get_ddl(table_str: str, table_type: str) -> str:
  741. """
  742. 解析表格式(A:B)并从Neo4j查询元数据生成DDL
  743. Args:
  744. table_str: 表格式字符串,格式为"label:name_en"
  745. table_type: 表类型,用于日志记录(input/output)
  746. Returns:
  747. DDL格式的表结构字符串
  748. """
  749. try:
  750. # 解析A:B格式
  751. if ':' not in table_str:
  752. logger.error(f"表格式错误,应为'label:name_en'格式: {table_str}")
  753. return ""
  754. parts = table_str.split(':', 1)
  755. if len(parts) != 2:
  756. logger.error(f"表格式解析失败: {table_str}")
  757. return ""
  758. label = parts[0].strip()
  759. name_en = parts[1].strip()
  760. if not label or not name_en:
  761. logger.error(f"标签或英文名为空: label={label}, name_en={name_en}")
  762. return ""
  763. logger.info(f"开始查询{table_type}表: label={label}, name_en={name_en}")
  764. # 从Neo4j查询节点及其关联的元数据
  765. with connect_graph().session() as session:
  766. # 查询节点及其关联的元数据
  767. cypher = f"""
  768. MATCH (n:{label} {{name_en: $name_en}})
  769. OPTIONAL MATCH (n)-[:INCLUDES]->(m:DataMeta)
  770. RETURN n, collect(m) as metadata
  771. """
  772. result = session.run(cypher, {'name_en': name_en}) # type: ignore[arg-type]
  773. record = result.single()
  774. if not record:
  775. logger.error(f"未找到节点: label={label}, name_en={name_en}")
  776. return ""
  777. node = record['n']
  778. metadata = record['metadata']
  779. logger.info(f"找到节点,关联元数据数量: {len(metadata)}")
  780. # 生成DDL格式的表结构
  781. ddl_lines = []
  782. ddl_lines.append(f"CREATE TABLE {name_en} (")
  783. if metadata:
  784. column_definitions = []
  785. for meta in metadata:
  786. if meta: # 确保meta不为空
  787. meta_props = dict(meta)
  788. column_name = meta_props.get('name_en', meta_props.get('name_zh', 'unknown_column'))
  789. data_type = meta_props.get('data_type', 'VARCHAR(255)')
  790. comment = meta_props.get('name_zh', '')
  791. # 构建列定义
  792. column_def = f" {column_name} {data_type}"
  793. if comment:
  794. column_def += f" COMMENT '{comment}'"
  795. column_definitions.append(column_def)
  796. if column_definitions:
  797. ddl_lines.append(",\n".join(column_definitions))
  798. else:
  799. ddl_lines.append(" id BIGINT PRIMARY KEY COMMENT '主键ID'")
  800. else:
  801. # 如果没有元数据,添加默认列
  802. ddl_lines.append(" id BIGINT PRIMARY KEY COMMENT '主键ID'")
  803. ddl_lines.append(");")
  804. # 添加表注释
  805. node_props = dict(node)
  806. table_comment = node_props.get('name_zh', node_props.get('describe', name_en))
  807. if table_comment and table_comment != name_en:
  808. ddl_lines.append(f"COMMENT ON TABLE {name_en} IS '{table_comment}';")
  809. ddl_content = "\n".join(ddl_lines)
  810. logger.info(f"{table_type}表DDL生成成功: {name_en}")
  811. logger.debug(f"生成的DDL: {ddl_content}")
  812. return ddl_content
  813. except Exception as e:
  814. logger.error(f"解析表格式和生成DDL失败: {str(e)}")
  815. return ""
  816. @staticmethod
  817. def _handle_script_relationships(data: Dict[str, Any],dataflow_name:str,name_en:str):
  818. """
  819. 处理脚本关系,在Neo4j图数据库中创建从source_table到target_table之间的DERIVED_FROM关系
  820. Args:
  821. data: 包含脚本信息的数据字典,应包含script_name, script_type, schedule_status, source_table, target_table, update_mode
  822. """
  823. try:
  824. # 从data中读取键值对
  825. script_name = dataflow_name,
  826. script_type = data.get('script_type', 'sql')
  827. schedule_status = data.get('status', 'inactive')
  828. source_table_full = data.get('source_table', '')
  829. target_table_full = data.get('target_table', '')
  830. update_mode = data.get('update_mode', 'full')
  831. # 处理source_table和target_table的格式
  832. source_table = source_table_full.split(':')[-1] if ':' in source_table_full else source_table_full
  833. target_table = target_table_full.split(':')[-1] if ':' in target_table_full else target_table_full
  834. source_label = source_table_full.split(':')[0] if ':' in source_table_full else source_table_full
  835. target_label = target_table_full.split(':')[0] if ':' in target_table_full else target_table_full
  836. # 验证必要字段
  837. if not source_table or not target_table:
  838. logger.warning(f"source_table或target_table为空,跳过关系创建: source_table={source_table}, target_table={target_table}")
  839. return
  840. logger.info(f"开始创建脚本关系: {source_table} -> {target_table}")
  841. with connect_graph().session() as session:
  842. # 创建或获取source和target节点
  843. create_nodes_query = f"""
  844. MERGE (source:{source_label} {{name: $source_table}})
  845. ON CREATE SET source.created_at = $created_at,
  846. source.type = 'source'
  847. WITH source
  848. MERGE (target:{target_label} {{name: $target_table}})
  849. ON CREATE SET target.created_at = $created_at,
  850. target.type = 'target'
  851. RETURN source, target, id(source) as source_id, id(target) as target_id
  852. """
  853. # 执行创建节点的查询
  854. result = session.run(create_nodes_query, { # type: ignore[arg-type]
  855. 'source_table': source_table,
  856. 'target_table': target_table,
  857. 'created_at': get_formatted_time()
  858. }).single()
  859. if result:
  860. source_id = result['source_id']
  861. target_id = result['target_id']
  862. # 检查并创建关系
  863. create_relationship_query = f"""
  864. MATCH (source:{source_label}), (target:{target_label})
  865. WHERE id(source) = $source_id AND id(target) = $target_id
  866. AND NOT EXISTS((target)-[:DERIVED_FROM]->(source))
  867. CREATE (target)-[r:DERIVED_FROM]->(source)
  868. SET r.script_name = $script_name,
  869. r.script_type = $script_type,
  870. r.schedule_status = $schedule_status,
  871. r.update_mode = $update_mode,
  872. r.created_at = $created_at,
  873. r.updated_at = $created_at
  874. RETURN r
  875. """
  876. relationship_result = session.run(create_relationship_query, { # type: ignore[arg-type]
  877. 'source_id': source_id,
  878. 'target_id': target_id,
  879. 'script_name': script_name,
  880. 'script_type': script_type,
  881. 'schedule_status': schedule_status,
  882. 'update_mode': update_mode,
  883. 'created_at': get_formatted_time()
  884. }).single()
  885. if relationship_result:
  886. logger.info(f"成功创建DERIVED_FROM关系: {target_table} -> {source_table} (script: {script_name})")
  887. else:
  888. logger.info(f"DERIVED_FROM关系已存在: {target_table} -> {source_table}")
  889. else:
  890. logger.error(f"创建表节点失败: source_table={source_table}, target_table={target_table}")
  891. except Exception as e:
  892. logger.error(f"处理脚本关系失败: {str(e)}")
  893. raise e