dataflows.py 93 KB

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