Skip to main content

sqlitegraph_cli/
client.rs

1use sqlitegraph::backend::GraphBackend;
2use sqlitegraph::backend::SqliteGraphBackend;
3
4/// CLI backend client supporting SQLite and V3 backends
5pub enum CliClient {
6    Sqlite(SqliteGraphBackend),
7    #[cfg(feature = "native-v3")]
8    V3(sqlitegraph::backend::native::v3::V3Backend),
9}
10
11impl CliClient {
12    /// Open database with specified backend
13    pub fn open(
14        backend: super::cli::BackendType,
15        path: &std::path::Path,
16    ) -> anyhow::Result<Self> {
17        match backend {
18            super::cli::BackendType::Sqlite => {
19                let graph = sqlitegraph::SqliteGraph::open(path)?;
20                Ok(Self::Sqlite(SqliteGraphBackend::from_graph(graph)))
21            }
22            #[cfg(feature = "native-v3")]
23            super::cli::BackendType::V3 => {
24                use sqlitegraph::backend::native::v3::V3Backend;
25                let backend = if path.exists() {
26                    V3Backend::open(path)?
27                } else {
28                    V3Backend::create(path)?
29                };
30                Ok(Self::V3(backend))
31            }
32        }
33    }
34
35    /// Open in-memory database
36    pub fn open_in_memory(backend: super::cli::BackendType) -> anyhow::Result<Self> {
37        match backend {
38            super::cli::BackendType::Sqlite => {
39                let graph = sqlitegraph::SqliteGraph::open_in_memory()?;
40                Ok(Self::Sqlite(SqliteGraphBackend::from_graph(graph)))
41            }
42            #[cfg(feature = "native-v3")]
43            super::cli::BackendType::V3 => {
44                anyhow::bail!("V3 backend does not support in-memory mode")
45            }
46        }
47    }
48
49    /// Get backend trait object
50    pub fn backend(&self) -> &dyn GraphBackend {
51        match self {
52            Self::Sqlite(b) => b,
53            #[cfg(feature = "native-v3")]
54            Self::V3(b) => b,
55        }
56    }
57
58    /// Get SQLite graph reference (if SQLite backend)
59    pub fn sqlite_graph(&self) -> Option<&sqlitegraph::SqliteGraph> {
60        match self {
61            Self::Sqlite(b) => Some(b.graph()),
62            #[cfg(feature = "native-v3")]
63            Self::V3(_) => None,
64        }
65    }
66
67    /// Get backend name
68    pub fn backend_name(&self) -> &'static str {
69        match self {
70            Self::Sqlite(_) => "sqlite",
71            #[cfg(feature = "native-v3")]
72            Self::V3(_) => "v3",
73        }
74    }
75
76    /// Get node count
77    pub fn node_count(&self) -> anyhow::Result<usize> {
78        let ids = self.backend().entity_ids()?;
79        Ok(ids.len())
80    }
81}