Skip to main content

common_function/
function_registry.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! functions registry
16use std::collections::HashMap;
17use std::collections::hash_map::Entry;
18use std::sync::{Arc, LazyLock, RwLock};
19
20use datafusion::catalog::TableFunction;
21use datafusion_expr::expr_rewriter::FunctionRewrite;
22use datafusion_expr::{AggregateUDF, WindowUDF};
23
24use crate::admin::AdminFunction;
25use crate::aggrs::aggr_wrapper::StateMergeHelper;
26use crate::aggrs::approximate::ApproximateFunction;
27use crate::aggrs::count_hash::CountHash;
28use crate::aggrs::extremum::Extremum;
29use crate::aggrs::vector::VectorFunction as VectorAggrFunction;
30use crate::function::{Function, FunctionRef};
31use crate::function_factory::ScalarFunctionFactory;
32#[cfg(feature = "ai_functions")]
33use crate::scalars::ai;
34use crate::scalars::anomaly::AnomalyFunction;
35use crate::scalars::avg_calc::AvgCalcFunction;
36use crate::scalars::date::DateFunction;
37use crate::scalars::expression::ExpressionFunction;
38use crate::scalars::hll_count::HllCalcFunction;
39use crate::scalars::iceberg_hash::{
40    IcebergHashBoundsFunction, IcebergHashBreakpointsFunction, IcebergHashFunction,
41    IcebergHashRangesSqlFunction,
42};
43use crate::scalars::ip::IpFunctions;
44use crate::scalars::json::JsonFunction;
45use crate::scalars::matches::MatchesFunction;
46use crate::scalars::matches_term::MatchesTermFunction;
47use crate::scalars::math::MathFunction;
48use crate::scalars::primary_key::DecodePrimaryKeyFunction;
49use crate::scalars::string::register_string_functions;
50use crate::scalars::timestamp::TimestampFunction;
51use crate::scalars::uddsketch_calc::UddSketchCalcFunction;
52use crate::scalars::uddsketch_rank::UddSketchRankFunction;
53use crate::scalars::vector::VectorFunction as VectorScalarFunction;
54use crate::scalars::welford_stddev::WelfordStddevFunction;
55use crate::system::SystemFunction;
56
57#[derive(Default)]
58pub struct FunctionRegistry {
59    functions: RwLock<HashMap<String, ScalarFunctionFactory>>,
60    aggregate_functions: RwLock<HashMap<String, AggregateUDF>>,
61    table_functions: RwLock<HashMap<String, Arc<TableFunction>>>,
62    function_rewrites: RwLock<Vec<Arc<dyn FunctionRewrite + Send + Sync>>>,
63    window_functions: RwLock<HashMap<String, WindowUDF>>,
64}
65
66/// The result of registering a function.
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
68pub enum FunctionRegistrationResult {
69    /// The function was newly registered.
70    Registered,
71    /// A function with the same name was already registered and was kept.
72    AlreadyExists,
73}
74
75impl FunctionRegistry {
76    /// Register a function in the registry by converting it into a `ScalarFunctionFactory`.
77    ///
78    /// # Arguments
79    ///
80    /// * `func` - An object that can be converted into a `ScalarFunctionFactory`.
81    ///
82    /// The function is inserted into the internal function map, keyed by its name.
83    /// If a function with the same name already exists, it will be replaced.
84    pub fn register(&self, func: impl Into<ScalarFunctionFactory>) {
85        let func = func.into();
86        let _ = self
87            .functions
88            .write()
89            .unwrap()
90            .insert(func.name().to_string(), func);
91    }
92
93    /// Register a function only if no function with the same name exists.
94    ///
95    /// The duplicate check and the insert happen atomically under the same
96    /// write lock of the functions map. If a function with the same name
97    /// already exists, it is kept unchanged and
98    /// [`FunctionRegistrationResult::AlreadyExists`] is returned; otherwise the
99    /// function is registered and [`FunctionRegistrationResult::Registered`] is
100    /// returned.
101    pub fn register_if_absent(
102        &self,
103        func: impl Into<ScalarFunctionFactory>,
104    ) -> FunctionRegistrationResult {
105        let func = func.into();
106        let mut functions = self.functions.write().unwrap();
107        match functions.entry(func.name().to_string()) {
108            Entry::Occupied(_) => FunctionRegistrationResult::AlreadyExists,
109            Entry::Vacant(entry) => {
110                entry.insert(func);
111                FunctionRegistrationResult::Registered
112            }
113        }
114    }
115
116    /// Register a scalar function in the registry.
117    pub fn register_scalar(&self, func: impl Function + 'static) {
118        let func = Arc::new(func) as FunctionRef;
119
120        for alias in func.aliases() {
121            let func: ScalarFunctionFactory = func.clone().into();
122            let alias = ScalarFunctionFactory {
123                name: alias.clone(),
124                ..func
125            };
126            self.register(alias);
127        }
128
129        self.register(func)
130    }
131
132    /// Register an aggregate function in the registry.
133    pub fn register_aggr(&self, func: AggregateUDF) {
134        let _ = self
135            .aggregate_functions
136            .write()
137            .unwrap()
138            .insert(func.name().to_string(), func);
139    }
140
141    /// Register a table function
142    pub fn register_table_function(&self, func: TableFunction) {
143        let _ = self
144            .table_functions
145            .write()
146            .unwrap()
147            .insert(func.name().to_string(), Arc::new(func));
148    }
149
150    /// Register a function rewrite rule.
151    pub fn register_function_rewrite(&self, func: impl FunctionRewrite + Send + Sync + 'static) {
152        self.function_rewrites.write().unwrap().push(Arc::new(func));
153    }
154
155    /// Register a window function (UDWF).
156    pub fn register_window(&self, func: WindowUDF) {
157        let _ = self
158            .window_functions
159            .write()
160            .unwrap()
161            .insert(func.name().to_string(), func);
162    }
163
164    pub fn get_function(&self, name: &str) -> Option<ScalarFunctionFactory> {
165        self.functions.read().unwrap().get(name).cloned()
166    }
167
168    /// Returns a list of all scalar functions registered in the registry.
169    pub fn scalar_functions(&self) -> Vec<ScalarFunctionFactory> {
170        self.functions.read().unwrap().values().cloned().collect()
171    }
172
173    /// Returns a list of all aggregate functions registered in the registry.
174    pub fn aggregate_functions(&self) -> Vec<AggregateUDF> {
175        self.aggregate_functions
176            .read()
177            .unwrap()
178            .values()
179            .cloned()
180            .collect()
181    }
182
183    pub fn table_functions(&self) -> Vec<Arc<TableFunction>> {
184        self.table_functions
185            .read()
186            .unwrap()
187            .values()
188            .cloned()
189            .collect()
190    }
191
192    /// Returns a list of all window functions registered in the registry.
193    pub fn window_functions(&self) -> Vec<WindowUDF> {
194        self.window_functions
195            .read()
196            .unwrap()
197            .values()
198            .cloned()
199            .collect()
200    }
201
202    /// Returns a registered aggregate function by name.
203    pub fn get_aggr_func(&self, name: &str) -> Option<AggregateUDF> {
204        self.aggregate_functions.read().unwrap().get(name).cloned()
205    }
206
207    /// Returns true if an aggregate function with the given name exists in the registry.
208    pub fn is_aggr_func_exist(&self, name: &str) -> bool {
209        self.aggregate_functions.read().unwrap().contains_key(name)
210    }
211
212    /// Returns a list of all function rewrite rules registered in the registry.
213    pub fn function_rewrites(&self) -> Vec<Arc<dyn FunctionRewrite + Send + Sync>> {
214        self.function_rewrites.read().unwrap().clone()
215    }
216}
217
218pub static FUNCTION_REGISTRY: LazyLock<Arc<FunctionRegistry>> = LazyLock::new(|| {
219    let function_registry = FunctionRegistry::default();
220
221    // Utility functions
222    MathFunction::register(&function_registry);
223    TimestampFunction::register(&function_registry);
224    DateFunction::register(&function_registry);
225    ExpressionFunction::register(&function_registry);
226    AvgCalcFunction::register(&function_registry);
227    UddSketchCalcFunction::register(&function_registry);
228    UddSketchRankFunction::register(&function_registry);
229    HllCalcFunction::register(&function_registry);
230    WelfordStddevFunction::register(&function_registry);
231    DecodePrimaryKeyFunction::register(&function_registry);
232
233    // Hash used by `iceberg_hash` partition rules, plus its breakpoint helpers.
234    IcebergHashFunction::register(&function_registry);
235    IcebergHashBoundsFunction::register(&function_registry);
236    IcebergHashBreakpointsFunction::register(&function_registry);
237    IcebergHashRangesSqlFunction::register(&function_registry);
238
239    // Full text search function
240    MatchesFunction::register(&function_registry);
241    MatchesTermFunction::register(&function_registry);
242    #[cfg(feature = "ai_functions")]
243    ai::register(&function_registry);
244
245    // System and administration functions
246    SystemFunction::register(&function_registry);
247    AdminFunction::register(&function_registry);
248
249    // Json related functions
250    JsonFunction::register(&function_registry);
251
252    // String related functions
253    register_string_functions(&function_registry);
254
255    // Vector related functions
256    VectorScalarFunction::register(&function_registry);
257    VectorAggrFunction::register(&function_registry);
258
259    // Geo functions
260    #[cfg(feature = "geo")]
261    crate::scalars::geo::GeoFunctions::register(&function_registry);
262    #[cfg(feature = "geo")]
263    crate::aggrs::geo::GeoFunction::register(&function_registry);
264
265    // Ip functions
266    IpFunctions::register(&function_registry);
267
268    // Approximate functions
269    ApproximateFunction::register(&function_registry);
270
271    // CountHash function
272    CountHash::register(&function_registry);
273
274    // PromQL min/max; registered before the state functions are derived.
275    Extremum::register(&function_registry);
276
277    // state function of supported aggregate functions
278    StateMergeHelper::register(&function_registry);
279
280    // Anomaly detection window functions
281    AnomalyFunction::register(&function_registry);
282
283    Arc::new(function_registry)
284});
285
286static ADMIN_FUNCTION_REGISTRY: LazyLock<FunctionRegistry> = LazyLock::new(|| {
287    let registry = FunctionRegistry::default();
288    AdminFunction::register_admin_only(&registry);
289    registry
290});
291
292/// Returns a function that is only available to the ADMIN statement executor.
293pub fn get_admin_function(name: &str) -> Option<ScalarFunctionFactory> {
294    ADMIN_FUNCTION_REGISTRY.get_function(name)
295}
296
297/// Register a function that is only available to the ADMIN statement executor.
298///
299/// If a function with the same name is already registered in the ADMIN
300/// registry, the existing one is kept and
301/// [`FunctionRegistrationResult::AlreadyExists`] is returned. A name that
302/// already exists in the normal [`FUNCTION_REGISTRY`] when this call
303/// linearizes is also rejected: the ADMIN executor resolves admin-only
304/// functions before falling back to the normal registry, so inserting such a
305/// name here would shadow the built-in. Otherwise the function is registered
306/// and [`FunctionRegistrationResult::Registered`] is returned.
307///
308/// The enforced contract is one-way: it only guards the ADMIN registration
309/// against names already present in the normal registry. A later ordinary
310/// [`FunctionRegistry::register`] may still install the same name in the
311/// normal registry because the normal registry keeps its legacy replace
312/// semantics.
313pub fn register_admin_function(
314    func: impl Into<ScalarFunctionFactory>,
315) -> FunctionRegistrationResult {
316    register_admin_function_in(&ADMIN_FUNCTION_REGISTRY, &FUNCTION_REGISTRY, func)
317}
318
319/// Core implementation of [`register_admin_function`] against a pair of
320/// registries, parameterized so tests can exercise it with local registries.
321///
322/// Locking: the ADMIN-registry write lock is acquired first, then a read lock
323/// on the normal registry, and the normal-registry guard (bound to
324/// `normal_functions`) is kept alive through both the normal-name check and
325/// the ADMIN insertion below. This is the only code path that holds both
326/// registries' locks, so the ADMIN -> FUNCTION acquisition order is
327/// consistent and a concurrent normal-registry registration cannot slip in
328/// between the check and the ADMIN insert and be shadowed.
329///
330/// The enforced contract is one-way: it only guards the ADMIN registration
331/// against names already present in the normal registry. A later ordinary
332/// [`FunctionRegistry::register`] may still install the same name in the
333/// normal registry because the normal registry keeps its legacy replace
334/// semantics.
335fn register_admin_function_in(
336    admin_registry: &FunctionRegistry,
337    normal_registry: &FunctionRegistry,
338    func: impl Into<ScalarFunctionFactory>,
339) -> FunctionRegistrationResult {
340    let func = func.into();
341    let mut admin_functions = admin_registry.functions.write().unwrap();
342    // The normal-registry guard is a read lock: it is held across the
343    // normal-name check and the ADMIN insertion below, and while it is alive
344    // no writer can acquire the normal-registry write lock, so a concurrent
345    // normal-registry registration cannot slip in between the check and the
346    // ADMIN insert and be shadowed.
347    let normal_functions = normal_registry.functions.read().unwrap();
348    if normal_functions.contains_key(func.name()) {
349        drop(normal_functions);
350        return FunctionRegistrationResult::AlreadyExists;
351    }
352    let result = match admin_functions.entry(func.name().to_string()) {
353        Entry::Occupied(_) => FunctionRegistrationResult::AlreadyExists,
354        Entry::Vacant(entry) => {
355            entry.insert(func);
356            FunctionRegistrationResult::Registered
357        }
358    };
359    // Drop the read guard only after the ADMIN insertion, so writers to the
360    // normal registry stay blocked until the check-and-insert is complete.
361    drop(normal_functions);
362    result
363}
364
365#[cfg(test)]
366mod tests {
367    use std::sync::{Arc, Barrier};
368    use std::thread;
369
370    use super::*;
371    use crate::scalars::test::TestAndFunction;
372    use crate::scalars::udf::create_udf;
373
374    /// Creates a [`ScalarFunctionFactory`] with the given name. Each call
375    /// allocates a distinct factory closure, so factories can be told apart by
376    /// [`Arc::ptr_eq`] on their `factory` field even when names are identical.
377    fn named_factory(name: &str) -> ScalarFunctionFactory {
378        ScalarFunctionFactory {
379            name: name.to_string(),
380            factory: Arc::new(|_ctx| create_udf(Arc::new(TestAndFunction::default()))),
381        }
382    }
383
384    #[test]
385    fn test_function_registry() {
386        let registry = FunctionRegistry::default();
387
388        assert!(registry.get_function("test_and").is_none());
389        assert!(registry.scalar_functions().is_empty());
390        registry.register_scalar(TestAndFunction::default());
391        let _ = registry.get_function("test_and").unwrap();
392        assert_eq!(1, registry.scalar_functions().len());
393    }
394
395    #[test]
396    fn test_uddsketch_rank_registered() {
397        assert!(FUNCTION_REGISTRY.get_function("uddsketch_rank").is_some());
398    }
399
400    #[test]
401    fn test_ai_registration_matches_feature() {
402        for name in ["ai_match", "ai_choose", "ai_score"] {
403            assert_eq!(
404                FUNCTION_REGISTRY.get_function(name).is_some(),
405                cfg!(feature = "ai_functions"),
406                "{name}"
407            );
408        }
409        for name in ["jev", "jev_choice", "jev_score"] {
410            assert!(FUNCTION_REGISTRY.get_function(name).is_none(), "{name}");
411        }
412    }
413
414    #[test]
415    fn test_register_if_absent_registers_new_function() {
416        let registry = FunctionRegistry::default();
417        let name = "pr3_register_if_absent_new";
418        let factory = named_factory(name);
419
420        assert_eq!(
421            registry.register_if_absent(factory.clone()),
422            FunctionRegistrationResult::Registered
423        );
424        let registered = registry
425            .get_function(name)
426            .expect("function should be registered");
427        assert!(Arc::ptr_eq(&registered.factory, &factory.factory));
428    }
429
430    #[test]
431    fn test_register_if_absent_first_registration_wins() {
432        let registry = FunctionRegistry::default();
433        let name = "pr3_register_if_absent_duplicate";
434        let first = named_factory(name);
435        let second = named_factory(name);
436
437        assert_eq!(
438            registry.register_if_absent(first.clone()),
439            FunctionRegistrationResult::Registered
440        );
441        assert_eq!(
442            registry.register_if_absent(second.clone()),
443            FunctionRegistrationResult::AlreadyExists
444        );
445
446        let stored = registry
447            .get_function(name)
448            .expect("function should be registered");
449        assert!(Arc::ptr_eq(&stored.factory, &first.factory));
450        assert!(!Arc::ptr_eq(&stored.factory, &second.factory));
451    }
452
453    #[test]
454    fn test_register_replaces_existing_function() {
455        // Regression test: `register` keeps its replace semantics.
456        let registry = FunctionRegistry::default();
457        let name = "pr3_register_replaces";
458        let first = named_factory(name);
459        let second = named_factory(name);
460
461        registry.register(first.clone());
462        registry.register(second.clone());
463
464        let stored = registry
465            .get_function(name)
466            .expect("function should be registered");
467        assert!(Arc::ptr_eq(&stored.factory, &second.factory));
468        assert!(!Arc::ptr_eq(&stored.factory, &first.factory));
469    }
470
471    #[test]
472    fn test_concurrent_register_if_absent_same_name() {
473        const THREADS: usize = 8;
474        let registry = Arc::new(FunctionRegistry::default());
475        let name = "pr3_concurrent_same_name";
476        let barrier = Arc::new(Barrier::new(THREADS));
477
478        let handles: Vec<_> = (0..THREADS)
479            .map(|_| {
480                let registry = Arc::clone(&registry);
481                let barrier = Arc::clone(&barrier);
482                thread::spawn(move || {
483                    let factory = named_factory(name);
484                    // Synchronize so every thread attempts registration at the
485                    // same time; only one may win the write lock.
486                    barrier.wait();
487                    let result = registry.register_if_absent(factory.clone());
488                    (result, factory)
489                })
490            })
491            .collect();
492
493        let mut results: Vec<(FunctionRegistrationResult, ScalarFunctionFactory)> =
494            Vec::with_capacity(THREADS);
495        for handle in handles {
496            results.push(handle.join().expect("thread should not panic"));
497        }
498
499        let registered = results
500            .iter()
501            .filter(|(result, _)| *result == FunctionRegistrationResult::Registered)
502            .count();
503        let already_exists = results
504            .iter()
505            .filter(|(result, _)| *result == FunctionRegistrationResult::AlreadyExists)
506            .count();
507        assert_eq!(registered, 1);
508        assert_eq!(already_exists, THREADS - 1);
509
510        let winner = results
511            .iter()
512            .find(|(result, _)| *result == FunctionRegistrationResult::Registered)
513            .map(|(_, factory)| factory)
514            .expect("exactly one registration must win");
515
516        let stored = registry
517            .get_function(name)
518            .expect("function should be registered");
519        assert!(
520            Arc::ptr_eq(&stored.factory, &winner.factory),
521            "the stored factory must be the factory of the winning registration"
522        );
523    }
524
525    #[test]
526    fn test_register_admin_function_first_wins() {
527        // Tests touching the global registry must use unique names.
528        let name = "pr3_admin_runtime_register";
529        let first = named_factory(name);
530        let second = named_factory(name);
531
532        assert_eq!(
533            register_admin_function(first.clone()),
534            FunctionRegistrationResult::Registered
535        );
536        assert_eq!(
537            register_admin_function(second.clone()),
538            FunctionRegistrationResult::AlreadyExists
539        );
540
541        let stored = get_admin_function(name).expect("admin function should be queryable");
542        assert!(Arc::ptr_eq(&stored.factory, &first.factory));
543        assert!(!Arc::ptr_eq(&stored.factory, &second.factory));
544    }
545
546    #[test]
547    fn test_register_admin_function_duplicate_same_factory() {
548        // The exact same factory clone registered twice: the first registration
549        // wins, the duplicate is rejected, and the stored factory is
550        // pointer-equal to the original. Tests touching the global registry
551        // must use unique names.
552        let name = "pr3_admin_runtime_register_same_factory";
553        let factory = named_factory(name);
554
555        assert_eq!(
556            register_admin_function(factory.clone()),
557            FunctionRegistrationResult::Registered
558        );
559        assert_eq!(
560            register_admin_function(factory.clone()),
561            FunctionRegistrationResult::AlreadyExists
562        );
563
564        let stored = get_admin_function(name).expect("admin function should be queryable");
565        assert!(Arc::ptr_eq(&stored.factory, &factory.factory));
566    }
567
568    #[test]
569    fn test_register_admin_function_in_is_one_way_later_normal_register_allowed() {
570        // The guard is one-way: after the ADMIN registration completes, an
571        // ordinary normal-registry registration of the same name still
572        // succeeds because the normal registry keeps its legacy replace
573        // semantics.
574        let admin = FunctionRegistry::default();
575        let normal = FunctionRegistry::default();
576        let name = "pr3_admin_in_one_way";
577        let admin_factory = named_factory(name);
578        let normal_factory = named_factory(name);
579
580        assert_eq!(
581            register_admin_function_in(&admin, &normal, admin_factory.clone()),
582            FunctionRegistrationResult::Registered
583        );
584
585        normal.register(normal_factory.clone());
586
587        let stored_admin = admin
588            .get_function(name)
589            .expect("the ADMIN registration must be kept");
590        assert!(Arc::ptr_eq(&stored_admin.factory, &admin_factory.factory));
591        let stored_normal = normal
592            .get_function(name)
593            .expect("the later normal registration must succeed");
594        assert!(Arc::ptr_eq(&stored_normal.factory, &normal_factory.factory));
595    }
596
597    #[test]
598    fn test_register_admin_function_rejects_normal_registry_builtin_name() {
599        // Regression test: the ADMIN executor resolves `get_admin_function`
600        // before falling back to `FUNCTION_REGISTRY`, so registering a function
601        // whose name already exists in the normal registry would shadow the
602        // ADMIN-invocable built-in (e.g. `flush_table`). Such registrations
603        // must be rejected with
604        // [`FunctionRegistrationResult::AlreadyExists`] and must not be
605        // inserted into the ADMIN registry.
606        let factory = named_factory("flush_table");
607
608        assert_eq!(
609            register_admin_function(factory.clone()),
610            FunctionRegistrationResult::AlreadyExists
611        );
612        assert!(
613            get_admin_function("flush_table").is_none(),
614            "a normal-registry built-in must not be shadowed into the ADMIN registry"
615        );
616        assert!(
617            FUNCTION_REGISTRY.get_function("flush_table").is_some(),
618            "the normal-registry built-in must remain registered"
619        );
620    }
621
622    #[test]
623    fn test_builtin_admin_functions_remain_queryable() {
624        // Built-in admin-only functions registered at startup stay queryable
625        // through the same global registry used for runtime registrations.
626        #[cfg(feature = "enterprise")]
627        {
628            assert!(get_admin_function("purge_table").is_some());
629        }
630        #[cfg(not(feature = "enterprise"))]
631        {
632            assert!(get_admin_function("purge_table").is_none());
633        }
634    }
635}