dataflows.py 87 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163
  1. import contextlib
  2. import copy
  3. import json
  4. import logging
  5. import os
  6. import uuid
  7. from datetime import datetime
  8. from pathlib import Path
  9. from typing import Any, Dict, List, Optional, Union
  10. from sqlalchemy import text
  11. from app import db
  12. from app.core.common.identifiers import ensure_governance_uid
  13. from app.core.data_rules.contracts import validate_dataflow_spec
  14. from app.core.data_service.data_product_service import DataProductService
  15. from app.core.graph.graph_operations import (
  16. connect_graph,
  17. create_or_get_node,
  18. get_node,
  19. relationship_exists,
  20. )
  21. from app.core.meta_data import get_formatted_time, translate_and_parse
  22. logger = logging.getLogger(__name__)
  23. # 项目根目录
  24. PROJECT_ROOT = Path(__file__).parent.parent.parent.parent
  25. class DataFlowService:
  26. """数据流服务类,处理数据流相关的业务逻辑"""
  27. _GOVERNED_REQUIREMENT_KEYS = {
  28. "dataflow_spec",
  29. "dataset_edges",
  30. "migration_metadata",
  31. }
  32. _MIGRATION_METADATA_KEYS = {
  33. "status",
  34. "legacy_fields_present",
  35. "preserved_for_read_only",
  36. "governed_semantics",
  37. }
  38. _GOVERNED_PAYLOAD_FIELDS = {
  39. "draft_reservation",
  40. "dataflow_spec",
  41. "dataset_edges",
  42. "migration_metadata",
  43. }
  44. _GOVERNED_FORBIDDEN_FIELDS = {
  45. "code",
  46. "generated_code",
  47. "legacy_script_path",
  48. "n8n_workflow_id",
  49. "task_list",
  50. "workflow",
  51. }
  52. @staticmethod
  53. def _decode_script_requirement(value: Any) -> Any:
  54. if not isinstance(value, str):
  55. return copy.deepcopy(value)
  56. try:
  57. return json.loads(value)
  58. except (TypeError, json.JSONDecodeError):
  59. return value
  60. @classmethod
  61. def _signals_governed(cls, data: dict[str, Any], requirement: Any) -> bool:
  62. return (
  63. data.get("script_type") == "governed"
  64. or bool(set(data) & cls._GOVERNED_PAYLOAD_FIELDS)
  65. or (
  66. isinstance(requirement, dict)
  67. and bool(set(requirement) & cls._GOVERNED_REQUIREMENT_KEYS)
  68. )
  69. )
  70. @classmethod
  71. def _reject_governed_execution_fields(cls, data: dict[str, Any]) -> None:
  72. if set(data) & cls._GOVERNED_FORBIDDEN_FIELDS:
  73. raise ValueError(
  74. "governed DataFlow cannot contain legacy execution fields"
  75. )
  76. if data.get("script_type") not in {None, "governed"}:
  77. raise ValueError("governed DataFlow script_type must be governed")
  78. if data.get("script_path") not in {None, ""}:
  79. raise ValueError("governed DataFlow cannot define script_path")
  80. @classmethod
  81. def validate_governed_requirement(
  82. cls, value: Any, *, repository
  83. ) -> Dict[str, Any]:
  84. """Validate the closed, published-asset DataFlow save envelope."""
  85. requirement = cls._decode_script_requirement(value)
  86. if not isinstance(requirement, dict):
  87. raise ValueError("governed script_requirement must be an object")
  88. if set(requirement) != cls._GOVERNED_REQUIREMENT_KEYS:
  89. raise ValueError(
  90. "governed script_requirement contains unsupported fields"
  91. )
  92. flow = validate_dataflow_spec(requirement.get("dataflow_spec"))
  93. edges = requirement.get("dataset_edges")
  94. if not isinstance(edges, dict) or set(edges) != {
  95. "source_table",
  96. "target_table",
  97. }:
  98. raise ValueError("dataset edges must be a closed object")
  99. if (
  100. edges.get("source_table") != flow["input_schema_refs"]
  101. or edges.get("target_table") != flow["output_schema_ref"]
  102. ):
  103. raise ValueError("dataset edges must match the DataFlow schema refs")
  104. metadata = requirement.get("migration_metadata")
  105. if (
  106. not isinstance(metadata, dict)
  107. or set(metadata) != cls._MIGRATION_METADATA_KEYS
  108. ):
  109. raise ValueError("migration metadata must be a closed object")
  110. if metadata.get("status") not in {"migrated", "unmigrated"}:
  111. raise ValueError("unsupported migration status")
  112. if type(metadata.get("legacy_fields_present")) is not bool:
  113. raise ValueError("legacy_fields_present must be a boolean")
  114. if metadata.get("preserved_for_read_only") is not True:
  115. raise ValueError("legacy fields must be preserved for read-only use")
  116. if metadata.get("governed_semantics") != "dataflow_spec":
  117. raise ValueError("unsupported governed semantics")
  118. repository.load_published_assets(flow)
  119. return {
  120. "dataflow_spec": flow,
  121. "dataset_edges": {
  122. "source_table": list(flow["input_schema_refs"]),
  123. "target_table": flow["output_schema_ref"],
  124. },
  125. "migration_metadata": copy.deepcopy(metadata),
  126. }
  127. @staticmethod
  128. def _merge_governed_dataflow(node_data: dict[str, Any]) -> tuple[int, dict]:
  129. """Idempotently create by stable UID and reject immutable conflicts."""
  130. immutable = {
  131. key: node_data[key]
  132. for key in ("uid", "name_zh", "script_type", "script_requirement")
  133. }
  134. driver = connect_graph()
  135. try:
  136. with driver.session() as session:
  137. session.run(
  138. "CREATE CONSTRAINT data_flow_uid IF NOT EXISTS "
  139. "FOR (n:DataFlow) REQUIRE n.uid IS UNIQUE"
  140. )
  141. conflict = session.run(
  142. "MATCH (n:DataFlow {name_zh: $name_zh}) "
  143. "WHERE n.uid IS NULL OR n.uid <> $uid "
  144. "RETURN n.uid AS uid LIMIT 1",
  145. {"name_zh": node_data["name_zh"], "uid": node_data["uid"]},
  146. ).single()
  147. if conflict is not None:
  148. raise ValueError("dataflow_uid_conflict")
  149. record = session.run(
  150. "MERGE (n:DataFlow {uid: $uid}) "
  151. "ON CREATE SET n = $properties "
  152. "RETURN n, id(n) AS node_id",
  153. {"uid": node_data["uid"], "properties": node_data},
  154. ).single()
  155. if record is None:
  156. raise RuntimeError(
  157. "governed DataFlow MERGE returned no node"
  158. )
  159. persisted = dict(record["n"])
  160. for key, expected in immutable.items():
  161. if persisted.get(key) != expected:
  162. raise ValueError("dataflow_uid_conflict")
  163. node_id = record["node_id"]
  164. if isinstance(node_id, bool) or not isinstance(node_id, int):
  165. raise RuntimeError("governed DataFlow node id is invalid")
  166. result = dict(persisted)
  167. result["id"] = node_id
  168. return node_id, result
  169. finally:
  170. driver.close()
  171. @staticmethod
  172. def get_dataflows(
  173. page: int = 1,
  174. page_size: int = 10,
  175. search: str = "",
  176. ) -> Dict[str, Any]:
  177. """
  178. 获取数据流列表
  179. Args:
  180. page: 页码
  181. page_size: 每页大小
  182. search: 搜索关键词
  183. Returns:
  184. 包含数据流列表和分页信息的字典
  185. """
  186. try:
  187. # 从图数据库查询数据流列表
  188. skip_count = (page - 1) * page_size
  189. # 构建搜索条件
  190. where_clause = ""
  191. params: Dict[str, Union[int, str]] = {
  192. "skip": skip_count,
  193. "limit": page_size,
  194. }
  195. if search:
  196. where_clause = (
  197. "WHERE n.name_zh CONTAINS $search OR n.description CONTAINS $search"
  198. )
  199. params["search"] = search
  200. # 查询数据流列表(包含标签数组)
  201. # 使用WITH子句先分页,再聚合标签,避免分页结果不准确
  202. query = f"""
  203. MATCH (n:DataFlow)
  204. {where_clause}
  205. WITH n
  206. ORDER BY n.created_at DESC
  207. SKIP $skip
  208. LIMIT $limit
  209. OPTIONAL MATCH (n)-[:LABEL]->(label:DataLabel)
  210. RETURN n, id(n) as node_id,
  211. n.created_at as created_at,
  212. collect({{
  213. id: id(label),
  214. name_zh: label.name_zh,
  215. name_en: label.name_en
  216. }}) as tags
  217. """
  218. # 获取Neo4j驱动(如果连接失败会抛出ConnectionError异常)
  219. try:
  220. with connect_graph().session() as session:
  221. list_result = session.run(query, params).data()
  222. # 查询总数
  223. count_query = f"""
  224. MATCH (n:DataFlow)
  225. {where_clause}
  226. RETURN count(n) as total
  227. """
  228. count_params = {"search": search} if search else {}
  229. count_result = session.run(count_query, count_params).single()
  230. total = count_result["total"] if count_result else 0
  231. except Exception as e:
  232. # 确保 driver 被正确关闭,避免资源泄漏 - 这里不再需要手动关闭
  233. # driver,因为connect_graph可能返回单例或新实例。如果是新实例,
  234. # 我们没有引用它去关闭;若connect_graph每次返回新实例且需要关闭,
  235. # 之前的代码是对的。如果connect_graph返回单例,则不应关闭。
  236. # 用户反馈:The driver.close() call prematurely closes a shared
  237. # driver instance,所以直接使用 session,并不关闭 driver。
  238. logger.error(f"查询数据流失败: {str(e)}")
  239. raise e
  240. # 格式化结果
  241. dataflows = []
  242. for record in list_result:
  243. node = record["n"]
  244. dataflow = dict(node)
  245. dataflow["id"] = record["node_id"] # 使用查询返回的node_id
  246. # 处理标签数组,过滤掉空标签
  247. tags = record.get("tags", [])
  248. dataflow["tag"] = [tag for tag in tags if tag.get("id") is not None]
  249. dataflows.append(dataflow)
  250. return {
  251. "list": dataflows,
  252. "pagination": {
  253. "page": page,
  254. "page_size": page_size,
  255. "total": total,
  256. "total_pages": (total + page_size - 1) // page_size,
  257. },
  258. }
  259. except Exception as e:
  260. logger.error(f"获取数据流列表失败: {str(e)}")
  261. raise e
  262. @staticmethod
  263. def get_dataflow_by_id(dataflow_id: int) -> Optional[Dict[str, Any]]:
  264. """
  265. 根据ID获取数据流详情
  266. Args:
  267. dataflow_id: 数据流ID
  268. Returns:
  269. 数据流详情字典,如果不存在则返回None
  270. """
  271. try:
  272. # 从Neo4j获取DataFlow节点的所有属性(包含标签数组)
  273. neo4j_query = """
  274. MATCH (n:DataFlow)
  275. WHERE id(n) = $dataflow_id
  276. OPTIONAL MATCH (n)-[:LABEL]->(label:DataLabel)
  277. RETURN n, id(n) as node_id,
  278. collect({
  279. id: id(label),
  280. name_zh: label.name_zh,
  281. name_en: label.name_en
  282. }) as tags
  283. """
  284. with connect_graph().session() as session:
  285. neo4j_result = session.run(neo4j_query, dataflow_id=dataflow_id).data()
  286. if not neo4j_result:
  287. logger.warning(f"未找到ID为 {dataflow_id} 的DataFlow节点")
  288. return None
  289. record = neo4j_result[0]
  290. node = record["n"]
  291. # 将节点属性转换为字典
  292. dataflow = dict(node)
  293. dataflow["id"] = record["node_id"]
  294. # 处理标签数组,过滤掉空标签
  295. tags = record.get("tags", [])
  296. dataflow["tag"] = [tag for tag in tags if tag.get("id") is not None]
  297. # 处理 script_requirement:如果是JSON字符串,解析为对象
  298. script_requirement_str = dataflow.get("script_requirement", "")
  299. if script_requirement_str:
  300. try:
  301. # 尝试解析JSON字符串
  302. script_requirement_obj = json.loads(script_requirement_str)
  303. dataflow["script_requirement"] = script_requirement_obj
  304. logger.debug(
  305. "成功解析script_requirement: %s",
  306. script_requirement_obj,
  307. )
  308. except (json.JSONDecodeError, TypeError) as e:
  309. logger.warning(f"script_requirement解析失败,保持原值: {e}")
  310. # 保持原值(字符串)
  311. dataflow["script_requirement"] = script_requirement_str
  312. else:
  313. # 如果为空,设置为None
  314. dataflow["script_requirement"] = None
  315. logger.info(
  316. "成功获取DataFlow详情,ID: %s, 名称: %s",
  317. dataflow_id,
  318. dataflow.get("name_zh"),
  319. )
  320. return dataflow
  321. except Exception as e:
  322. logger.error(f"获取数据流详情失败: {str(e)}")
  323. raise e
  324. @staticmethod
  325. def create_dataflow(
  326. data: Dict[str, Any], *, repository=None, actor_uid=None
  327. ) -> Dict[str, Any]:
  328. """
  329. 创建新的数据流
  330. Args:
  331. data: 数据流配置数据
  332. Returns:
  333. 创建的数据流信息
  334. """
  335. try:
  336. # 验证必填字段
  337. required_fields = ["name_zh", "describe"]
  338. for field in required_fields:
  339. if field not in data:
  340. raise ValueError(f"缺少必填字段: {field}")
  341. dataflow_name = data["name_zh"]
  342. # 使用LLM翻译名称生成英文名
  343. try:
  344. result_list = translate_and_parse(dataflow_name)
  345. name_en = (
  346. result_list[0]
  347. if result_list
  348. else dataflow_name.lower().replace(" ", "_")
  349. )
  350. except Exception as e:
  351. logger.warning(f"翻译失败,使用默认英文名: {str(e)}")
  352. name_en = dataflow_name.lower().replace(" ", "_")
  353. script_requirement = data.get("script_requirement")
  354. decoded_requirement = DataFlowService._decode_script_requirement(
  355. script_requirement
  356. )
  357. governed = DataFlowService._signals_governed(
  358. data, decoded_requirement
  359. )
  360. saga_claim = None
  361. receipt = None
  362. if governed:
  363. DataFlowService._reject_governed_execution_fields(data)
  364. if repository is None:
  365. from app.core.data_rules.repository import DataRuleRepository
  366. repository = DataRuleRepository(db.session)
  367. decoded_requirement = (
  368. DataFlowService.validate_governed_requirement(
  369. decoded_requirement, repository=repository
  370. )
  371. )
  372. if actor_uid is None:
  373. raise ValueError(
  374. "governed DataFlow requires an authenticated actor"
  375. )
  376. receipt = data.get("draft_reservation")
  377. saga_claim = repository.begin_dataflow_create(
  378. receipt, actor_uid=actor_uid
  379. )
  380. if saga_claim["status"] == "completed":
  381. return copy.deepcopy(saga_claim["result"])
  382. reserved_uid = saga_claim["dataflow_uid"]
  383. if (
  384. reserved_uid
  385. != decoded_requirement["dataflow_spec"]["dataflow_uid"]
  386. ):
  387. raise ValueError(
  388. "draft reservation does not match dataflow_uid"
  389. )
  390. repository.commit_dataflow_create_claim()
  391. script_requirement = decoded_requirement
  392. # 处理 script_requirement,将其转换为 JSON 字符串
  393. if script_requirement is not None:
  394. # 如果是字典或列表,转换为 JSON 字符串
  395. if isinstance(script_requirement, (dict, list)):
  396. script_requirement_str = json.dumps(
  397. script_requirement,
  398. ensure_ascii=False,
  399. sort_keys=governed,
  400. separators=(",", ":") if governed else None,
  401. )
  402. else:
  403. # 如果已经是字符串,直接使用
  404. script_requirement_str = str(script_requirement)
  405. else:
  406. script_requirement_str = ""
  407. # 准备节点数据(tag不作为节点属性存储,而是通过LABEL关系关联)
  408. node_data = {
  409. "name_zh": dataflow_name,
  410. "name_en": name_en,
  411. "category": data.get("category", ""),
  412. "organization": data.get("organization", ""),
  413. "leader": data.get("leader", ""),
  414. "frequency": data.get("frequency", ""),
  415. "describe": data.get("describe", ""),
  416. "status": data.get("status", "inactive"),
  417. "update_mode": data.get("update_mode", "append"),
  418. "script_type": data.get("script_type", "python"),
  419. "script_requirement": script_requirement_str,
  420. "script_path": "", # 脚本路径,任务完成后更新
  421. "created_at": get_formatted_time(),
  422. "updated_at": get_formatted_time(),
  423. }
  424. if governed:
  425. node_data["uid"] = decoded_requirement["dataflow_spec"][
  426. "dataflow_uid"
  427. ]
  428. node_data["script_type"] = "governed"
  429. ensure_governance_uid(node_data)
  430. # Governed nodes use the reservation UID as the only create key.
  431. if governed:
  432. try:
  433. dataflow_id, result = (
  434. DataFlowService._merge_governed_dataflow(node_data)
  435. )
  436. except Exception as graph_error:
  437. try:
  438. repository.commit_dataflow_create_failure(
  439. reservation_id=receipt["reservation_id"],
  440. lease_token=saga_claim["lease_token"],
  441. error_code="neo4j_create_failed",
  442. )
  443. except Exception:
  444. logger.exception(
  445. "failed to persist governed DataFlow saga failure"
  446. )
  447. raise graph_error
  448. else:
  449. dataflow_id = get_node("DataFlow", name=dataflow_name)
  450. if dataflow_id:
  451. raise ValueError(f"数据流 '{dataflow_name}' 已存在")
  452. dataflow_id = create_or_get_node("DataFlow", **node_data)
  453. # 处理标签关系(支持多标签数组)
  454. tag_list = data.get("tag", [])
  455. if tag_list:
  456. try:
  457. DataFlowService._handle_tag_relationships(dataflow_id, tag_list)
  458. except Exception as e:
  459. logger.warning(f"处理标签关系时出错: {str(e)}")
  460. # Governed definitions are control-plane assets. Data Factory owns
  461. # all later task, code, workflow and product deployment side effects.
  462. if not governed:
  463. try:
  464. DataFlowService._save_to_pg_database(
  465. data, dataflow_name, name_en
  466. )
  467. logger.info(
  468. f"数据流信息已写入PG数据库: {dataflow_name}"
  469. )
  470. try:
  471. DataFlowService._handle_script_relationships(
  472. data, dataflow_name, name_en
  473. )
  474. logger.info(f"脚本关系创建成功: {dataflow_name}")
  475. except Exception as script_error:
  476. logger.warning(
  477. f"创建脚本关系失败: {str(script_error)}"
  478. )
  479. except Exception as pg_error:
  480. logger.error(f"写入PG数据库失败: {str(pg_error)}")
  481. if governed:
  482. result = repository.complete_dataflow_create(
  483. reservation_id=receipt["reservation_id"],
  484. dataflow_uid=node_data["uid"],
  485. lease_token=saga_claim["lease_token"],
  486. dataflow_node_id=dataflow_id,
  487. result=result,
  488. )
  489. else:
  490. # 查询创建的节点获取完整信息
  491. query = (
  492. "MATCH (n:DataFlow {name_zh: $name_zh}) "
  493. "RETURN n, id(n) as node_id"
  494. )
  495. with connect_graph().session() as session:
  496. id_result = session.run(query, name_zh=dataflow_name).single()
  497. if id_result:
  498. dataflow_node = id_result["n"]
  499. node_id = id_result["node_id"]
  500. result = dict(dataflow_node)
  501. result["id"] = node_id
  502. else:
  503. result = {
  504. "id": (
  505. dataflow_id
  506. if isinstance(dataflow_id, int)
  507. else None
  508. ),
  509. "uid": node_data["uid"],
  510. "name_zh": dataflow_name,
  511. "name_en": name_en,
  512. "created_at": get_formatted_time(),
  513. }
  514. if not governed:
  515. try:
  516. DataFlowService._register_data_product(
  517. data=data,
  518. dataflow_name=dataflow_name,
  519. name_en=name_en,
  520. dataflow_id=result.get("id"),
  521. )
  522. logger.info(f"数据产品注册成功: {dataflow_name}")
  523. except Exception as product_error:
  524. logger.warning(f"注册数据产品失败: {str(product_error)}")
  525. logger.info(f"创建数据流成功: {dataflow_name}")
  526. return result
  527. except Exception as e:
  528. logger.error(f"创建数据流失败: {str(e)}")
  529. raise e
  530. @staticmethod
  531. def _save_to_pg_database(
  532. data: Dict[str, Any],
  533. script_name: str,
  534. name_en: str,
  535. ):
  536. """
  537. 将任务信息保存到PG数据库的task_list表
  538. Args:
  539. data: 包含脚本信息的数据
  540. script_name: 脚本名称
  541. name_en: 英文名称
  542. """
  543. try:
  544. # 提取脚本相关信息
  545. # 处理 script_requirement,确保保存为 JSON 字符串
  546. script_requirement_raw = data.get("script_requirement")
  547. if script_requirement_raw is not None:
  548. if isinstance(script_requirement_raw, (dict, list)):
  549. script_requirement = json.dumps(
  550. script_requirement_raw, ensure_ascii=False
  551. )
  552. else:
  553. script_requirement = str(script_requirement_raw)
  554. else:
  555. script_requirement = ""
  556. # 验证必需字段
  557. if not script_name:
  558. raise ValueError("script_name不能为空")
  559. current_time = datetime.now()
  560. # 保存到task_list表
  561. try:
  562. # 1. 解析script_requirement并构建详细的任务描述
  563. task_description_md = script_requirement
  564. try:
  565. # 尝试解析JSON
  566. try:
  567. req_json = json.loads(script_requirement)
  568. except (json.JSONDecodeError, TypeError):
  569. req_json = None
  570. if isinstance(req_json, dict):
  571. # 1. 从script_requirement中提取rule字段作为request_content_str
  572. request_content_str = req_json.get("rule", "")
  573. # 2. 从script_requirement中提取source_table和
  574. # target_table字段信息
  575. source_table_ids = req_json.get("source_table", [])
  576. target_table_ids = req_json.get("target_table", [])
  577. # 确保是列表格式
  578. if not isinstance(source_table_ids, list):
  579. source_table_ids = (
  580. [source_table_ids] if source_table_ids else []
  581. )
  582. if not isinstance(target_table_ids, list):
  583. target_table_ids = (
  584. [target_table_ids] if target_table_ids else []
  585. )
  586. # 从data参数中提取update_mode
  587. update_mode = data.get("update_mode", "append")
  588. # 生成Business Domain DDLs和数据源信息
  589. source_tables_info = []
  590. target_tables_info = []
  591. if source_table_ids or target_table_ids:
  592. try:
  593. with connect_graph().session() as session:
  594. # 处理source tables
  595. for bd_id in source_table_ids:
  596. ddl_info = DataFlowService._generate_businessdomain_ddl(
  597. session,
  598. bd_id,
  599. is_target=False,
  600. )
  601. if ddl_info:
  602. source_tables_info.append(ddl_info)
  603. # 处理target tables(目标表缺省要有create_time字段)
  604. for bd_id in target_table_ids:
  605. ddl_info = DataFlowService._generate_businessdomain_ddl(
  606. session,
  607. bd_id,
  608. is_target=True,
  609. update_mode=update_mode,
  610. )
  611. if ddl_info:
  612. target_tables_info.append(ddl_info)
  613. except Exception as neo_e:
  614. logger.error(
  615. f"获取BusinessDomain DDL失败: {str(neo_e)}"
  616. )
  617. # 构建Markdown格式的任务描述
  618. task_desc_parts = [f"# Task: {script_name}\n"]
  619. # 添加源表信息(DDL和数据源)
  620. if source_tables_info:
  621. task_desc_parts.append("## Source Tables")
  622. for info in source_tables_info:
  623. task_desc_parts.append(f"### {info['table_name']}")
  624. if info.get("data_source"):
  625. ds = info["data_source"]
  626. task_desc_parts.append("**Data Source**")
  627. task_desc_parts.append(
  628. f"- **Type**: {ds.get('type', 'N/A')}"
  629. )
  630. task_desc_parts.append(
  631. f"- **Host**: {ds.get('host', 'N/A')}"
  632. )
  633. task_desc_parts.append(
  634. f"- **Port**: {ds.get('port', 'N/A')}"
  635. )
  636. task_desc_parts.append(
  637. f"- **Database**: {ds.get('database', 'N/A')}"
  638. )
  639. task_desc_parts.append(
  640. f"- **Schema**: {ds.get('schema', 'N/A')}\n"
  641. )
  642. task_desc_parts.append("**DDL**")
  643. task_desc_parts.append(f"```sql\n{info['ddl']}\n```\n")
  644. # 添加目标表信息(DDL和数据源)
  645. if target_tables_info:
  646. task_desc_parts.append("## Target Tables")
  647. for info in target_tables_info:
  648. task_desc_parts.append(f"### {info['table_name']}")
  649. if info.get("data_source"):
  650. ds = info["data_source"]
  651. task_desc_parts.append("**Data Source**")
  652. task_desc_parts.append(
  653. f"- **Type**: {ds.get('type', 'N/A')}"
  654. )
  655. task_desc_parts.append(
  656. f"- **Host**: {ds.get('host', 'N/A')}"
  657. )
  658. task_desc_parts.append(
  659. f"- **Port**: {ds.get('port', 'N/A')}"
  660. )
  661. task_desc_parts.append(
  662. f"- **Database**: {ds.get('database', 'N/A')}"
  663. )
  664. task_desc_parts.append(
  665. f"- **Schema**: {ds.get('schema', 'N/A')}\n"
  666. )
  667. task_desc_parts.append("**DDL**")
  668. task_desc_parts.append(f"```sql\n{info['ddl']}\n```\n")
  669. # 添加更新模式说明
  670. task_desc_parts.append("## Update Mode")
  671. if update_mode == "append":
  672. task_desc_parts.append("- **Mode**: Append (追加模式)")
  673. task_desc_parts.append(
  674. "- **Description**: 新数据将追加到目标表,不删除现有数据\n"
  675. )
  676. else:
  677. task_desc_parts.append(
  678. "- **Mode**: Full Refresh (全量更新)"
  679. )
  680. task_desc_parts.append(
  681. "- **Description**: 目标表将被清空后重新写入数据\n"
  682. )
  683. # 添加请求内容(rule)
  684. if request_content_str:
  685. task_desc_parts.append("## Request Content")
  686. task_desc_parts.append(f"{request_content_str}\n")
  687. # 添加实施步骤(统一使用数据转换任务步骤)
  688. task_desc_parts.append("## Implementation Steps")
  689. task_desc_parts.append(
  690. "1. Extract data from source tables as specified in the DDL"
  691. )
  692. task_desc_parts.append(
  693. "2. Apply transformation logic according to the rule:"
  694. )
  695. if request_content_str:
  696. task_desc_parts.append(f" - Rule: {request_content_str}")
  697. task_desc_parts.append(
  698. "3. Generate Python program to implement the "
  699. "data transformation logic"
  700. )
  701. task_desc_parts.append(
  702. f"4. Write transformed data to target table "
  703. f"using {update_mode} mode"
  704. )
  705. task_description_md = "\n".join(task_desc_parts)
  706. except Exception as parse_e:
  707. logger.warning(
  708. f"解析任务描述详情失败,使用原始描述: {str(parse_e)}"
  709. )
  710. task_description_md = script_requirement
  711. # 设置 code_path(不包含文件名)
  712. # code_name 需要在获取 task_id 后生成
  713. code_path = "datafactory/scripts"
  714. task_insert_sql = text(
  715. "INSERT INTO public.task_list\n"
  716. "(task_name, task_description, status, code_name, "
  717. "code_path, create_by, create_time, update_time)\n"
  718. "VALUES\n"
  719. "(:task_name, :task_description, :status, :code_name, "
  720. ":code_path, :create_by, :create_time, :update_time)\n"
  721. "RETURNING task_id"
  722. )
  723. task_params = {
  724. "task_name": script_name,
  725. "task_description": task_description_md,
  726. "status": "pending",
  727. "code_name": "", # 暂时为空,等获取 task_id 后更新
  728. "code_path": code_path,
  729. "create_by": "cursor",
  730. "create_time": current_time,
  731. "update_time": current_time,
  732. }
  733. result = db.session.execute(task_insert_sql, task_params)
  734. row = result.fetchone()
  735. task_id = row[0] if row else None
  736. # 根据 task_id 生成脚本文件名
  737. # 格式: task_{task_id}_{task_name}.py(与 auto_execute_tasks 生成的一致)
  738. code_name = f"task_{task_id}_{script_name}.py"
  739. # 更新 code_name 字段
  740. if task_id:
  741. update_sql = text(
  742. "UPDATE public.task_list SET code_name = :code_name "
  743. "WHERE task_id = :task_id"
  744. )
  745. db.session.execute(
  746. update_sql, {"code_name": code_name, "task_id": task_id}
  747. )
  748. db.session.commit()
  749. logger.info(
  750. f"成功将任务信息写入task_list表: "
  751. f"task_id={task_id}, task_name={script_name}, code_name={code_name}"
  752. )
  753. # 自动生成 n8n 工作流 JSON 文件
  754. try:
  755. DataFlowService._generate_n8n_workflow(
  756. script_name=script_name,
  757. code_name=code_name,
  758. code_path=code_path,
  759. update_mode=update_mode,
  760. task_id=task_id,
  761. )
  762. except Exception as wf_error:
  763. logger.warning(f"生成n8n工作流文件失败: {str(wf_error)}")
  764. # 不影响主流程
  765. except Exception as task_error:
  766. db.session.rollback()
  767. logger.error(f"写入task_list表失败: {str(task_error)}")
  768. raise task_error
  769. except Exception as e:
  770. db.session.rollback()
  771. logger.error(f"保存到PG数据库失败: {str(e)}")
  772. raise e
  773. @staticmethod
  774. def _generate_n8n_workflow(
  775. script_name: str,
  776. code_name: str,
  777. code_path: str,
  778. update_mode: str = "append",
  779. task_id: Optional[int] = None,
  780. ) -> Optional[str]:
  781. """
  782. 自动生成 n8n 工作流 JSON 文件
  783. Args:
  784. script_name: 脚本/任务名称
  785. code_name: 代码文件名(如 task_42_DF_DO202601210001.py)
  786. code_path: 代码路径(如 datafactory/scripts)
  787. update_mode: 更新模式
  788. task_id: 关联的任务 ID
  789. Returns:
  790. 生成的工作流文件路径,失败返回 None
  791. """
  792. try:
  793. # 确保工作流目录存在
  794. workflows_dir = PROJECT_ROOT / "datafactory" / "workflows"
  795. workflows_dir.mkdir(parents=True, exist_ok=True)
  796. # 生成工作流文件名(使用任务ID以便于关联)
  797. if task_id:
  798. workflow_filename = f"task_{task_id}_{script_name}_workflow.json"
  799. else:
  800. workflow_filename = f"{script_name}_workflow.json"
  801. workflow_path = workflows_dir / workflow_filename
  802. # 生成唯一ID
  803. def gen_id():
  804. return str(uuid.uuid4())
  805. # 构建完整的 SSH 命令,包含激活 venv
  806. # 注意:由于 n8n 服务器与应用服务器分离,必须使用 SSH 节点
  807. # code_name 已经包含 .py 后缀(如 task_42_DF_DO202601210001.py)
  808. ssh_command = (
  809. f"cd /opt/dataops-platform && source venv/bin/activate && "
  810. f"python {code_path}/{code_name}"
  811. )
  812. workflow_json = {
  813. "name": f"{script_name}_工作流",
  814. "nodes": [
  815. {
  816. "parameters": {
  817. "rule": {
  818. "interval": [
  819. {
  820. "field": "days",
  821. "daysInterval": 1,
  822. "triggerAtHour": 1,
  823. "triggerAtMinute": 0,
  824. }
  825. ]
  826. }
  827. },
  828. "id": gen_id(),
  829. "name": "Schedule Trigger",
  830. "type": "n8n-nodes-base.scheduleTrigger",
  831. "typeVersion": 1.2,
  832. "position": [250, 300],
  833. },
  834. {
  835. "parameters": {
  836. "resource": "command",
  837. "operation": "execute",
  838. "command": ssh_command,
  839. "cwd": "/opt/dataops-platform",
  840. },
  841. "id": gen_id(),
  842. "name": "Execute Script",
  843. "type": "n8n-nodes-base.ssh",
  844. "typeVersion": 1,
  845. "position": [450, 300],
  846. "credentials": {
  847. "sshPassword": {
  848. "id": "pYTwwuyC15caQe6y",
  849. "name": "SSH Password account",
  850. }
  851. },
  852. },
  853. {
  854. "parameters": {
  855. "conditions": {
  856. "options": {
  857. "caseSensitive": True,
  858. "leftValue": "",
  859. "typeValidation": "strict",
  860. },
  861. "conditions": [
  862. {
  863. "id": "condition-success",
  864. "leftValue": "={{ $json.code }}",
  865. "rightValue": 0,
  866. "operator": {
  867. "type": "number",
  868. "operation": "equals",
  869. },
  870. }
  871. ],
  872. "combinator": "and",
  873. }
  874. },
  875. "id": gen_id(),
  876. "name": "Check Result",
  877. "type": "n8n-nodes-base.if",
  878. "typeVersion": 2,
  879. "position": [650, 300],
  880. },
  881. {
  882. "parameters": {
  883. "assignments": {
  884. "assignments": [
  885. {
  886. "id": "result-success",
  887. "name": "status",
  888. "value": "success",
  889. "type": "string",
  890. },
  891. {
  892. "id": "result-message",
  893. "name": "message",
  894. "value": f"{script_name} 执行成功",
  895. "type": "string",
  896. },
  897. {
  898. "id": "result-output",
  899. "name": "output",
  900. "value": "={{ $json.stdout }}",
  901. "type": "string",
  902. },
  903. {
  904. "id": "result-time",
  905. "name": "executionTime",
  906. "value": "={{ $now.toISO() }}",
  907. "type": "string",
  908. },
  909. ]
  910. }
  911. },
  912. "id": gen_id(),
  913. "name": "Success Response",
  914. "type": "n8n-nodes-base.set",
  915. "typeVersion": 3.4,
  916. "position": [850, 200],
  917. },
  918. {
  919. "parameters": {
  920. "assignments": {
  921. "assignments": [
  922. {
  923. "id": "error-status",
  924. "name": "status",
  925. "value": "error",
  926. "type": "string",
  927. },
  928. {
  929. "id": "error-message",
  930. "name": "message",
  931. "value": f"{script_name} 执行失败",
  932. "type": "string",
  933. },
  934. {
  935. "id": "error-output",
  936. "name": "error",
  937. "value": "={{ $json.stderr }}",
  938. "type": "string",
  939. },
  940. {
  941. "id": "error-code",
  942. "name": "exitCode",
  943. "value": "={{ $json.code }}",
  944. "type": "number",
  945. },
  946. {
  947. "id": "error-time",
  948. "name": "executionTime",
  949. "value": "={{ $now.toISO() }}",
  950. "type": "string",
  951. },
  952. ]
  953. }
  954. },
  955. "id": gen_id(),
  956. "name": "Error Response",
  957. "type": "n8n-nodes-base.set",
  958. "typeVersion": 3.4,
  959. "position": [850, 400],
  960. },
  961. ],
  962. "connections": {
  963. "Schedule Trigger": {
  964. "main": [
  965. [
  966. {
  967. "node": "Execute Script",
  968. "type": "main",
  969. "index": 0,
  970. }
  971. ]
  972. ]
  973. },
  974. "Execute Script": {
  975. "main": [
  976. [
  977. {
  978. "node": "Check Result",
  979. "type": "main",
  980. "index": 0,
  981. }
  982. ]
  983. ]
  984. },
  985. "Check Result": {
  986. "main": [
  987. [
  988. {
  989. "node": "Success Response",
  990. "type": "main",
  991. "index": 0,
  992. }
  993. ],
  994. [
  995. {
  996. "node": "Error Response",
  997. "type": "main",
  998. "index": 0,
  999. }
  1000. ],
  1001. ]
  1002. },
  1003. },
  1004. "active": False,
  1005. "settings": {"executionOrder": "v1"},
  1006. "versionId": "1",
  1007. "meta": {
  1008. "templateCredsSetupCompleted": False,
  1009. "instanceId": "dataops-platform",
  1010. },
  1011. "tags": [
  1012. {
  1013. "createdAt": datetime.now().isoformat() + "Z",
  1014. "updatedAt": datetime.now().isoformat() + "Z",
  1015. "id": "1",
  1016. "name": "数据流程",
  1017. }
  1018. ],
  1019. }
  1020. # 写入文件
  1021. with open(workflow_path, "w", encoding="utf-8") as f:
  1022. json.dump(workflow_json, f, ensure_ascii=False, indent=2)
  1023. logger.info(f"成功生成n8n工作流文件: {workflow_path}")
  1024. return str(workflow_path)
  1025. except Exception as e:
  1026. logger.error(f"生成n8n工作流失败: {str(e)}")
  1027. return None
  1028. @staticmethod
  1029. def _handle_children_relationships(dataflow_node, children_ids):
  1030. """处理子节点关系"""
  1031. logger.debug(
  1032. "处理子节点关系,原始children_ids: %s, 类型: %s",
  1033. children_ids,
  1034. type(children_ids),
  1035. )
  1036. # 确保children_ids是列表格式
  1037. if not isinstance(children_ids, (list, tuple)):
  1038. if children_ids is not None:
  1039. children_ids = [children_ids] # 如果是单个值,转换为列表
  1040. logger.debug(f"将单个值转换为列表: {children_ids}")
  1041. else:
  1042. children_ids = [] # 如果是None,转换为空列表
  1043. logger.debug("将None转换为空列表")
  1044. for child_id in children_ids:
  1045. try:
  1046. # 查找子节点
  1047. query = "MATCH (n) WHERE id(n) = $child_id RETURN n"
  1048. with connect_graph().session() as session:
  1049. result = session.run(query, child_id=child_id).data()
  1050. if result:
  1051. # 获取dataflow_node的ID
  1052. dataflow_id = getattr(dataflow_node, "identity", None)
  1053. if dataflow_id is None:
  1054. # 如果没有identity属性,从名称查询ID
  1055. query_id = (
  1056. "MATCH (n:DataFlow) WHERE n.name_zh = "
  1057. "$name_zh RETURN id(n) as node_id"
  1058. )
  1059. id_result = session.run(
  1060. query_id,
  1061. name_zh=dataflow_node.get("name_zh"),
  1062. ).single()
  1063. dataflow_id = id_result["node_id"] if id_result else None
  1064. # 创建关系 - 使用ID调用relationship_exists
  1065. if dataflow_id and not relationship_exists(
  1066. dataflow_id, "child", child_id
  1067. ):
  1068. session.run(
  1069. "MATCH (a), (b) WHERE id(a) = $dataflow_id "
  1070. "AND id(b) = $child_id "
  1071. "CREATE (a)-[:child]->(b)",
  1072. dataflow_id=dataflow_id,
  1073. child_id=child_id,
  1074. )
  1075. logger.info(f"创建子节点关系: {dataflow_id} -> {child_id}")
  1076. except Exception as e:
  1077. logger.warning(f"创建子节点关系失败 {child_id}: {str(e)}")
  1078. @staticmethod
  1079. def _handle_tag_relationships(dataflow_id, tag_list):
  1080. """
  1081. 处理多标签关系
  1082. Args:
  1083. dataflow_id: 数据流节点ID
  1084. tag_list: 标签列表,可以是ID数组或包含id字段的对象数组
  1085. """
  1086. # 确保tag_list是列表格式
  1087. if not isinstance(tag_list, list):
  1088. tag_list = [tag_list] if tag_list else []
  1089. for tag_item in tag_list:
  1090. tag_id = None
  1091. if isinstance(tag_item, dict) and "id" in tag_item:
  1092. tag_id = int(tag_item["id"])
  1093. elif isinstance(tag_item, (int, str)):
  1094. with contextlib.suppress(ValueError, TypeError):
  1095. tag_id = int(tag_item)
  1096. if tag_id:
  1097. DataFlowService._handle_single_tag_relationship(dataflow_id, tag_id)
  1098. @staticmethod
  1099. def _handle_single_tag_relationship(dataflow_id, tag_id):
  1100. """处理单个标签关系"""
  1101. try:
  1102. # 查找标签节点
  1103. query = "MATCH (n:DataLabel) WHERE id(n) = $tag_id RETURN n"
  1104. with connect_graph().session() as session:
  1105. result = session.run(query, tag_id=tag_id).data()
  1106. # 创建关系 - 使用ID调用relationship_exists
  1107. if (
  1108. result
  1109. and dataflow_id
  1110. and not relationship_exists(dataflow_id, "LABEL", tag_id)
  1111. ):
  1112. session.run(
  1113. "MATCH (a), (b) WHERE id(a) = $dataflow_id "
  1114. "AND id(b) = $tag_id "
  1115. "CREATE (a)-[:LABEL]->(b)",
  1116. dataflow_id=dataflow_id,
  1117. tag_id=tag_id,
  1118. )
  1119. logger.info(f"创建标签关系: {dataflow_id} -> {tag_id}")
  1120. except Exception as e:
  1121. logger.warning(f"创建标签关系失败 {tag_id}: {str(e)}")
  1122. @staticmethod
  1123. def update_dataflow_script_path(
  1124. dataflow_name: str,
  1125. script_path: str,
  1126. ) -> bool:
  1127. """
  1128. 更新 DataFlow 节点的脚本路径
  1129. 当任务完成后,将创建的 Python 脚本路径更新到 DataFlow 节点
  1130. Args:
  1131. dataflow_name: 数据流名称(中文名)
  1132. script_path: Python 脚本的完整路径
  1133. Returns:
  1134. 是否更新成功
  1135. """
  1136. try:
  1137. query = """
  1138. MATCH (n:DataFlow {name_zh: $name_zh})
  1139. SET n.script_path = $script_path, n.updated_at = $updated_at
  1140. RETURN n
  1141. """
  1142. with connect_graph().session() as session:
  1143. result = session.run(
  1144. query,
  1145. name_zh=dataflow_name,
  1146. script_path=script_path,
  1147. updated_at=get_formatted_time(),
  1148. ).single()
  1149. if result:
  1150. logger.info(
  1151. f"已更新 DataFlow 脚本路径: {dataflow_name} -> {script_path}"
  1152. )
  1153. return True
  1154. else:
  1155. logger.warning(f"未找到 DataFlow 节点: {dataflow_name}")
  1156. return False
  1157. except Exception as e:
  1158. logger.error(f"更新 DataFlow 脚本路径失败: {str(e)}")
  1159. return False
  1160. @staticmethod
  1161. def get_script_content(dataflow_id: int) -> Dict[str, Any]:
  1162. """
  1163. 根据 DataFlow ID 获取关联的脚本内容
  1164. Args:
  1165. dataflow_id: 数据流ID
  1166. Returns:
  1167. 包含脚本内容和元信息的字典:
  1168. - script_path: 脚本路径
  1169. - script_content: 脚本内容
  1170. - script_type: 脚本类型(如 python)
  1171. - dataflow_name: 数据流名称
  1172. Raises:
  1173. ValueError: 当 DataFlow 不存在或脚本路径为空时
  1174. FileNotFoundError: 当脚本文件不存在时
  1175. """
  1176. from pathlib import Path
  1177. try:
  1178. # 从 Neo4j 获取 DataFlow 节点
  1179. query = """
  1180. MATCH (n:DataFlow)
  1181. WHERE id(n) = $dataflow_id
  1182. RETURN n, id(n) as node_id
  1183. """
  1184. with connect_graph().session() as session:
  1185. result = session.run(query, dataflow_id=dataflow_id).single()
  1186. if not result:
  1187. raise ValueError(f"未找到 ID 为 {dataflow_id} 的 DataFlow 节点")
  1188. node = result["n"]
  1189. node_props = dict(node)
  1190. # 获取脚本路径
  1191. script_path = node_props.get("script_path", "")
  1192. if not script_path:
  1193. raise ValueError(
  1194. f"DataFlow (ID: {dataflow_id}) 的 script_path 属性为空"
  1195. )
  1196. # 确定脚本文件的完整路径
  1197. # script_path 可能是相对路径或绝对路径
  1198. script_file = Path(script_path)
  1199. # 如果是相对路径,相对于项目根目录
  1200. if not script_file.is_absolute():
  1201. # 获取项目根目录(假设 app 目录的父目录是项目根)
  1202. project_root = Path(__file__).parent.parent.parent.parent
  1203. script_file = project_root / script_path
  1204. # 检查文件是否存在
  1205. if not script_file.exists():
  1206. raise FileNotFoundError(f"脚本文件不存在: {script_file}")
  1207. # 读取脚本内容
  1208. with script_file.open("r", encoding="utf-8") as f:
  1209. script_content = f.read()
  1210. # 确定脚本类型
  1211. suffix = script_file.suffix.lower()
  1212. script_type_map = {
  1213. ".py": "python",
  1214. ".js": "javascript",
  1215. ".ts": "typescript",
  1216. ".sql": "sql",
  1217. ".sh": "shell",
  1218. }
  1219. script_type = script_type_map.get(suffix, "text")
  1220. logger.info(
  1221. f"成功读取脚本内容: DataFlow ID={dataflow_id}, "
  1222. f"路径={script_path}, 类型={script_type}"
  1223. )
  1224. return {
  1225. "script_path": script_path,
  1226. "script_content": script_content,
  1227. "script_type": script_type,
  1228. "dataflow_id": dataflow_id,
  1229. "dataflow_name": node_props.get("name_zh", ""),
  1230. "dataflow_name_en": node_props.get("name_en", ""),
  1231. }
  1232. except (ValueError, FileNotFoundError):
  1233. raise
  1234. except Exception as e:
  1235. logger.error(f"获取脚本内容失败: {str(e)}")
  1236. raise
  1237. @staticmethod
  1238. def update_dataflow(
  1239. dataflow_id: int,
  1240. data: Dict[str, Any],
  1241. *,
  1242. repository=None,
  1243. ) -> Optional[Dict[str, Any]]:
  1244. """
  1245. 更新数据流
  1246. Args:
  1247. dataflow_id: 数据流ID
  1248. data: 更新的数据
  1249. Returns:
  1250. 更新后的数据流信息,如果不存在则返回None
  1251. """
  1252. try:
  1253. data = copy.deepcopy(data)
  1254. requirement = DataFlowService._decode_script_requirement(
  1255. data.get("script_requirement")
  1256. )
  1257. # 查找节点
  1258. query = "MATCH (n:DataFlow) WHERE id(n) = $dataflow_id RETURN n"
  1259. with connect_graph().session() as session:
  1260. result = session.run(query, dataflow_id=dataflow_id).data()
  1261. if not result:
  1262. return None
  1263. existing = dict(result[0]["n"])
  1264. existing_requirement = (
  1265. DataFlowService._decode_script_requirement(
  1266. existing.get("script_requirement")
  1267. )
  1268. )
  1269. governed = DataFlowService._signals_governed(
  1270. data, requirement
  1271. ) or DataFlowService._signals_governed(
  1272. existing, existing_requirement
  1273. )
  1274. if governed:
  1275. if "draft_reservation" in data:
  1276. raise ValueError(
  1277. "existing DataFlow cannot consume a new draft"
  1278. )
  1279. DataFlowService._reject_governed_execution_fields(data)
  1280. if repository is None:
  1281. from app.core.data_rules.repository import (
  1282. DataRuleRepository,
  1283. )
  1284. repository = DataRuleRepository(db.session)
  1285. requirement = (
  1286. DataFlowService.validate_governed_requirement(
  1287. requirement, repository=repository
  1288. )
  1289. )
  1290. data["script_requirement"] = requirement
  1291. data["script_type"] = "governed"
  1292. data["script_path"] = ""
  1293. data["uid"] = requirement["dataflow_spec"][
  1294. "dataflow_uid"
  1295. ]
  1296. existing_uid = existing.get("uid")
  1297. requested_uid = data["uid"]
  1298. if not existing_uid or str(existing_uid) != requested_uid:
  1299. raise ValueError(
  1300. "dataflow_uid cannot replace an existing identity"
  1301. )
  1302. # 提取 tag 数组(不作为节点属性存储)
  1303. tag_list = data.pop("tag", None)
  1304. # 更新节点属性
  1305. update_fields = []
  1306. params: Dict[str, Any] = {"dataflow_id": dataflow_id}
  1307. for key, value in data.items():
  1308. if key not in ["id", "created_at"]: # 保护字段
  1309. # 复杂对象序列化为 JSON 字符串
  1310. if key in ["config", "script_requirement"] and isinstance(
  1311. value, dict
  1312. ):
  1313. value = json.dumps(value, ensure_ascii=False)
  1314. update_fields.append(f"n.{key} = ${key}")
  1315. params[key] = value
  1316. if update_fields:
  1317. params["updated_at"] = get_formatted_time()
  1318. update_fields.append("n.updated_at = $updated_at")
  1319. update_query = f"""
  1320. MATCH (n:DataFlow) WHERE id(n) = $dataflow_id
  1321. SET {", ".join(update_fields)}
  1322. RETURN n, id(n) as node_id
  1323. """
  1324. result = session.run(update_query, params).data()
  1325. # 处理 tag 关系(支持多标签数组)
  1326. if tag_list is not None:
  1327. # 确保是列表格式
  1328. if not isinstance(tag_list, list):
  1329. tag_list = [tag_list] if tag_list else []
  1330. # 先删除现有的 LABEL 关系
  1331. delete_query = """
  1332. MATCH (n:DataFlow)-[r:LABEL]->(:DataLabel)
  1333. WHERE id(n) = $dataflow_id
  1334. DELETE r
  1335. """
  1336. session.run(delete_query, dataflow_id=dataflow_id)
  1337. logger.info(f"删除数据流 {dataflow_id} 的现有标签关系")
  1338. # 为每个 tag 创建新的 LABEL 关系
  1339. for tag_item in tag_list:
  1340. tag_id = None
  1341. if isinstance(tag_item, dict) and "id" in tag_item:
  1342. tag_id = int(tag_item["id"])
  1343. elif isinstance(tag_item, (int, str)):
  1344. with contextlib.suppress(ValueError, TypeError):
  1345. tag_id = int(tag_item)
  1346. if tag_id:
  1347. DataFlowService._handle_single_tag_relationship(
  1348. dataflow_id, tag_id
  1349. )
  1350. if result:
  1351. node = result[0]["n"]
  1352. updated_dataflow = dict(node)
  1353. # 使用查询返回的node_id
  1354. updated_dataflow["id"] = result[0]["node_id"]
  1355. # 查询并添加标签数组到返回数据
  1356. tags_query = """
  1357. MATCH (n:DataFlow)
  1358. WHERE id(n) = $dataflow_id
  1359. OPTIONAL MATCH (n)-[:LABEL]->(label:DataLabel)
  1360. RETURN collect({
  1361. id: id(label),
  1362. name_zh: label.name_zh,
  1363. name_en: label.name_en
  1364. }) as tags
  1365. """
  1366. tags_result = session.run(
  1367. tags_query, dataflow_id=dataflow_id
  1368. ).single()
  1369. if tags_result:
  1370. tags = tags_result.get("tags", [])
  1371. updated_dataflow["tag"] = [
  1372. tag for tag in tags if tag.get("id") is not None
  1373. ]
  1374. else:
  1375. updated_dataflow["tag"] = []
  1376. logger.info(f"更新数据流成功: ID={dataflow_id}")
  1377. return updated_dataflow
  1378. return None
  1379. except Exception as e:
  1380. logger.error(f"更新数据流失败: {str(e)}")
  1381. raise e
  1382. @staticmethod
  1383. def delete_dataflow(dataflow_id: int) -> bool:
  1384. """
  1385. 删除数据流
  1386. Args:
  1387. dataflow_id: 数据流ID
  1388. Returns:
  1389. 删除是否成功
  1390. """
  1391. try:
  1392. # 删除节点及其关系
  1393. query = """
  1394. MATCH (n:DataFlow) WHERE id(n) = $dataflow_id
  1395. DETACH DELETE n
  1396. RETURN count(n) as deleted_count
  1397. """
  1398. with connect_graph().session() as session:
  1399. delete_result = session.run(query, dataflow_id=dataflow_id).single()
  1400. result = delete_result["deleted_count"] if delete_result else 0
  1401. if result and result > 0:
  1402. logger.info(f"删除数据流成功: ID={dataflow_id}")
  1403. return True
  1404. return False
  1405. except Exception as e:
  1406. logger.error(f"删除数据流失败: {str(e)}")
  1407. raise e
  1408. # 无 COME_FROM 关系时使用显式环境配置;默认仅指向本机,禁止回退内网地址。
  1409. DEFAULT_DATA_SOURCE = {
  1410. "type": "postgresql",
  1411. "host": os.environ.get("DATAFLOW_DEFAULT_DB_HOST", "127.0.0.1"),
  1412. "port": int(os.environ.get("DATAFLOW_DEFAULT_DB_PORT", "5432")),
  1413. "database": os.environ.get("DATAFLOW_DEFAULT_DB_NAME", "dataops"),
  1414. "schema": os.environ.get("DATAFLOW_SCHEMA", "dags"),
  1415. }
  1416. @staticmethod
  1417. def _generate_businessdomain_ddl(
  1418. session,
  1419. bd_id: int,
  1420. is_target: bool = False,
  1421. update_mode: str = "append",
  1422. ) -> Optional[Dict[str, Any]]:
  1423. """
  1424. 根据BusinessDomain节点ID生成DDL
  1425. Args:
  1426. session: Neo4j session对象
  1427. bd_id: BusinessDomain节点ID
  1428. is_target: 是否为目标表(目标表需要添加create_time字段)
  1429. update_mode: 更新模式(append或full)
  1430. Returns:
  1431. 包含ddl和data_source信息的字典,如果节点不存在则返回None
  1432. data_source始终返回,如果没有COME_FROM关系则使用显式环境配置
  1433. """
  1434. try:
  1435. # 查询BusinessDomain节点、元数据、标签关系和数据源关系
  1436. cypher = """
  1437. MATCH (bd:BusinessDomain)
  1438. WHERE id(bd) = $bd_id
  1439. OPTIONAL MATCH (bd)-[:INCLUDES]->(m:DataMeta)
  1440. OPTIONAL MATCH (bd)-[:LABEL]->(label:DataLabel)
  1441. OPTIONAL MATCH (bd)-[:COME_FROM]->(ds:DataSource)
  1442. RETURN bd,
  1443. collect(DISTINCT m) as metadata,
  1444. collect(DISTINCT {
  1445. id: id(label),
  1446. name_zh: label.name_zh,
  1447. name_en: label.name_en
  1448. }) as labels,
  1449. ds.type as ds_type,
  1450. ds.host as ds_host,
  1451. ds.port as ds_port,
  1452. ds.database as ds_database,
  1453. ds.schema as ds_schema
  1454. """
  1455. result = session.run(cypher, bd_id=bd_id).single()
  1456. if not result or not result["bd"]:
  1457. logger.warning(f"未找到ID为 {bd_id} 的BusinessDomain节点")
  1458. return None
  1459. node = result["bd"]
  1460. metadata = result["metadata"]
  1461. # 生成DDL
  1462. node_props = dict(node)
  1463. table_name = node_props.get("name_en", f"table_{bd_id}")
  1464. ddl_lines = []
  1465. ddl_lines.append(f"CREATE TABLE {table_name} (")
  1466. column_definitions = []
  1467. # 添加元数据列
  1468. if metadata:
  1469. for meta in metadata:
  1470. if meta:
  1471. meta_props = dict(meta)
  1472. column_name = meta_props.get(
  1473. "name_en",
  1474. meta_props.get("name_zh", "unknown_column"),
  1475. )
  1476. data_type = meta_props.get("data_type", "VARCHAR(255)")
  1477. comment = meta_props.get("name_zh", "")
  1478. column_def = f" {column_name} {data_type}"
  1479. if comment:
  1480. column_def += f" COMMENT '{comment}'"
  1481. column_definitions.append(column_def)
  1482. # 如果没有元数据,添加默认主键
  1483. if not column_definitions:
  1484. column_definitions.append(" id BIGINT PRIMARY KEY COMMENT '主键ID'")
  1485. # 如果是目标表,添加create_time字段
  1486. if is_target:
  1487. column_definitions.append(
  1488. " create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP "
  1489. "COMMENT '数据创建时间'"
  1490. )
  1491. ddl_lines.append(",\n".join(column_definitions))
  1492. ddl_lines.append(");")
  1493. # 添加表注释
  1494. table_comment = node_props.get(
  1495. "name_zh", node_props.get("describe", table_name)
  1496. )
  1497. if table_comment and table_comment != table_name:
  1498. ddl_lines.append(f"COMMENT ON TABLE {table_name} IS '{table_comment}';")
  1499. ddl_content = "\n".join(ddl_lines)
  1500. # 始终返回数据源信息
  1501. # 如果通过COME_FROM关系找到了数据源,使用该数据源
  1502. # 否则使用默认的生产环境数据库配置
  1503. if result["ds_type"]:
  1504. data_source = {
  1505. "type": result["ds_type"],
  1506. "host": result["ds_host"],
  1507. "port": result["ds_port"],
  1508. "database": result["ds_database"],
  1509. "schema": result["ds_schema"],
  1510. }
  1511. # 端口验证:确保数据库类型使用正确的端口
  1512. # PostgreSQL 默认端口 5432,MySQL 默认端口 3306
  1513. # 5678 是 n8n 服务端口,不是数据库端口
  1514. ds_type_lower = (result["ds_type"] or "").lower()
  1515. current_port = data_source.get("port")
  1516. # 定义数据库类型与默认端口的映射
  1517. db_default_ports = {
  1518. "postgresql": 5432,
  1519. "postgres": 5432,
  1520. "mysql": 3306,
  1521. "mariadb": 3306,
  1522. "sqlserver": 1433,
  1523. "mssql": 1433,
  1524. "oracle": 1521,
  1525. }
  1526. # 常见的非数据库端口(需要修正)
  1527. invalid_db_ports = {5678, 8080, 80, 443, 8000, 3000}
  1528. if ds_type_lower in db_default_ports:
  1529. expected_port = db_default_ports[ds_type_lower]
  1530. if current_port in invalid_db_ports:
  1531. logger.warning(
  1532. f"检测到数据源端口配置异常: type={ds_type_lower}, "
  1533. f"port={current_port}(疑似非数据库端口),"
  1534. f"已自动修正为默认端口 {expected_port}"
  1535. )
  1536. data_source["port"] = expected_port
  1537. elif current_port is None:
  1538. logger.info(f"数据源端口为空,使用默认端口: {expected_port}")
  1539. data_source["port"] = expected_port
  1540. logger.info(f"通过COME_FROM关系获取到数据源信息: {data_source}")
  1541. else:
  1542. # 使用默认生产环境数据源配置
  1543. data_source = DataFlowService.DEFAULT_DATA_SOURCE.copy()
  1544. logger.info(
  1545. f"未找到COME_FROM关系,使用默认生产环境数据源: {data_source}"
  1546. )
  1547. logger.debug(
  1548. f"生成BusinessDomain DDL成功: {table_name}, is_target={is_target}"
  1549. )
  1550. return {
  1551. "ddl": ddl_content,
  1552. "table_name": table_name,
  1553. "data_source": data_source,
  1554. }
  1555. except Exception as e:
  1556. logger.error(f"生成BusinessDomain DDL失败,ID={bd_id}: {str(e)}")
  1557. return None
  1558. @staticmethod
  1559. def _handle_script_relationships(
  1560. data: Dict[str, Any],
  1561. dataflow_name: str,
  1562. name_en: str,
  1563. ):
  1564. """
  1565. 处理脚本关系,在Neo4j图数据库中创建从source BusinessDomain到DataFlow的
  1566. INPUT关系,以及从DataFlow到target BusinessDomain的OUTPUT关系。
  1567. 关系模型:
  1568. - (source:BusinessDomain)-[:INPUT]->(dataflow:DataFlow)
  1569. - (dataflow:DataFlow)-[:OUTPUT]->(target:BusinessDomain)
  1570. Args:
  1571. data: 包含脚本信息的数据字典,应包含script_name, script_type,
  1572. schedule_status, source_table, target_table, update_mode
  1573. """
  1574. try:
  1575. # 从data中读取键值对
  1576. source_table_full = data.get("source_table", "")
  1577. target_table_full = data.get("target_table", "")
  1578. # 处理source_table和target_table的格式
  1579. # 格式: "label:name" 或 直接 "name"
  1580. source_table = (
  1581. source_table_full.split(":")[-1]
  1582. if ":" in source_table_full
  1583. else source_table_full
  1584. )
  1585. target_table = (
  1586. target_table_full.split(":")[-1]
  1587. if ":" in target_table_full
  1588. else target_table_full
  1589. )
  1590. source_label = (
  1591. source_table_full.split(":")[0]
  1592. if ":" in source_table_full
  1593. else "BusinessDomain"
  1594. )
  1595. target_label = (
  1596. target_table_full.split(":")[0]
  1597. if ":" in target_table_full
  1598. else "BusinessDomain"
  1599. )
  1600. # 验证必要字段
  1601. if not source_table or not target_table:
  1602. logger.warning(
  1603. "source_table或target_table为空,跳过关系创建: "
  1604. "source_table=%s, target_table=%s",
  1605. source_table,
  1606. target_table,
  1607. )
  1608. return
  1609. logger.info(
  1610. "开始创建INPUT/OUTPUT关系: %s -[INPUT]-> %s -[OUTPUT]-> %s",
  1611. source_table,
  1612. dataflow_name,
  1613. target_table,
  1614. )
  1615. with connect_graph().session() as session:
  1616. # 步骤1:获取DataFlow节点ID
  1617. dataflow_query = """
  1618. MATCH (df:DataFlow {name_zh: $dataflow_name})
  1619. RETURN id(df) as dataflow_id
  1620. """
  1621. df_result = session.run(
  1622. dataflow_query, # type: ignore[arg-type]
  1623. {"dataflow_name": dataflow_name},
  1624. ).single()
  1625. if not df_result:
  1626. logger.error(f"未找到DataFlow节点: {dataflow_name}")
  1627. return
  1628. dataflow_id = df_result["dataflow_id"]
  1629. # 步骤2:获取或创建source节点
  1630. # 优先通过name_en匹配,其次通过name匹配
  1631. source_query = f"""
  1632. MATCH (source:{source_label})
  1633. WHERE source.name_en = $source_table OR source.name = $source_table
  1634. RETURN id(source) as source_id
  1635. LIMIT 1
  1636. """
  1637. source_result = session.run(
  1638. source_query, # type: ignore[arg-type]
  1639. {"source_table": source_table},
  1640. ).single()
  1641. if not source_result:
  1642. logger.warning(
  1643. "未找到source节点: %s,将创建新节点",
  1644. source_table,
  1645. )
  1646. # 创建source节点
  1647. create_source_query = f"""
  1648. CREATE (source:{source_label} {{
  1649. name: $source_table,
  1650. name_en: $source_table,
  1651. created_at: $created_at,
  1652. type: 'source'
  1653. }})
  1654. RETURN id(source) as source_id
  1655. """
  1656. source_result = session.run(
  1657. create_source_query, # type: ignore[arg-type]
  1658. {
  1659. "source_table": source_table,
  1660. "created_at": get_formatted_time(),
  1661. },
  1662. ).single()
  1663. source_id = source_result["source_id"] if source_result else None
  1664. # 步骤3:获取或创建target节点
  1665. target_query = f"""
  1666. MATCH (target:{target_label})
  1667. WHERE target.name_en = $target_table OR target.name = $target_table
  1668. RETURN id(target) as target_id
  1669. LIMIT 1
  1670. """
  1671. target_result = session.run(
  1672. target_query, # type: ignore[arg-type]
  1673. {"target_table": target_table},
  1674. ).single()
  1675. if not target_result:
  1676. logger.warning(
  1677. "未找到target节点: %s,将创建新节点",
  1678. target_table,
  1679. )
  1680. # 创建target节点
  1681. create_target_query = f"""
  1682. CREATE (target:{target_label} {{
  1683. name: $target_table,
  1684. name_en: $target_table,
  1685. created_at: $created_at,
  1686. type: 'target'
  1687. }})
  1688. RETURN id(target) as target_id
  1689. """
  1690. target_result = session.run(
  1691. create_target_query, # type: ignore[arg-type]
  1692. {
  1693. "target_table": target_table,
  1694. "created_at": get_formatted_time(),
  1695. },
  1696. ).single()
  1697. target_id = target_result["target_id"] if target_result else None
  1698. if not source_id or not target_id:
  1699. logger.error(
  1700. "无法获取source或target节点ID: source_id=%s, target_id=%s",
  1701. source_id,
  1702. target_id,
  1703. )
  1704. return
  1705. # 步骤4:创建 INPUT 关系 (source)-[:INPUT]->(dataflow)
  1706. create_input_query = """
  1707. MATCH (source), (dataflow:DataFlow)
  1708. WHERE id(source) = $source_id AND id(dataflow) = $dataflow_id
  1709. MERGE (source)-[r:INPUT]->(dataflow)
  1710. ON CREATE SET r.created_at = $created_at
  1711. ON MATCH SET r.updated_at = $created_at
  1712. RETURN r
  1713. """
  1714. input_result = session.run(
  1715. create_input_query, # type: ignore[arg-type]
  1716. {
  1717. "source_id": source_id,
  1718. "dataflow_id": dataflow_id,
  1719. "created_at": get_formatted_time(),
  1720. },
  1721. ).single()
  1722. if input_result:
  1723. logger.info(
  1724. "成功创建INPUT关系: %s -> %s",
  1725. source_table,
  1726. dataflow_name,
  1727. )
  1728. else:
  1729. logger.warning(
  1730. "INPUT关系创建失败或已存在: %s -> %s",
  1731. source_table,
  1732. dataflow_name,
  1733. )
  1734. # 步骤5:创建 OUTPUT 关系 (dataflow)-[:OUTPUT]->(target)
  1735. create_output_query = """
  1736. MATCH (dataflow:DataFlow), (target)
  1737. WHERE id(dataflow) = $dataflow_id AND id(target) = $target_id
  1738. MERGE (dataflow)-[r:OUTPUT]->(target)
  1739. ON CREATE SET r.created_at = $created_at
  1740. ON MATCH SET r.updated_at = $created_at
  1741. RETURN r
  1742. """
  1743. output_result = session.run(
  1744. create_output_query, # type: ignore[arg-type]
  1745. {
  1746. "dataflow_id": dataflow_id,
  1747. "target_id": target_id,
  1748. "created_at": get_formatted_time(),
  1749. },
  1750. ).single()
  1751. if output_result:
  1752. logger.info(
  1753. "成功创建OUTPUT关系: %s -> %s",
  1754. dataflow_name,
  1755. target_table,
  1756. )
  1757. else:
  1758. logger.warning(
  1759. "OUTPUT关系创建失败或已存在: %s -> %s",
  1760. dataflow_name,
  1761. target_table,
  1762. )
  1763. logger.info(
  1764. "血缘关系创建完成: %s -[INPUT]-> %s -[OUTPUT]-> %s",
  1765. source_table,
  1766. dataflow_name,
  1767. target_table,
  1768. )
  1769. except Exception as e:
  1770. logger.error(f"处理脚本关系失败: {str(e)}")
  1771. raise e
  1772. @staticmethod
  1773. def get_business_domain_list() -> List[Dict[str, Any]]:
  1774. """
  1775. 获取BusinessDomain节点列表
  1776. Returns:
  1777. BusinessDomain节点列表,每个节点包含 id, name_zh, name_en, tag
  1778. """
  1779. try:
  1780. logger.info("开始查询BusinessDomain节点列表")
  1781. with connect_graph().session() as session:
  1782. # 查询所有BusinessDomain节点及其LABEL关系指向的标签(支持多标签)
  1783. query = """
  1784. MATCH (bd:BusinessDomain)
  1785. OPTIONAL MATCH (bd)-[:LABEL]->(label:DataLabel)
  1786. RETURN id(bd) as id,
  1787. bd.name_zh as name_zh,
  1788. bd.name_en as name_en,
  1789. bd.create_time as create_time,
  1790. collect({
  1791. id: id(label),
  1792. name_zh: label.name_zh,
  1793. name_en: label.name_en
  1794. }) as tags
  1795. ORDER BY create_time DESC
  1796. """
  1797. result = session.run(query)
  1798. bd_list = []
  1799. for record in result:
  1800. # 处理标签数组,过滤掉空标签
  1801. tags = record.get("tags", [])
  1802. tag_list = [tag for tag in tags if tag.get("id") is not None]
  1803. bd_item = {
  1804. "id": record["id"],
  1805. "name_zh": record.get("name_zh", "") or "",
  1806. "name_en": record.get("name_en", "") or "",
  1807. "tag": tag_list,
  1808. }
  1809. bd_list.append(bd_item)
  1810. logger.info(f"成功查询到 {len(bd_list)} 个BusinessDomain节点")
  1811. return bd_list
  1812. except Exception as e:
  1813. logger.error(f"查询BusinessDomain节点列表失败: {str(e)}")
  1814. raise e
  1815. @staticmethod
  1816. def _register_data_product(
  1817. data: Dict[str, Any],
  1818. dataflow_name: str,
  1819. name_en: str,
  1820. dataflow_id: Optional[int] = None,
  1821. ) -> None:
  1822. """
  1823. 注册数据产品到数据服务
  1824. 当数据流创建成功后,自动将其注册为数据产品,
  1825. 以便在数据服务模块中展示和管理。
  1826. 从 script_requirement.target_table 中获取 BusinessDomain ID,
  1827. 然后查询 Neo4j 获取对应节点的 name_zh 和 name_en 作为数据产品名称。
  1828. Args:
  1829. data: 数据流配置数据
  1830. dataflow_name: 数据流名称(中文)
  1831. name_en: 数据流英文名
  1832. dataflow_id: 数据流ID(Neo4j节点ID)
  1833. """
  1834. try:
  1835. # 从script_requirement中获取target_table(BusinessDomain ID列表)
  1836. script_requirement = data.get("script_requirement")
  1837. description = data.get("describe", "")
  1838. # 解析 script_requirement
  1839. req_json: Optional[Dict[str, Any]] = None
  1840. if script_requirement:
  1841. if isinstance(script_requirement, dict):
  1842. req_json = script_requirement
  1843. elif isinstance(script_requirement, str):
  1844. try:
  1845. parsed = json.loads(script_requirement)
  1846. if isinstance(parsed, dict):
  1847. req_json = parsed
  1848. except (json.JSONDecodeError, TypeError):
  1849. pass
  1850. # 获取target_table中的BusinessDomain ID列表
  1851. target_bd_ids: List[int] = []
  1852. if req_json:
  1853. target_table_ids = req_json.get("target_table", [])
  1854. if isinstance(target_table_ids, list):
  1855. target_bd_ids = [
  1856. int(bid) for bid in target_table_ids if bid is not None
  1857. ]
  1858. elif target_table_ids is not None:
  1859. target_bd_ids = [int(target_table_ids)]
  1860. # 如果有rule字段,添加到描述中
  1861. rule = req_json.get("rule", "")
  1862. if rule and not description:
  1863. description = rule
  1864. # 如果没有target_table ID,则不注册数据产品
  1865. if not target_bd_ids:
  1866. logger.warning(
  1867. f"数据流 {dataflow_name} 没有指定target_table,跳过数据产品注册"
  1868. )
  1869. return
  1870. # 从Neo4j查询每个BusinessDomain节点的name_zh和name_en,以及关联数据源的schema
  1871. with connect_graph().session() as session:
  1872. for bd_id in target_bd_ids:
  1873. try:
  1874. # 查询BusinessDomain节点信息及其关联的数据源schema
  1875. query = """
  1876. MATCH (bd:BusinessDomain)
  1877. WHERE id(bd) = $bd_id
  1878. OPTIONAL MATCH (bd)-[:COME_FROM]->(ds:DataSource)
  1879. RETURN bd.name_zh as name_zh,
  1880. bd.name_en as name_en,
  1881. bd.describe as describe,
  1882. ds.schema as ds_schema
  1883. """
  1884. result = session.run(query, bd_id=bd_id).single()
  1885. if not result:
  1886. logger.warning(
  1887. f"未找到ID为 {bd_id} 的BusinessDomain节点,跳过"
  1888. )
  1889. continue
  1890. # 使用BusinessDomain节点的name_zh和name_en
  1891. product_name = result.get("name_zh") or ""
  1892. product_name_en = result.get("name_en") or ""
  1893. # 如果没有name_zh,使用name_en
  1894. if not product_name:
  1895. product_name = product_name_en
  1896. # 如果没有name_en,使用name_zh转换
  1897. if not product_name_en:
  1898. product_name_en = product_name.lower().replace(" ", "_")
  1899. # 目标表名使用BusinessDomain的name_en
  1900. target_table = product_name_en
  1901. # 如果BusinessDomain有describe且当前description为空,使用它
  1902. bd_describe = result.get("describe") or ""
  1903. if bd_describe and not description:
  1904. description = bd_describe
  1905. # 从关联的数据源获取schema,如果没有则默认为public
  1906. target_schema = result.get("ds_schema") or "public"
  1907. # 调用数据产品服务进行注册
  1908. DataProductService.register_data_product(
  1909. product_name=product_name,
  1910. product_name_en=product_name_en,
  1911. target_table=target_table,
  1912. target_schema=target_schema,
  1913. description=description,
  1914. source_dataflow_id=dataflow_id,
  1915. source_dataflow_name=dataflow_name,
  1916. created_by=data.get("created_by", "dataflow"),
  1917. )
  1918. logger.info(
  1919. f"数据产品注册成功: {product_name} -> "
  1920. f"{target_schema}.{target_table}"
  1921. )
  1922. except Exception as bd_error:
  1923. logger.error(
  1924. f"处理BusinessDomain {bd_id} 失败: {str(bd_error)}"
  1925. )
  1926. # 继续处理下一个
  1927. except Exception as e:
  1928. logger.error(f"注册数据产品失败: {str(e)}")
  1929. raise