Skip to main content

uni_db/api/
functions.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2024-2026 Dragonscale Team
3
4//! Custom function facade for registering Cypher scalar functions.
5
6use uni_common::{Result, UniError, Value};
7
8use super::UniInner;
9
10/// Facade for managing custom Cypher scalar functions.
11///
12/// Obtained via `db.functions()`. Functions are registered at the database
13/// level and visible to all sessions.
14pub struct Functions<'a> {
15    pub(crate) inner: &'a UniInner,
16}
17
18impl Functions<'_> {
19    /// Register a custom scalar function.
20    ///
21    /// If a function with the same name already exists, it is replaced.
22    pub fn register<F>(&self, name: &str, func: F) -> Result<()>
23    where
24        F: Fn(&[Value]) -> Result<Value> + Send + Sync + 'static,
25    {
26        let mut registry = self.inner.custom_functions.write().map_err(|_| {
27            UniError::Internal(anyhow::anyhow!("custom function registry lock poisoned"))
28        })?;
29        registry.register(name.to_string(), std::sync::Arc::new(func));
30        Ok(())
31    }
32
33    /// Remove a custom function by name. Returns true if it existed.
34    pub fn remove(&self, name: &str) -> Result<bool> {
35        let mut registry = self.inner.custom_functions.write().map_err(|_| {
36            UniError::Internal(anyhow::anyhow!("custom function registry lock poisoned"))
37        })?;
38        Ok(registry.remove(name))
39    }
40
41    /// List names of all registered custom functions.
42    pub fn list(&self) -> Vec<String> {
43        let registry = self.inner.custom_functions.read().unwrap();
44        registry.iter().map(|(name, _)| name.to_string()).collect()
45    }
46
47    /// Get the number of registered custom functions.
48    pub fn count(&self) -> usize {
49        let registry = self.inner.custom_functions.read().unwrap();
50        registry.iter().count()
51    }
52}