Spaces:
Build error
Build error
github-actions[bot] commited on
Commit ·
f19b7a9
1
Parent(s): 0134a08
Auto-sync from demo at Mon Dec 22 09:30:22 UTC 2025
Browse files12345662 unmodified lines69707172737436 unmodified lines1111121131141151161171181191203 unmodified lines1241251261271281291306 unmodified lines1371381391401411421435 unmodified lines1491501511521531541551561571584 unmodified lines1631641651661671681691701711721731741751763 unmodified lines1801811821831841851866 unmodified lines1931941951961971981991 unmodified line20120220320420520620716 unmodified lines22422522622722822923017 unmodified lines248249250251252253254255256import jsonimport osimport shutilfrom dataclasses import dataclassfrom typing import Any62 unmodified linesdef index_done_callback(self):"""KuzuDB is ACID, changes are immediate, but we can verify generic persistence here."""def has_node(self, node_id: str) -> bool:result = self._conn.execute("MATCH (a:Entity {id: $id}) RETURN count(a)", {"id": node_id}36 unmodified linesresult = self._conn.execute("MATCH (a:Entity {id: $id}) RETURN a.data", {"id": node_id})if result.has_next():data_str = result.get_next()[0]return json.loads(data_str) if data_str else {}return Nonedef update_node(self, node_id: str, node_data: dict[str, str]):current_data = self.get_node(node_id)3 unmodified lines# Merge existing data with new datacurrent_data.update(node_data)json_data = json.dumps(current_data, ensure_ascii=False)self._conn.execute("MATCH (a:Entity {id: $id}) SET a.data = $data",6 unmodified linesnodes = []while result.has_next():row = result.get_next()nodes.append((row[0], json.loads(row[1])))return nodesdef get_edge(self, source_node_id: str, target_node_id: str):5 unmodified linesresult = self._conn.execute(query, {"src": source_node_id, "dst": target_node_id})if result.has_next():data_str = result.get_next()[0]return json.loads(data_str) if data_str else {}return Nonedef update_edge(self, source_node_id: str, target_node_id: str, edge_data: dict[str, str]4 unmodified linesreturncurrent_data.update(edge_data)json_data = json.dumps(current_data, ensure_ascii=False)query = """MATCH (a:Entity {id: $src})-[e:Relation]->(b:Entity {id: $dst})SET e.data = $data"""self._conn.execute(query, {"src": source_node_id, "dst": target_node_id, "data": json_data})def get_all_edges(self) -> Any:3 unmodified linesedges = []while result.has_next():row = result.get_next()edges.append((row[0], row[1], json.loads(row[2])))return edgesdef get_node_edges(self, source_node_id: str) -> Any:6 unmodified linesedges = []while result.has_next():row = result.get_next()edges.append((row[0], row[1], json.loads(row[2])))return edgesdef upsert_node(self, node_id: str, node_data: dict[str, str]):1 unmodified lineInsert or Update node.Kuzu supports MERGE clause (similar to Neo4j) to handle upserts."""json_data = json.dumps(node_data, ensure_ascii=False)query = """MERGE (a:Entity {id: $id})ON MATCH SET a.data = $data16 unmodified linesif not self.has_node(target_node_id):self.upsert_node(target_node_id, {})json_data = json.dumps(edge_data, ensure_ascii=False)query = """MATCH (a:Entity {id: $src}), (b:Entity {id: $dst})MERGE (a)-[e:Relation]->(b)17 unmodified linesdef reload(self):"""For databases that need reloading, KuzuDB auto-manages this."""def drop(self):"""Completely remove the database folder."""if self.db_path and os.path.exists(self.db_path):shutil.rmtree(self.db_path)print(f"Dropped KuzuDB at {self.db_path}")1234562 unmodified lines6869707172737475767778798081828336 unmodified lines1201211221231241251261271281291303 unmodified lines1341351361371381391401411421431446 unmodified lines1511521531541551561571581591601615 unmodified lines1671681691701711721731741751761774 unmodified lines1821831841851861871881891901911921931941951961971981992002013 unmodified lines2052062072082092102112122132142156 unmodified lines2222232242252262272282292302312321 unmodified line23423523623723823924024124224324416 unmodified lines26126226326426526626726826927027127227317 unmodified lines291292293import jsonimport osfrom dataclasses import dataclassfrom typing import Any62 unmodified linesdef index_done_callback(self):"""KuzuDB is ACID, changes are immediate, but we can verify generic persistence here."""@staticmethoddef _safe_json_loads(data_str: str) -> dict:if not isinstance(data_str, str) or not data_str.strip():return {}try:return json.loads(data_str)except json.JSONDecodeError as e:print(f"Error decoding JSON: {e}")return {}def has_node(self, node_id: str) -> bool:result = self._conn.execute("MATCH (a:Entity {id: $id}) RETURN count(a)", {"id": node_id}36 unmodified linesresult = self._conn.execute("MATCH (a:Entity {id: $id}) RETURN a.data", {"id": node_id})if not result.has_next():return Nonedata_str = result.get_next()[0]return self._safe_json_loads(data_str)def update_node(self, node_id: str, node_data: dict[str, str]):current_data = self.get_node(node_id)3 unmodified lines# Merge existing data with new datacurrent_data.update(node_data)try:json_data = json.dumps(current_data, ensure_ascii=False)except (TypeError, ValueError) as e:print(f"Error serializing JSON for node {node_id}: {e}")returnself._conn.execute("MATCH (a:Entity {id: $id}) SET a.data = $data",6 unmodified linesnodes = []while result.has_next():row = result.get_next()if row is None or len(row) < 2:continuenode_id, data_str = row[0], row[1]data = self._safe_json_loads(data_str)nodes.append((node_id, data))return nodesdef get_edge(self, source_node_id: str, target_node_id: str):5 unmodified linesresult = self._conn.execute(query, {"src": source_node_id, "dst": target_node_id})if not result.has_next():return Nonedata_str = result.get_next()[0]return self._safe_json_loads(data_str)def update_edge(self, source_node_id: str, target_node_id: str, edge_data: dict[str, str]4 unmodified linesreturncurrent_data.update(edge_data)try:json_data = json.dumps(current_data, ensure_ascii=False)except (TypeError, ValueError) as e:print(f"Error serializing JSON for edge {source_node_id}->{target_node_id}: {e}")returnself._conn.execute("""MATCH (a:Entity {id: $src})-[e:Relation]->(b:Entity {id: $dst})SET e.data = $data""",{"src": source_node_id, "dst": target_node_id, "data": json_data},)def get_all_edges(self) -> Any:3 unmodified linesedges = []while result.has_next():row = result.get_next()if row is None or len(row) < 3:continuesrc, dst, data_str = row[0], row[1], row[2]data = self._safe_json_loads(data_str)edges.append((src, dst, data))return edgesdef get_node_edges(self, source_node_id: str) -> Any:6 unmodified linesedges = []while result.has_next():row = result.get_next()if row is None or len(row) < 3:continuesrc, dst, data_str = row[0], row[1], row[2]data = self._safe_json_loads(data_str)edges.append((src, dst, data))return edgesdef upsert_node(self, node_id: str, node_data: dict[str, str]):1 unmodified lineInsert or Update node.Kuzu supports MERGE clause (similar to Neo4j) to handle upserts."""try:json_data = json.dumps(node_data, ensure_ascii=False)except (TypeError, ValueError) as e:print(f"Error serializing JSON for node {node_id}: {e}")returnquery = """MERGE (a:Entity {id: $id})ON MATCH SET a.data = $data16 unmodified linesif not self.has_node(target_node_id):self.upsert_node(target_node_id, {})try:json_data = json.dumps(edge_data, ensure_ascii=False)except (TypeError, ValueError) as e:print(f"Error serializing JSON for edge {source_node_id}->{target_node_id}: {e}")returnquery = """MATCH (a:Entity {id: $src}), (b:Entity {id: $dst})MERGE (a)-[e:Relation]->(b)17 unmodified linesdef reload(self):"""For databases that need reloading, KuzuDB auto-manages this."""
graphgen/models/storage/graph/kuzu_storage.py+63-26