Skip to main content

khive_db/backend/
namespace_listing.rs

1use super::*;
2
3/// Which rows contribute to administrative namespace enumeration.
4#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
5pub enum NamespaceLiveness {
6    /// Exclude tombstoned entities and notes. Events are append-only.
7    #[default]
8    Live,
9    /// Include tombstoned entities and notes as well as all events.
10    All,
11}
12
13impl StorageBackend {
14    /// List sorted, distinct namespaces containing stored graph edges.
15    ///
16    /// This administrative read is unscoped and does not initialize an absent
17    /// graph table. `All` includes soft-deleted edges; `Live` excludes them.
18    pub async fn list_edge_namespaces(
19        &self,
20        liveness: NamespaceLiveness,
21    ) -> khive_storage::StorageResult<Vec<String>> {
22        crate::stores::run_pooled_store_read(
23            Arc::clone(&self.pool),
24            khive_storage::StorageCapability::Sql,
25            "list_edge_namespaces",
26            move |conn| {
27                let read = || -> Result<Vec<String>, SqliteError> {
28                    if !sqlite_table_exists(conn, "graph_edges")? {
29                        return Ok(Vec::new());
30                    }
31                    let sql = if liveness == NamespaceLiveness::Live {
32                        "SELECT DISTINCT namespace FROM graph_edges WHERE deleted_at IS NULL ORDER BY namespace"
33                    } else {
34                        "SELECT DISTINCT namespace FROM graph_edges ORDER BY namespace"
35                    };
36                    let mut statement = conn.prepare(sql)?;
37                    let rows = statement
38                        .query_map(rusqlite::params![], |row| row.get::<_, String>(0))?;
39                    let mut namespaces = Vec::new();
40                    for row in rows {
41                        namespaces.push(row?);
42                    }
43                    Ok(namespaces)
44                };
45                read().map_err(|error| {
46                    error.into_storage_error(
47                        khive_storage::StorageCapability::Sql,
48                        "list_edge_namespaces",
49                    )
50                })
51            },
52        )
53        .await
54    }
55
56    /// List sorted, distinct namespaces containing an exact stored record kind.
57    ///
58    /// This administrative read is unscoped: it unions existing entities, notes
59    /// and events tables, comparing `kind` exactly. It does not initialize absent
60    /// tables, filter schedules by due time, or interpret kind as a substrate.
61    /// Unknown kinds return an empty list. Pass `NamespaceLiveness::default()`
62    /// for live rows; events have no tombstone field, so both modes include them.
63    pub async fn list_namespaces(
64        &self,
65        kind: &str,
66        liveness: NamespaceLiveness,
67    ) -> khive_storage::StorageResult<Vec<String>> {
68        let kind = kind.to_string();
69        crate::stores::run_pooled_store_read(
70            Arc::clone(&self.pool),
71            khive_storage::StorageCapability::Sql,
72            "list_namespaces",
73            move |conn| {
74                let read = || -> Result<Vec<String>, SqliteError> {
75                    let mut namespaces = std::collections::BTreeSet::new();
76                    // Tables are optional, and only these fixed identifiers enter SQL.
77                    for (table, has_tombstones) in
78                        [("entities", true), ("notes", true), ("events", false)]
79                    {
80                        if !sqlite_table_exists(conn, table)? {
81                            continue;
82                        }
83                        let live = if has_tombstones && liveness == NamespaceLiveness::Live {
84                            " AND deleted_at IS NULL"
85                        } else {
86                            ""
87                        };
88                        let mut statement = conn.prepare(&format!(
89                            "SELECT DISTINCT namespace FROM {table} WHERE kind = ?1{live}"
90                        ))?;
91                        let rows = statement
92                            .query_map(rusqlite::params![kind], |row| row.get::<_, String>(0))?;
93                        for row in rows {
94                            namespaces.insert(row?);
95                        }
96                    }
97                    Ok(namespaces.into_iter().collect())
98                };
99                read().map_err(|error| {
100                    error.into_storage_error(
101                        khive_storage::StorageCapability::Sql,
102                        "list_namespaces",
103                    )
104                })
105            },
106        )
107        .await
108    }
109}