pg_requirement_store.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. """
  2. PostgreSQL requirement 存储封装
  3. 用于存储和检索需求数据,支持向量检索。
  4. 表名:requirement(从 requirement_table 迁移)
  5. """
  6. import os
  7. import json
  8. import psycopg2
  9. from psycopg2.extras import RealDictCursor
  10. from typing import List, Dict, Optional
  11. from dotenv import load_dotenv
  12. from knowhub.knowhub_db.cascade import cascade_delete
  13. load_dotenv()
  14. # 关联字段子查询。knowledge 边暴露两种视图:knowledge_ids(扁平)+ knowledge_links(含 type)
  15. _REL_SUBQUERY = """
  16. (SELECT COALESCE(json_agg(rc.capability_id), '[]'::json)
  17. FROM requirement_capability rc WHERE rc.requirement_id = requirement.id) AS capability_ids,
  18. (SELECT COALESCE(json_agg(rk.knowledge_id), '[]'::json)
  19. FROM requirement_knowledge rk WHERE rk.requirement_id = requirement.id) AS knowledge_ids,
  20. (SELECT COALESCE(json_agg(json_build_object(
  21. 'id', rk2.knowledge_id, 'relation_type', rk2.relation_type
  22. )), '[]'::json)
  23. FROM requirement_knowledge rk2 WHERE rk2.requirement_id = requirement.id) AS knowledge_links,
  24. (SELECT COALESCE(json_agg(rr.resource_id), '[]'::json)
  25. FROM requirement_resource rr WHERE rr.requirement_id = requirement.id) AS resource_ids,
  26. (SELECT COALESCE(json_agg(rs.strategy_id), '[]'::json)
  27. FROM requirement_strategy rs WHERE rs.requirement_id = requirement.id) AS strategy_ids
  28. """
  29. _BASE_FIELDS = "id, description, source_nodes, status, match_result, version"
  30. _SELECT_FIELDS = f"{_BASE_FIELDS}, {_REL_SUBQUERY}"
  31. def _normalize_links(data: Dict, links_key: str, ids_key: str, default_type: str):
  32. """两种输入格式统一:{links_key: [{id, relation_type}]} 或 {ids_key: [id]}"""
  33. if links_key in data and data[links_key] is not None:
  34. out = []
  35. for item in data[links_key]:
  36. if isinstance(item, dict):
  37. out.append((item['id'], item.get('relation_type', default_type)))
  38. else:
  39. out.append((item, default_type))
  40. return out
  41. if ids_key in data and data[ids_key] is not None:
  42. return [(i, default_type) for i in data[ids_key]]
  43. return None
  44. class PostgreSQLRequirementStore:
  45. def __init__(self):
  46. """初始化 PostgreSQL 连接"""
  47. self.conn = psycopg2.connect(
  48. host=os.getenv('KNOWHUB_DB'),
  49. port=int(os.getenv('KNOWHUB_PORT', 5432)),
  50. user=os.getenv('KNOWHUB_USER'),
  51. password=os.getenv('KNOWHUB_PASSWORD'),
  52. database=os.getenv('KNOWHUB_DB_NAME')
  53. )
  54. self.conn.autocommit = True
  55. print(f"[PostgreSQL Requirement] 已连接到远程数据库: {os.getenv('KNOWHUB_DB')}")
  56. def _reconnect(self):
  57. self.conn = psycopg2.connect(
  58. host=os.getenv('KNOWHUB_DB'),
  59. port=int(os.getenv('KNOWHUB_PORT', 5432)),
  60. user=os.getenv('KNOWHUB_USER'),
  61. password=os.getenv('KNOWHUB_PASSWORD'),
  62. database=os.getenv('KNOWHUB_DB_NAME')
  63. )
  64. self.conn.autocommit = True
  65. def _ensure_connection(self):
  66. if self.conn.closed != 0:
  67. self._reconnect()
  68. else:
  69. try:
  70. c = self.conn.cursor()
  71. c.execute("SELECT 1")
  72. c.close()
  73. except (psycopg2.OperationalError, psycopg2.InterfaceError):
  74. self._reconnect()
  75. def _get_cursor(self):
  76. self._ensure_connection()
  77. return self.conn.cursor(cursor_factory=RealDictCursor)
  78. def insert_or_update(self, requirement: Dict):
  79. """插入或更新需求记录。AnalyticDB beam 表不支持 ON CONFLICT UPDATE 当含 ALTER 新增列,改用 DELETE+INSERT。"""
  80. cursor = self._get_cursor()
  81. try:
  82. cursor.execute("DELETE FROM requirement WHERE id = %s", (requirement['id'],))
  83. cursor.execute("""
  84. INSERT INTO requirement (
  85. id, description, source_nodes, status, match_result, embedding, version
  86. ) VALUES (%s, %s, %s, %s, %s, %s, %s)
  87. """, (
  88. requirement['id'],
  89. requirement.get('description', ''),
  90. json.dumps(requirement.get('source_nodes', [])),
  91. requirement.get('status', '未满足'),
  92. requirement.get('match_result', ''),
  93. requirement.get('embedding'),
  94. requirement.get('version', 'v0'),
  95. ))
  96. # 写入关联表
  97. req_id = requirement['id']
  98. if 'capability_ids' in requirement:
  99. cursor.execute("DELETE FROM requirement_capability WHERE requirement_id = %s", (req_id,))
  100. for cap_id in requirement['capability_ids']:
  101. cursor.execute(
  102. "INSERT INTO requirement_capability (requirement_id, capability_id) VALUES (%s, %s) ON CONFLICT DO NOTHING",
  103. (req_id, cap_id))
  104. k_links = _normalize_links(requirement, 'knowledge_links', 'knowledge_ids', 'related')
  105. if k_links is not None:
  106. cursor.execute("DELETE FROM requirement_knowledge WHERE requirement_id = %s", (req_id,))
  107. for kid, rtype in k_links:
  108. cursor.execute(
  109. "INSERT INTO requirement_knowledge (requirement_id, knowledge_id, relation_type) "
  110. "VALUES (%s, %s, %s) ON CONFLICT DO NOTHING",
  111. (req_id, kid, rtype))
  112. if 'resource_ids' in requirement and requirement['resource_ids'] is not None:
  113. cursor.execute("DELETE FROM requirement_resource WHERE requirement_id = %s", (req_id,))
  114. for rid in requirement['resource_ids']:
  115. cursor.execute(
  116. "INSERT INTO requirement_resource (requirement_id, resource_id) VALUES (%s, %s) ON CONFLICT DO NOTHING",
  117. (req_id, rid))
  118. if 'strategy_ids' in requirement and requirement['strategy_ids'] is not None:
  119. cursor.execute("DELETE FROM requirement_strategy WHERE requirement_id = %s", (req_id,))
  120. for sid in requirement['strategy_ids']:
  121. cursor.execute(
  122. "INSERT INTO requirement_strategy (requirement_id, strategy_id) VALUES (%s, %s) ON CONFLICT DO NOTHING",
  123. (req_id, sid))
  124. self.conn.commit()
  125. finally:
  126. cursor.close()
  127. def get_by_id(self, req_id: str) -> Optional[Dict]:
  128. """根据 ID 获取需求"""
  129. cursor = self._get_cursor()
  130. try:
  131. cursor.execute(f"""
  132. SELECT {_SELECT_FIELDS}
  133. FROM requirement WHERE id = %s
  134. """, (req_id,))
  135. result = cursor.fetchone()
  136. return self._format_result(result) if result else None
  137. finally:
  138. cursor.close()
  139. def search(self, query_embedding: List[float], limit: int = 10) -> List[Dict]:
  140. """向量检索需求"""
  141. cursor = self._get_cursor()
  142. try:
  143. cursor.execute(f"""
  144. SELECT {_SELECT_FIELDS},
  145. 1 - (embedding <=> %s::real[]) as score
  146. FROM requirement
  147. WHERE embedding IS NOT NULL
  148. ORDER BY embedding <=> %s::real[]
  149. LIMIT %s
  150. """, (query_embedding, query_embedding, limit))
  151. results = cursor.fetchall()
  152. return [self._format_result(r) for r in results]
  153. finally:
  154. cursor.close()
  155. def list_all(self, limit: int = 100, offset: int = 0, status: Optional[str] = None) -> List[Dict]:
  156. """列出需求"""
  157. cursor = self._get_cursor()
  158. try:
  159. if status:
  160. cursor.execute(f"""
  161. SELECT {_SELECT_FIELDS}
  162. FROM requirement
  163. WHERE status = %s
  164. ORDER BY id
  165. LIMIT %s OFFSET %s
  166. """, (status, limit, offset))
  167. else:
  168. cursor.execute(f"""
  169. SELECT {_SELECT_FIELDS}
  170. FROM requirement
  171. ORDER BY id
  172. LIMIT %s OFFSET %s
  173. """, (limit, offset))
  174. results = cursor.fetchall()
  175. return [self._format_result(r) for r in results]
  176. finally:
  177. cursor.close()
  178. def update(self, req_id: str, updates: Dict):
  179. """更新需求字段"""
  180. cursor = self._get_cursor()
  181. try:
  182. # 分离关联字段
  183. cap_ids = updates.pop('capability_ids', None)
  184. strategy_ids = updates.pop('strategy_ids', None)
  185. rel_data = {}
  186. for k in ('knowledge_ids', 'knowledge_links', 'resource_ids'):
  187. if k in updates:
  188. rel_data[k] = updates.pop(k)
  189. if updates:
  190. set_parts = []
  191. params = []
  192. json_fields = ('source_nodes',)
  193. for key, value in updates.items():
  194. set_parts.append(f"{key} = %s")
  195. if key in json_fields:
  196. params.append(json.dumps(value))
  197. else:
  198. params.append(value)
  199. params.append(req_id)
  200. cursor.execute(
  201. f"UPDATE requirement SET {', '.join(set_parts)} WHERE id = %s",
  202. params
  203. )
  204. if cap_ids is not None:
  205. cursor.execute("DELETE FROM requirement_capability WHERE requirement_id = %s", (req_id,))
  206. for cap_id in cap_ids:
  207. cursor.execute(
  208. "INSERT INTO requirement_capability (requirement_id, capability_id) VALUES (%s, %s) ON CONFLICT DO NOTHING",
  209. (req_id, cap_id))
  210. k_links = _normalize_links(rel_data, 'knowledge_links', 'knowledge_ids', 'related')
  211. if k_links is not None:
  212. cursor.execute("DELETE FROM requirement_knowledge WHERE requirement_id = %s", (req_id,))
  213. for kid, rtype in k_links:
  214. cursor.execute(
  215. "INSERT INTO requirement_knowledge (requirement_id, knowledge_id, relation_type) "
  216. "VALUES (%s, %s, %s) ON CONFLICT DO NOTHING",
  217. (req_id, kid, rtype))
  218. if 'resource_ids' in rel_data and rel_data['resource_ids'] is not None:
  219. cursor.execute("DELETE FROM requirement_resource WHERE requirement_id = %s", (req_id,))
  220. for rid in rel_data['resource_ids']:
  221. cursor.execute(
  222. "INSERT INTO requirement_resource (requirement_id, resource_id) VALUES (%s, %s) ON CONFLICT DO NOTHING",
  223. (req_id, rid))
  224. if strategy_ids is not None:
  225. cursor.execute("DELETE FROM requirement_strategy WHERE requirement_id = %s", (req_id,))
  226. for sid in strategy_ids:
  227. cursor.execute(
  228. "INSERT INTO requirement_strategy (requirement_id, strategy_id) VALUES (%s, %s) ON CONFLICT DO NOTHING",
  229. (req_id, sid))
  230. self.conn.commit()
  231. finally:
  232. cursor.close()
  233. def add_knowledge(self, req_id: str, knowledge_id: str, relation_type: str = 'related'):
  234. """增量挂接 requirement-knowledge 边"""
  235. cursor = self._get_cursor()
  236. try:
  237. cursor.execute(
  238. "INSERT INTO requirement_knowledge (requirement_id, knowledge_id, relation_type) "
  239. "VALUES (%s, %s, %s) ON CONFLICT DO NOTHING",
  240. (req_id, knowledge_id, relation_type))
  241. self.conn.commit()
  242. finally:
  243. cursor.close()
  244. def add_resource(self, req_id: str, resource_id: str):
  245. """增量挂接 requirement-resource 边"""
  246. cursor = self._get_cursor()
  247. try:
  248. cursor.execute(
  249. "INSERT INTO requirement_resource (requirement_id, resource_id) VALUES (%s, %s) ON CONFLICT DO NOTHING",
  250. (req_id, resource_id))
  251. self.conn.commit()
  252. finally:
  253. cursor.close()
  254. def add_strategy(self, req_id: str, strategy_id: str):
  255. """增量挂接 requirement-strategy 边(该 strategy 满足此 requirement)"""
  256. cursor = self._get_cursor()
  257. try:
  258. cursor.execute(
  259. "INSERT INTO requirement_strategy (requirement_id, strategy_id) VALUES (%s, %s) ON CONFLICT DO NOTHING",
  260. (req_id, strategy_id))
  261. self.conn.commit()
  262. finally:
  263. cursor.close()
  264. def delete(self, req_id: str):
  265. """删除需求及其关联表记录"""
  266. cursor = self._get_cursor()
  267. try:
  268. cascade_delete(cursor, 'requirement', req_id)
  269. self.conn.commit()
  270. finally:
  271. cursor.close()
  272. def count(self, status: Optional[str] = None) -> int:
  273. """统计需求总数"""
  274. cursor = self._get_cursor()
  275. try:
  276. if status:
  277. cursor.execute("SELECT COUNT(*) as count FROM requirement WHERE status = %s", (status,))
  278. else:
  279. cursor.execute("SELECT COUNT(*) as count FROM requirement")
  280. return cursor.fetchone()['count']
  281. finally:
  282. cursor.close()
  283. def _format_result(self, row: Dict) -> Dict:
  284. """格式化查询结果"""
  285. if not row:
  286. return None
  287. result = dict(row)
  288. if 'source_nodes' in result and isinstance(result['source_nodes'], str):
  289. result['source_nodes'] = json.loads(result['source_nodes'])
  290. # 关联字段(来自 junction table 子查询)
  291. for field in ('capability_ids', 'knowledge_ids', 'resource_ids', 'strategy_ids', 'knowledge_links'):
  292. if field in result and isinstance(result[field], str):
  293. result[field] = json.loads(result[field])
  294. elif field in result and result[field] is None:
  295. result[field] = []
  296. return result
  297. def close(self):
  298. if self.conn:
  299. self.conn.close()