Skip to main content

citadel_sql/
schema.rs

1//! Schema manager: in-memory cache of table schemas.
2
3use std::collections::HashMap;
4
5use citadel::Database;
6
7use crate::error::{Result, SqlError};
8use crate::types::TableSchema;
9
10const SCHEMA_TABLE: &[u8] = b"_schema";
11
12/// Manages table schemas in memory, backed by the `_schema` table.
13pub struct SchemaManager {
14    tables: HashMap<String, TableSchema>,
15    generation: u64,
16}
17
18impl SchemaManager {
19    /// Load all schemas from the database's `_schema` table.
20    pub fn load(db: &Database) -> Result<Self> {
21        let mut tables = HashMap::new();
22
23        let mut rtx = db.begin_read();
24        let mut parse_err: Option<crate::error::SqlError> = None;
25        let scan_result = rtx.table_for_each(SCHEMA_TABLE, |_key, value| {
26            match TableSchema::deserialize(value) {
27                Ok(schema) => {
28                    tables.insert(schema.name.clone(), schema);
29                }
30                Err(e) => {
31                    parse_err = Some(e);
32                }
33            }
34            Ok(())
35        });
36
37        match scan_result {
38            Ok(()) => {}
39            Err(citadel_core::Error::TableNotFound(_)) => {}
40            Err(e) => return Err(e.into()),
41        }
42        if let Some(e) = parse_err {
43            return Err(e);
44        }
45
46        Ok(Self {
47            tables,
48            generation: 0,
49        })
50    }
51
52    pub fn get(&self, name: &str) -> Option<&TableSchema> {
53        let lower = name.to_ascii_lowercase();
54        self.tables.get(&lower)
55    }
56
57    pub fn contains(&self, name: &str) -> bool {
58        let lower = name.to_ascii_lowercase();
59        self.tables.contains_key(&lower)
60    }
61
62    pub fn generation(&self) -> u64 {
63        self.generation
64    }
65
66    pub fn register(&mut self, schema: TableSchema) {
67        let lower = schema.name.to_ascii_lowercase();
68        self.tables.insert(lower, schema);
69        self.generation += 1;
70    }
71
72    pub fn remove(&mut self, name: &str) -> Option<TableSchema> {
73        let lower = name.to_ascii_lowercase();
74        let result = self.tables.remove(&lower);
75        if result.is_some() {
76            self.generation += 1;
77        }
78        result
79    }
80
81    pub fn table_names(&self) -> Vec<&str> {
82        self.tables.keys().map(|s| s.as_str()).collect()
83    }
84
85    /// Persist a schema to the _schema table (called within a write txn).
86    pub fn save_schema(
87        wtx: &mut citadel_txn::write_txn::WriteTxn<'_>,
88        schema: &TableSchema,
89    ) -> Result<()> {
90        let lower = schema.name.to_ascii_lowercase();
91        let data = schema.serialize();
92        wtx.table_insert(SCHEMA_TABLE, lower.as_bytes(), &data)?;
93        Ok(())
94    }
95
96    /// Remove a schema from the _schema table (called within a write txn).
97    pub fn delete_schema(wtx: &mut citadel_txn::write_txn::WriteTxn<'_>, name: &str) -> Result<()> {
98        let lower = name.to_ascii_lowercase();
99        wtx.table_delete(SCHEMA_TABLE, lower.as_bytes())
100            .map_err(|e| match e {
101                citadel_core::Error::TableNotFound(_) => SqlError::TableNotFound(name.into()),
102                other => SqlError::Storage(other),
103            })?;
104        Ok(())
105    }
106
107    /// Ensure the _schema table exists (called once per write).
108    pub fn ensure_schema_table(wtx: &mut citadel_txn::write_txn::WriteTxn<'_>) -> Result<()> {
109        // Try to create; ignore if already exists
110        match wtx.create_table(SCHEMA_TABLE) {
111            Ok(()) => Ok(()),
112            Err(citadel_core::Error::TableAlreadyExists(_)) => Ok(()),
113            Err(e) => Err(e.into()),
114        }
115    }
116}