Skip to main content

vlorql_core/function/
registry.rs

1//! Global function registry with runtime registration support.
2//!
3//! Uses a `OnceLock<RwLock<HashMap>>` so that built-in functions are
4//! loaded at startup and user-defined functions (UDFs) can be added
5//! at runtime without sacrificing thread safety.
6
7use std::collections::HashMap;
8use std::sync::{OnceLock, RwLock};
9
10use super::def::{Dialect, FunctionDef, FunctionKind};
11
12static REGISTRY: OnceLock<RwLock<HashMap<String, FunctionDef>>> = OnceLock::new();
13
14fn registry() -> &'static RwLock<HashMap<String, FunctionDef>> {
15    REGISTRY.get_or_init(|| {
16        let map = HashMap::new();
17        let rw = RwLock::new(map);
18        // Auto-load built-in functions on first access so callers do
19        // not have to call `init_registry` explicitly.
20        {
21            let mut guard = rw.write().expect("function registry lock poisoned");
22            let builtin = super::builtin::builtin_functions();
23            for def in builtin {
24                for name in &def.names {
25                    guard.insert(name.to_string(), def.clone());
26                }
27            }
28        }
29        rw
30    })
31}
32
33/// Initialise the registry with a set of built-in functions.
34///
35/// Should be called once during program startup (e.g. from
36/// `vlorql_core::init_function_registry()`).
37pub fn init_registry(builtin: Vec<FunctionDef>) {
38    let mut guard = registry().write().expect("function registry lock poisoned");
39    for def in builtin {
40        for name in &def.names {
41            guard.insert(name.to_string(), def.clone());
42        }
43    }
44}
45
46/// Register a single function at runtime (e.g. a user-defined function).
47///
48/// Returns an error if any name is already registered.
49pub fn register_function(def: FunctionDef) -> Result<(), String> {
50    let mut guard = registry().write().expect("function registry lock poisoned");
51    for name in &def.names {
52        if guard.contains_key(name.as_ref()) {
53            return Err(format!("Function '{}' is already registered", name));
54        }
55    }
56    for name in &def.names {
57        guard.insert(name.to_string(), def.clone());
58    }
59    Ok(())
60}
61
62/// Look up a function by name (case-insensitive).
63///
64/// Returns a cloned `FunctionDef` so the caller does not hold a read lock.
65pub fn lookup_function(name: &str) -> Option<FunctionDef> {
66    let guard = registry().read().expect("function registry lock poisoned");
67    // Exact match first (fast path).
68    if let Some(def) = guard.get(name) {
69        return Some(def.clone());
70    }
71    // Case-insensitive fallback.
72    for (key, def) in guard.iter() {
73        if key.eq_ignore_ascii_case(name) {
74            return Some(def.clone());
75        }
76    }
77    None
78}
79
80/// Look up a function by name, filtering by dialect.
81pub fn lookup_function_for_dialect(name: &str, dialect: Dialect) -> Option<FunctionDef> {
82    lookup_function(name).and_then(|def| {
83        if def.supports_dialect(dialect) {
84            Some(def)
85        } else {
86            None
87        }
88    })
89}
90
91/// Returns `true` when `name` is a known aggregate function.
92pub fn is_aggregate(name: &str) -> bool {
93    lookup_function(name).is_some_and(|def| def.kind == FunctionKind::Aggregate)
94}
95
96/// Returns `true` when `name` is a known function of any kind.
97pub fn is_known_function(name: &str) -> bool {
98    lookup_function(name).is_some()
99}
100
101#[cfg(test)]
102mod tests {
103    use super::*;
104    use crate::function::builder::FunctionDefBuilder;
105
106    fn setup() {
107        let _ = init_registry(vec![
108            FunctionDefBuilder::new("sum")
109                .kind(FunctionKind::Aggregate)
110                .min_args(1)
111                .build(),
112            FunctionDefBuilder::new("upper")
113                .alias("ucase")
114                .kind(FunctionKind::Scalar)
115                .min_args(1)
116                .build(),
117        ]);
118    }
119
120    #[test]
121    fn lookup_known_function() {
122        setup();
123        let def = lookup_function("sum").expect("sum should be found");
124        assert_eq!(def.kind, FunctionKind::Aggregate);
125    }
126
127    #[test]
128    fn lookup_case_insensitive() {
129        setup();
130        assert!(lookup_function("SUM").is_some());
131        assert!(lookup_function("Upper").is_some());
132    }
133
134    #[test]
135    fn lookup_unknown_returns_none() {
136        setup();
137        assert!(lookup_function("nonexistent").is_none());
138    }
139
140    #[test]
141    fn alias_resolves() {
142        setup();
143        let def = lookup_function("ucase").expect("ucase alias should resolve");
144        assert_eq!(def.canonical_name(), "upper");
145    }
146
147    #[test]
148    fn is_aggregate_works() {
149        setup();
150        assert!(is_aggregate("sum"));
151        assert!(!is_aggregate("upper"));
152    }
153
154    #[test]
155    fn register_then_lookup() {
156        setup();
157        let def = FunctionDefBuilder::new("my_udf")
158            .kind(FunctionKind::Scalar)
159            .min_args(2)
160            .build();
161        register_function(def).unwrap();
162        assert!(lookup_function("my_udf").is_some());
163    }
164
165    #[test]
166    fn duplicate_registration_fails() {
167        setup();
168        let def = FunctionDefBuilder::new("sum").build();
169        assert!(register_function(def).is_err());
170    }
171}