-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode_graph_db.py
More file actions
191 lines (167 loc) · 5.34 KB
/
code_graph_db.py
File metadata and controls
191 lines (167 loc) · 5.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
#!/usr/bin/env python3
"""
代码图谱统一数据库适配器
屏蔽 simple_graph_sqlite 的真实 schema(nodes 表只有 body TEXT 列,id 从 body JSON 生成)。
所有对 code_graph.sqlite 的读写都通过此模块,避免直接写 SELECT properties FROM nodes。
"""
import os
import json
import sqlite3
import logging
from typing import List, Dict, Optional
logger = logging.getLogger(__name__)
# FAISS 相关文件后缀
FAISS_SUFFIXES = [
".comment.index",
".comment.ids.json",
".comment.meta.json",
".code.index",
".code.ids.json",
".code.meta.json",
]
def _connect(db_path: str) -> sqlite3.Connection:
conn = sqlite3.connect(db_path)
conn.row_factory = sqlite3.Row
return conn
def _parse_body(body_str: str) -> dict:
"""解析 body JSON,保证返回的 dict 中 id 为 int"""
d = json.loads(body_str)
if "id" in d:
try:
d["id"] = int(d["id"])
except (ValueError, TypeError):
pass
return d
def load_all_nodes(db_path: str) -> List[dict]:
"""
加载全部节点。
读取 SELECT id, body FROM nodes,解析 body JSON。
"""
if not os.path.exists(db_path):
return []
conn = _connect(db_path)
try:
cursor = conn.execute("SELECT id, body FROM nodes")
nodes = []
for row in cursor:
body = row["body"]
if not body:
continue
d = _parse_body(body)
# 确保 id 一致:优先用 body 中的 id
if "id" not in d:
d["id"] = int(row["id"]) if row["id"] is not None else 0
nodes.append(d)
return nodes
finally:
conn.close()
def load_node(db_path: str, node_id) -> Optional[dict]:
"""加载单个节点"""
if not os.path.exists(db_path):
return None
conn = _connect(db_path)
try:
cursor = conn.execute("SELECT body FROM nodes WHERE id = ?", (str(node_id),))
row = cursor.fetchone()
if row and row["body"]:
d = _parse_body(row["body"])
if "id" not in d:
d["id"] = int(node_id)
return d
return None
finally:
conn.close()
def load_edges(db_path: str) -> List[dict]:
"""
加载全部边。
source/target 从 TEXT 转为 int 以匹配 node id。
"""
if not os.path.exists(db_path):
return []
conn = _connect(db_path)
try:
cursor = conn.execute("SELECT source, target, properties FROM edges")
edges = []
for row in cursor:
props = json.loads(row["properties"]) if row["properties"] else {}
edges.append({
"source": int(row["source"]),
"target": int(row["target"]),
"properties": props,
})
return edges
finally:
conn.close()
def delete_edge(db_path: str, source, target, properties: Optional[dict] = None) -> int:
"""
Delete edges matching source and target.
If properties is provided, only edges whose parsed JSON properties exactly
match that dict are deleted. Returns the number of deleted rows.
"""
if not os.path.exists(db_path):
return 0
conn = _connect(db_path)
try:
if properties is None:
cursor = conn.execute(
"DELETE FROM edges WHERE source = ? AND target = ?",
(str(source), str(target)),
)
deleted = cursor.rowcount
else:
rows = conn.execute(
"SELECT rowid, properties FROM edges WHERE source = ? AND target = ?",
(str(source), str(target)),
).fetchall()
rowids = []
for row in rows:
edge_props = json.loads(row["properties"]) if row["properties"] else {}
if edge_props == properties:
rowids.append(row["rowid"])
deleted = 0
for rowid in rowids:
cursor = conn.execute("DELETE FROM edges WHERE rowid = ?", (rowid,))
deleted += cursor.rowcount
conn.commit()
return deleted
finally:
conn.close()
def next_numeric_id(db_path: str) -> int:
"""
从现有 nodes 中找最大数字 id,返回 max+1。
如果 DB 不存在或为空,返回 1。
"""
if not os.path.exists(db_path):
return 1
conn = _connect(db_path)
try:
cursor = conn.execute("SELECT body FROM nodes")
max_id = 0
for row in cursor:
if row["body"]:
d = json.loads(row["body"])
nid = d.get("id", 0)
try:
nid = int(nid)
except (ValueError, TypeError):
continue
if nid > max_id:
max_id = nid
return max_id + 1
finally:
conn.close()
def clear_graph_files(db_path: str):
"""
删除 SQLite 文件和同 base name 的 FAISS 文件。
"""
# 删除 SQLite
if os.path.exists(db_path):
os.remove(db_path)
logger.info(f"已删除数据库: {db_path}")
# 删除 FAISS 文件
base_name = os.path.splitext(db_path)[0]
for suffix in FAISS_SUFFIXES:
fpath = base_name + suffix
if os.path.exists(fpath):
os.remove(fpath)
logger.info(f"已删除FAISS文件: {fpath}")