Skip to main content

an5_adapters/base/
metadata.rs

1//! Adapter metadata injected by the generated `an5Client` crate.
2//!
3//! Mirrors the Go `an5adapters/base` metadata store.
4
5use std::collections::HashMap;
6use std::sync::{OnceLock, RwLock};
7
8/// Describes a model relation, used for eager-loading (`include`) support.
9#[derive(Debug, Clone, Default, PartialEq, Eq)]
10pub struct RelationDef {
11    pub model_name: String,
12    /// `many` or `one`.
13    pub relation_type: String,
14    pub foreign_key: String,
15    pub local_key: String,
16}
17
18/// Metadata bundle provided by the generated client.
19#[derive(Debug, Clone, Default)]
20pub struct AdapterMetadata {
21    pub model_to_table: HashMap<String, String>,
22    pub model_fields: HashMap<String, serde_json::Value>,
23    pub relation_map: HashMap<String, HashMap<String, RelationDef>>,
24}
25
26static MODEL_TO_TABLE: OnceLock<RwLock<HashMap<String, String>>> = OnceLock::new();
27static MODEL_FIELDS: OnceLock<RwLock<HashMap<String, serde_json::Value>>> = OnceLock::new();
28static RELATION_MAP: OnceLock<RwLock<HashMap<String, HashMap<String, RelationDef>>>> = OnceLock::new();
29static TABLE_OVERRIDES: OnceLock<RwLock<HashMap<String, String>>> = OnceLock::new();
30
31fn table_overrides_store() -> &'static RwLock<HashMap<String, String>> {
32    TABLE_OVERRIDES.get_or_init(|| RwLock::new(HashMap::new()))
33}
34
35/// Point a model alias at a different physical table.
36pub fn add_table_override(model: &str, table: &str) {
37    if let Ok(mut store) = table_overrides_store().write() {
38        store.insert(model.to_string(), table.to_string());
39    }
40}
41
42fn model_to_table_store() -> &'static RwLock<HashMap<String, String>> {
43    MODEL_TO_TABLE.get_or_init(|| RwLock::new(HashMap::new()))
44}
45
46fn model_fields_store() -> &'static RwLock<HashMap<String, serde_json::Value>> {
47    MODEL_FIELDS.get_or_init(|| RwLock::new(HashMap::new()))
48}
49
50fn relation_map_store() -> &'static RwLock<HashMap<String, HashMap<String, RelationDef>>> {
51    RELATION_MAP.get_or_init(|| RwLock::new(HashMap::new()))
52}
53
54/// Store metadata provided by the generated client. Call once at startup.
55pub fn set_adapter_metadata(meta: AdapterMetadata) {
56    if let Ok(mut store) = model_to_table_store().write() {
57        *store = meta.model_to_table;
58    }
59    if let Ok(mut store) = model_fields_store().write() {
60        *store = meta.model_fields;
61    }
62    if let Ok(mut store) = relation_map_store().write() {
63        *store = meta.relation_map;
64    }
65}
66
67/// Read-only snapshot of the model-to-table mapping.
68pub fn get_model_to_table() -> HashMap<String, String> {
69    model_to_table_store()
70        .read()
71        .map(|s| s.clone())
72        .unwrap_or_default()
73}
74
75/// Field metadata for a model, if present.
76pub fn get_fields_for_model(model: &str) -> Option<serde_json::Value> {
77    model_fields_store().read().ok().and_then(|s| s.get(model).cloned())
78}
79
80/// Relations declared for a model.
81pub fn get_relations_for_model(model: &str) -> HashMap<String, RelationDef> {
82    relation_map_store()
83        .read()
84        .ok()
85        .and_then(|s| s.get(model).cloned())
86        .unwrap_or_default()
87}
88
89/// Resolve the physical table for a model, honouring overrides, then the
90/// generated mapping, then a case-insensitive match, then the input itself.
91pub fn resolve_table(model: &str) -> String {
92    let lower = model.to_lowercase();
93    // Overrides win over the generated mapping, and both match
94    // case-insensitively so `with_table("User", ..)` also covers `db.table("user")`.
95    if let Ok(store) = table_overrides_store().read() {
96        if let Some(t) = store.get(model) {
97            return t.clone();
98        }
99        for (k, v) in store.iter() {
100            if k.to_lowercase() == lower {
101                return v.clone();
102            }
103        }
104    }
105    if let Ok(store) = model_to_table_store().read() {
106        if let Some(t) = store.get(model) {
107            return t.clone();
108        }
109        for (k, v) in store.iter() {
110            if k.to_lowercase() == lower {
111                return v.clone();
112            }
113        }
114    }
115    model.to_string()
116}
117
118#[cfg(test)]
119mod tests {
120    use super::*;
121
122    #[test]
123    fn resolves_table_with_case_fallback() {
124        let mut map = HashMap::new();
125        map.insert("User".to_string(), "[dbo].[Users]".to_string());
126        set_adapter_metadata(AdapterMetadata {
127            model_to_table: map,
128            ..Default::default()
129        });
130        assert_eq!(resolve_table("User"), "[dbo].[Users]");
131        assert_eq!(resolve_table("user"), "[dbo].[Users]");
132        assert_eq!(resolve_table("Missing"), "Missing");
133    }
134}