from __future__ import annotations
import json
import sqlite3
import threading
from functools import wraps
from contextlib import contextmanager
from collections.abc import Iterator
from pathlib import Path
from typing import Any
from project_brain.graph.models import Edge
from project_brain.graph.store import GraphStore
def _connection_locked(method):
@wraps(method)
def wrapped(self, *args, **kwargs):
with self._lock:
return method(self, *args, **kwargs)
return wrapped
class SqliteStore(GraphStore):
def __init__(self, path: Path):
self.path = Path(path)
self.path.mkdir(parents=True, exist_ok=True)
self.db_path = self.path / "graph.db"
self._lock = threading.RLock()
self._transaction_depth = 0
self.conn = sqlite3.connect(str(self.db_path), check_same_thread=False)
self.conn.row_factory = sqlite3.Row
self.conn.execute("PRAGMA journal_mode=WAL")
self.conn.execute("PRAGMA busy_timeout=5000")
self._init_tables()
@_connection_locked
def _init_tables(self) -> None:
self.conn.execute("""
CREATE TABLE IF NOT EXISTS nodes (
id TEXT PRIMARY KEY,
type TEXT NOT NULL,
data TEXT NOT NULL
)
""")
self.conn.execute("""
CREATE TABLE IF NOT EXISTS edges (
id TEXT PRIMARY KEY,
type TEXT NOT NULL,
source TEXT NOT NULL,
target TEXT NOT NULL,
properties TEXT
)
""")
self.conn.execute("CREATE INDEX IF NOT EXISTS idx_edge_source ON edges(source)")
self.conn.execute("CREATE INDEX IF NOT EXISTS idx_edge_target ON edges(target)")
self.conn.execute("CREATE INDEX IF NOT EXISTS idx_edge_type ON edges(type)")
self.conn.execute("CREATE INDEX IF NOT EXISTS idx_node_type ON nodes(type)")
self.conn.execute("""
CREATE TABLE IF NOT EXISTS metadata (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
)
""")
self._commit_if_needed()
def _commit_if_needed(self) -> None:
if self._transaction_depth == 0:
try:
self.conn.commit()
except BaseException:
self.conn.rollback()
raise
@contextmanager
def transaction(self) -> Iterator["SqliteStore"]:
with self._lock:
outer = self._transaction_depth == 0
if outer:
try:
self.conn.execute("BEGIN IMMEDIATE")
except BaseException:
self.conn.rollback()
raise
self._transaction_depth += 1
try:
try:
yield self
except BaseException:
if outer:
self.conn.rollback()
raise
else:
if outer:
try:
self.conn.commit()
except BaseException:
self.conn.rollback()
raise
finally:
self._transaction_depth -= 1
@_connection_locked
def add_node(self, node: dict[str, Any]) -> None:
self.conn.execute(
"INSERT OR REPLACE INTO nodes (id, type, data) VALUES (?, ?, ?)",
(node["id"], node.get("type", ""), json.dumps(node, ensure_ascii=False)),
)
self._commit_if_needed()
@_connection_locked
def get_node(self, node_id: str) -> dict[str, Any] | None:
row = self.conn.execute("SELECT data FROM nodes WHERE id = ?", (node_id,)).fetchone()
if row:
return json.loads(row["data"])
return None
@_connection_locked
def get_nodes_by_type(self, node_type: str) -> list[dict[str, Any]]:
rows = self.conn.execute("SELECT data FROM nodes WHERE type = ?", (node_type,)).fetchall()
return [json.loads(r["data"]) for r in rows]
@_connection_locked
def get_all_nodes(self) -> list[dict[str, Any]]:
rows = self.conn.execute("SELECT data FROM nodes").fetchall()
return [json.loads(row["data"]) for row in rows]
@_connection_locked
def update_node(self, node_id: str, updates: dict[str, Any]) -> None:
node = self.get_node(node_id)
if node:
node.update(updates)
self.conn.execute(
"UPDATE nodes SET data = ? WHERE id = ?",
(json.dumps(node, ensure_ascii=False), node_id),
)
self._commit_if_needed()
@_connection_locked
def delete_node(self, node_id: str) -> None:
self.conn.execute("DELETE FROM nodes WHERE id = ?", (node_id,))
self._commit_if_needed()
@_connection_locked
def add_edge(self, edge: Edge) -> None:
self.conn.execute(
"INSERT OR REPLACE INTO edges (id, type, source, target, properties) VALUES (?, ?, ?, ?, ?)",
(edge.id, edge.type, edge.source, edge.target, json.dumps(edge.properties)),
)
self._commit_if_needed()
@_connection_locked
def get_edge(self, edge_id: str) -> Edge | None:
row = self.conn.execute(
"SELECT * FROM edges WHERE id = ?", (edge_id,)
).fetchone()
if row is None:
return None
return Edge(
id=row["id"],
type=row["type"],
source=row["source"],
target=row["target"],
properties=json.loads(row["properties"]) if row["properties"] else {},
)
@_connection_locked
def get_edges(
self, node_id: str, edge_type: str | None = None, direction: str = "out"
) -> list[Edge]:
if direction == "out":
query = "SELECT * FROM edges WHERE source = ?"
params: list[Any] = [node_id]
elif direction == "in":
query = "SELECT * FROM edges WHERE target = ?"
params = [node_id]
else:
query = "SELECT * FROM edges WHERE (source = ? OR target = ?)"
params = [node_id, node_id]
if edge_type:
query += " AND type = ?"
params.append(edge_type)
rows = self.conn.execute(query, params).fetchall()
return [
Edge(
id=r["id"],
type=r["type"],
source=r["source"],
target=r["target"],
properties=json.loads(r["properties"]) if r["properties"] else {},
)
for r in rows
]
@_connection_locked
def delete_edges(self, node_id: str) -> None:
self.conn.execute("DELETE FROM edges WHERE source = ? OR target = ?", (node_id, node_id))
self._commit_if_needed()
@_connection_locked
def delete_edges_by_type(self, edge_types: set[str]) -> None:
if not edge_types:
return
placeholders = ",".join("?" for _ in edge_types)
self.conn.execute(
f"DELETE FROM edges WHERE type IN ({placeholders})",
tuple(sorted(edge_types)),
)
self._commit_if_needed()
@_connection_locked
def clear(self) -> None:
self.conn.execute("DELETE FROM edges")
self.conn.execute("DELETE FROM nodes")
self.conn.execute("DELETE FROM metadata")
self._commit_if_needed()
@_connection_locked
def set_metadata(self, key: str, value: Any) -> None:
self.conn.execute(
"INSERT OR REPLACE INTO metadata (key, value) VALUES (?, ?)",
(key, json.dumps(value, ensure_ascii=False)),
)
self._commit_if_needed()
@_connection_locked
def get_metadata(self, key: str, default: Any = None) -> Any:
row = self.conn.execute(
"SELECT value FROM metadata WHERE key = ?", (key,),
).fetchone()
if row is None:
return default
try:
return json.loads(row["value"])
except (TypeError, ValueError):
return default
@_connection_locked
def get_all_edges(self) -> list[Edge]:
rows = self.conn.execute(
"SELECT id, type, source, target, properties FROM edges"
).fetchall()
return [
Edge(
id=r[0],
type=r[1],
source=r[2],
target=r[3],
properties=json.loads(r[4]) if r[4] else {},
)
for r in rows
]
@_connection_locked
def get_neighbors(
self,
node_id: str,
edge_types: list[str] | None = None,
direction: str = "both",
depth: int = 1,
) -> list[dict[str, Any]]:
visited: set[str] = set()
results: list[dict[str, Any]] = []
queue: list[tuple[str, int]] = [(node_id, 0)]
while queue:
current_id, current_depth = queue.pop(0)
if current_id in visited:
continue
visited.add(current_id)
if current_depth >= depth:
continue
edges = self.get_edges(current_id, direction=direction)
for edge in edges:
if edge_types and edge.type not in edge_types:
continue
neighbor_id = edge.target if edge.source == current_id else edge.source
if neighbor_id not in visited and neighbor_id != node_id:
neighbor = self.get_node(neighbor_id)
if neighbor:
results.append(neighbor)
queue.append((neighbor_id, current_depth + 1))
return results
@_connection_locked
def save(self, path: str) -> None:
self._commit_if_needed()
@_connection_locked
def load(self, path: str) -> None:
pass
@_connection_locked
def close(self) -> None:
self.conn.close()