1use crate::graph::{
2 Entity, KnowledgeGraph, ObservationDeletion, ObservationInput, ObservationResult, Relation,
3};
4use crate::storage::Database;
5use anyhow::{Context, Result};
6use std::path::PathBuf;
7use std::sync::Arc;
8
9pub struct KnowledgeGraphManager {
12 db: Arc<Database>,
13}
14
15impl KnowledgeGraphManager {
16 pub fn new(db_path: PathBuf) -> Result<Self> {
18 let db = Database::open(&db_path)?;
19 Ok(Self { db: Arc::new(db) })
20 }
21
22 pub async fn create_entities(&self, entities: Vec<Entity>) -> Result<Vec<Entity>> {
24 let db = self.db.clone();
25 tokio::task::spawn_blocking(move || db.create_entities(&entities))
26 .await
27 .context("Task panicked")?
28 }
29
30 pub async fn create_relations(&self, relations: Vec<Relation>) -> Result<Vec<Relation>> {
32 let db = self.db.clone();
33 tokio::task::spawn_blocking(move || db.create_relations(&relations))
34 .await
35 .context("Task panicked")?
36 }
37
38 pub async fn add_observations(
40 &self,
41 inputs: Vec<ObservationInput>,
42 ) -> Result<Vec<ObservationResult>> {
43 let db = self.db.clone();
44 tokio::task::spawn_blocking(move || db.add_observations(&inputs))
45 .await
46 .context("Task panicked")?
47 }
48
49 pub async fn delete_entities(&self, names: Vec<String>) -> Result<usize> {
51 let db = self.db.clone();
52 tokio::task::spawn_blocking(move || db.delete_entities(&names))
53 .await
54 .context("Task panicked")?
55 }
56
57 pub async fn delete_observations(&self, deletions: Vec<ObservationDeletion>) -> Result<()> {
59 let db = self.db.clone();
60 tokio::task::spawn_blocking(move || db.delete_observations(&deletions))
61 .await
62 .context("Task panicked")?
63 }
64
65 pub async fn delete_relations(&self, relations: Vec<Relation>) -> Result<usize> {
67 let db = self.db.clone();
68 tokio::task::spawn_blocking(move || db.delete_relations(&relations))
69 .await
70 .context("Task panicked")?
71 }
72
73 pub async fn read_graph(&self) -> Result<KnowledgeGraph> {
75 let db = self.db.clone();
76 tokio::task::spawn_blocking(move || db.read_graph())
77 .await
78 .context("Task panicked")?
79 }
80
81 pub async fn search_nodes(&self, query: Option<String>) -> Result<KnowledgeGraph> {
83 let db = self.db.clone();
84 tokio::task::spawn_blocking(move || db.search_nodes(query.as_deref()))
85 .await
86 .context("Task panicked")?
87 }
88
89 pub async fn open_nodes(&self, names: Vec<String>) -> Result<KnowledgeGraph> {
91 let db = self.db.clone();
92 tokio::task::spawn_blocking(move || db.open_nodes(&names))
93 .await
94 .context("Task panicked")?
95 }
96}