pg_requirement_store.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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"
  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. """插入或更新需求记录"""
  80. cursor = self._get_cursor()
  81. try:
  82. cursor.execute("""
  83. INSERT INTO requirement (
  84. id, description, source_nodes, status, match_result, embedding
  85. ) VALUES (%s, %s, %s, %s, %s, %s)
  86. ON CONFLICT (id) DO UPDATE SET
  87. description = EXCLUDED.description,
  88. source_nodes = EXCLUDED.source_nodes,
  89. status = EXCLUDED.status,
  90. match_result = EXCLUDED.match_result,
  91. embedding = EXCLUDED.embedding
  92. """, (
  93. requirement['id'],
  94. requirement.get('description', ''),
  95. json.dumps(requirement.get('source_nodes', [])),
  96. requirement.get('status', '未满足'),
  97. requirement.get('match_result', ''),
  98. requirement.get('embedding'),
  99. ))
  100. # 写入关联表
  101. req_id = requirement['id']
  102. if 'capability_ids' in requirement:
  103. cursor.execute("DELETE FROM requirement_capability WHERE requirement_id = %s", (req_id,))
  104. for cap_id in requirement['capability_ids']:
  105. cursor.execute(
  106. "INSERT INTO requirement_capability (requirement_id, capability_id) VALUES (%s, %s) ON CONFLICT DO NOTHING",
  107. (req_id, cap_id))
  108. k_links = _normalize_links(requirement, 'knowledge_links', 'knowledge_ids', 'related')
  109. if k_links is not None:
  110. cursor.execute("DELETE FROM requirement_knowledge WHERE requirement_id = %s", (req_id,))
  111. for kid, rtype in k_links:
  112. cursor.execute(
  113. "INSERT INTO requirement_knowledge (requirement_id, knowledge_id, relation_type) "
  114. "VALUES (%s, %s, %s) ON CONFLICT DO NOTHING",
  115. (req_id, kid, rtype))
  116. if 'resource_ids' in requirement and requirement['resource_ids'] is not None:
  117. cursor.execute("DELETE FROM requirement_resource WHERE requirement_id = %s", (req_id,))
  118. for rid in requirement['resource_ids']:
  119. cursor.execute(
  120. "INSERT INTO requirement_resource (requirement_id, resource_id) VALUES (%s, %s) ON CONFLICT DO NOTHING",
  121. (req_id, rid))
  122. if 'strategy_ids' in requirement and requirement['strategy_ids'] is not None:
  123. cursor.execute("DELETE FROM requirement_strategy WHERE requirement_id = %s", (req_id,))
  124. for sid in requirement['strategy_ids']:
  125. cursor.execute(
  126. "INSERT INTO requirement_strategy (requirement_id, strategy_id) VALUES (%s, %s) ON CONFLICT DO NOTHING",
  127. (req_id, sid))
  128. self.conn.commit()
  129. finally:
  130. cursor.close()
  131. def get_by_id(self, req_id: str) -> Optional[Dict]:
  132. """根据 ID 获取需求"""
  133. cursor = self._get_cursor()
  134. try:
  135. cursor.execute(f"""
  136. SELECT {_SELECT_FIELDS}
  137. FROM requirement WHERE id = %s
  138. """, (req_id,))
  139. result = cursor.fetchone()
  140. return self._format_result(result) if result else None
  141. finally:
  142. cursor.close()
  143. def search(self, query_embedding: List[float], limit: int = 10) -> List[Dict]:
  144. """向量检索需求"""
  145. cursor = self._get_cursor()
  146. try:
  147. cursor.execute(f"""
  148. SELECT {_SELECT_FIELDS},
  149. 1 - (embedding <=> %s::real[]) as score
  150. FROM requirement
  151. WHERE embedding IS NOT NULL
  152. ORDER BY embedding <=> %s::real[]
  153. LIMIT %s
  154. """, (query_embedding, query_embedding, limit))
  155. results = cursor.fetchall()
  156. return [self._format_result(r) for r in results]
  157. finally:
  158. cursor.close()
  159. def list_all(self, limit: int = 100, offset: int = 0, status: Optional[str] = None) -> List[Dict]:
  160. """列出需求"""
  161. cursor = self._get_cursor()
  162. try:
  163. if status:
  164. cursor.execute(f"""
  165. SELECT {_SELECT_FIELDS}
  166. FROM requirement
  167. WHERE status = %s
  168. ORDER BY id
  169. LIMIT %s OFFSET %s
  170. """, (status, limit, offset))
  171. else:
  172. cursor.execute(f"""
  173. SELECT {_SELECT_FIELDS}
  174. FROM requirement
  175. ORDER BY id
  176. LIMIT %s OFFSET %s
  177. """, (limit, offset))
  178. results = cursor.fetchall()
  179. return [self._format_result(r) for r in results]
  180. finally:
  181. cursor.close()
  182. def update(self, req_id: str, updates: Dict):
  183. """更新需求字段"""
  184. cursor = self._get_cursor()
  185. try:
  186. # 分离关联字段
  187. cap_ids = updates.pop('capability_ids', None)
  188. strategy_ids = updates.pop('strategy_ids', None)
  189. rel_data = {}
  190. for k in ('knowledge_ids', 'knowledge_links', 'resource_ids'):
  191. if k in updates:
  192. rel_data[k] = updates.pop(k)
  193. if updates:
  194. set_parts = []
  195. params = []
  196. json_fields = ('source_nodes',)
  197. for key, value in updates.items():
  198. set_parts.append(f"{key} = %s")
  199. if key in json_fields:
  200. params.append(json.dumps(value))
  201. else:
  202. params.append(value)
  203. params.append(req_id)
  204. cursor.execute(
  205. f"UPDATE requirement SET {', '.join(set_parts)} WHERE id = %s",
  206. params
  207. )
  208. if cap_ids is not None:
  209. cursor.execute("DELETE FROM requirement_capability WHERE requirement_id = %s", (req_id,))
  210. for cap_id in cap_ids:
  211. cursor.execute(
  212. "INSERT INTO requirement_capability (requirement_id, capability_id) VALUES (%s, %s) ON CONFLICT DO NOTHING",
  213. (req_id, cap_id))
  214. k_links = _normalize_links(rel_data, 'knowledge_links', 'knowledge_ids', 'related')
  215. if k_links is not None:
  216. cursor.execute("DELETE FROM requirement_knowledge WHERE requirement_id = %s", (req_id,))
  217. for kid, rtype in k_links:
  218. cursor.execute(
  219. "INSERT INTO requirement_knowledge (requirement_id, knowledge_id, relation_type) "
  220. "VALUES (%s, %s, %s) ON CONFLICT DO NOTHING",
  221. (req_id, kid, rtype))
  222. if 'resource_ids' in rel_data and rel_data['resource_ids'] is not None:
  223. cursor.execute("DELETE FROM requirement_resource WHERE requirement_id = %s", (req_id,))
  224. for rid in rel_data['resource_ids']:
  225. cursor.execute(
  226. "INSERT INTO requirement_resource (requirement_id, resource_id) VALUES (%s, %s) ON CONFLICT DO NOTHING",
  227. (req_id, rid))
  228. if strategy_ids is not None:
  229. cursor.execute("DELETE FROM requirement_strategy WHERE requirement_id = %s", (req_id,))
  230. for sid in strategy_ids:
  231. cursor.execute(
  232. "INSERT INTO requirement_strategy (requirement_id, strategy_id) VALUES (%s, %s) ON CONFLICT DO NOTHING",
  233. (req_id, sid))
  234. self.conn.commit()
  235. finally:
  236. cursor.close()
  237. def add_knowledge(self, req_id: str, knowledge_id: str, relation_type: str = 'related'):
  238. """增量挂接 requirement-knowledge 边"""
  239. cursor = self._get_cursor()
  240. try:
  241. cursor.execute(
  242. "INSERT INTO requirement_knowledge (requirement_id, knowledge_id, relation_type) "
  243. "VALUES (%s, %s, %s) ON CONFLICT DO NOTHING",
  244. (req_id, knowledge_id, relation_type))
  245. self.conn.commit()
  246. finally:
  247. cursor.close()
  248. def add_resource(self, req_id: str, resource_id: str):
  249. """增量挂接 requirement-resource 边"""
  250. cursor = self._get_cursor()
  251. try:
  252. cursor.execute(
  253. "INSERT INTO requirement_resource (requirement_id, resource_id) VALUES (%s, %s) ON CONFLICT DO NOTHING",
  254. (req_id, resource_id))
  255. self.conn.commit()
  256. finally:
  257. cursor.close()
  258. def add_strategy(self, req_id: str, strategy_id: str):
  259. """增量挂接 requirement-strategy 边(该 strategy 满足此 requirement)"""
  260. cursor = self._get_cursor()
  261. try:
  262. cursor.execute(
  263. "INSERT INTO requirement_strategy (requirement_id, strategy_id) VALUES (%s, %s) ON CONFLICT DO NOTHING",
  264. (req_id, strategy_id))
  265. self.conn.commit()
  266. finally:
  267. cursor.close()
  268. def delete(self, req_id: str):
  269. """删除需求及其关联表记录"""
  270. cursor = self._get_cursor()
  271. try:
  272. cascade_delete(cursor, 'requirement', req_id)
  273. self.conn.commit()
  274. finally:
  275. cursor.close()
  276. def count(self, status: Optional[str] = None) -> int:
  277. """统计需求总数"""
  278. cursor = self._get_cursor()
  279. try:
  280. if status:
  281. cursor.execute("SELECT COUNT(*) as count FROM requirement WHERE status = %s", (status,))
  282. else:
  283. cursor.execute("SELECT COUNT(*) as count FROM requirement")
  284. return cursor.fetchone()['count']
  285. finally:
  286. cursor.close()
  287. def _format_result(self, row: Dict) -> Dict:
  288. """格式化查询结果"""
  289. if not row:
  290. return None
  291. result = dict(row)
  292. if 'source_nodes' in result and isinstance(result['source_nodes'], str):
  293. result['source_nodes'] = json.loads(result['source_nodes'])
  294. # 关联字段(来自 junction table 子查询)
  295. for field in ('capability_ids', 'knowledge_ids', 'resource_ids', 'strategy_ids', 'knowledge_links'):
  296. if field in result and isinstance(result[field], str):
  297. result[field] = json.loads(result[field])
  298. elif field in result and result[field] is None:
  299. result[field] = []
  300. return result
  301. def close(self):
  302. if self.conn:
  303. self.conn.close()