Skip to main content

datafusion_expr/
registry.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! FunctionRegistry trait
6
7use crate::expr_rewriter::FunctionRewrite;
8use crate::higher_order_function::HigherOrderUDF;
9use crate::planner::ExprPlanner;
10use crate::{AggregateUDF, ScalarUDF, UserDefinedLogicalNode, WindowUDF};
11use arrow::datatypes::Field;
12use arrow_schema::DataType;
13use arrow_schema::extension::{
14    Bool8, ExtensionType, FixedShapeTensor, Json, Opaque, TimestampWithOffset, Uuid,
15    VariableShapeTensor,
16};
17use datafusion_common::types::{
18    DFBool8, DFExtensionTypeRef, DFFixedShapeTensor, DFJson, DFOpaque,
19    DFTimestampWithOffset, DFUuid, DFVariableShapeTensor,
20};
21use datafusion_common::{HashMap, Result, not_impl_err, plan_datafusion_err};
22use std::collections::HashSet;
23use std::fmt::{Debug, Formatter};
24use std::sync::{Arc, RwLock};
25
26/// A registry knows how to build logical expressions out of user-defined function' names
27pub trait FunctionRegistry {
28    /// Returns names of all available scalar user defined functions.
29    fn udfs(&self) -> HashSet<String>;
30
31    /// Returns names of all available higher order user defined functions.
32    fn higher_order_function_names(&self) -> HashSet<String>;
33
34    /// Returns names of all available aggregate user defined functions.
35    fn udafs(&self) -> HashSet<String>;
36
37    /// Returns names of all available window user defined functions.
38    fn udwfs(&self) -> HashSet<String>;
39
40    /// Returns a reference to the user defined scalar function (udf) named
41    /// `name`.
42    fn udf(&self, name: &str) -> Result<Arc<ScalarUDF>>;
43
44    /// Returns a reference to the user defined higher order function named
45    /// `name`.
46    fn higher_order_function(&self, name: &str) -> Result<Arc<HigherOrderUDF>>;
47
48    /// Returns a reference to the user defined aggregate function (udaf) named
49    /// `name`.
50    fn udaf(&self, name: &str) -> Result<Arc<AggregateUDF>>;
51
52    /// Returns a reference to the user defined window function (udwf) named
53    /// `name`.
54    fn udwf(&self, name: &str) -> Result<Arc<WindowUDF>>;
55
56    /// Registers a new [`ScalarUDF`], returning any previously registered
57    /// implementation.
58    ///
59    /// Returns an error (the default) if the function can not be registered,
60    /// for example if the registry is read only.
61    fn register_udf(&mut self, _udf: Arc<ScalarUDF>) -> Result<Option<Arc<ScalarUDF>>> {
62        not_impl_err!("Registering ScalarUDF")
63    }
64    /// Registers a new [`HigherOrderUDF`], returning any previously registered
65    /// implementation.
66    ///
67    /// Returns an error (the default) if the function can not be registered,
68    /// for example if the registry is read only.
69    fn register_higher_order_function(
70        &mut self,
71        _function: Arc<HigherOrderUDF>,
72    ) -> Result<Option<Arc<HigherOrderUDF>>> {
73        not_impl_err!("Registering HigherOrderUDF")
74    }
75    /// Registers a new [`AggregateUDF`], returning any previously registered
76    /// implementation.
77    ///
78    /// Returns an error (the default) if the function can not be registered,
79    /// for example if the registry is read only.
80    fn register_udaf(
81        &mut self,
82        _udaf: Arc<AggregateUDF>,
83    ) -> Result<Option<Arc<AggregateUDF>>> {
84        not_impl_err!("Registering AggregateUDF")
85    }
86    /// Registers a new [`WindowUDF`], returning any previously registered
87    /// implementation.
88    ///
89    /// Returns an error (the default) if the function can not be registered,
90    /// for example if the registry is read only.
91    fn register_udwf(&mut self, _udaf: Arc<WindowUDF>) -> Result<Option<Arc<WindowUDF>>> {
92        not_impl_err!("Registering WindowUDF")
93    }
94
95    /// Deregisters a [`ScalarUDF`], returning the implementation that was
96    /// deregistered.
97    ///
98    /// Returns an error (the default) if the function can not be deregistered,
99    /// for example if the registry is read only.
100    fn deregister_udf(&mut self, _name: &str) -> Result<Option<Arc<ScalarUDF>>> {
101        not_impl_err!("Deregistering ScalarUDF")
102    }
103
104    /// Deregisters a [`HigherOrderUDF`], returning the implementation that was
105    /// deregistered.
106    ///
107    /// Returns an error (the default) if the function can not be deregistered,
108    /// for example if the registry is read only.
109    fn deregister_higher_order_function(
110        &mut self,
111        _name: &str,
112    ) -> Result<Option<Arc<HigherOrderUDF>>> {
113        not_impl_err!("Deregistering HigherOrderUDF")
114    }
115
116    /// Deregisters a [`AggregateUDF`], returning the implementation that was
117    /// deregistered.
118    ///
119    /// Returns an error (the default) if the function can not be deregistered,
120    /// for example if the registry is read only.
121    fn deregister_udaf(&mut self, _name: &str) -> Result<Option<Arc<AggregateUDF>>> {
122        not_impl_err!("Deregistering AggregateUDF")
123    }
124
125    /// Deregisters a [`WindowUDF`], returning the implementation that was
126    /// deregistered.
127    ///
128    /// Returns an error (the default) if the function can not be deregistered,
129    /// for example if the registry is read only.
130    fn deregister_udwf(&mut self, _name: &str) -> Result<Option<Arc<WindowUDF>>> {
131        not_impl_err!("Deregistering WindowUDF")
132    }
133
134    /// Registers a new [`FunctionRewrite`] with the registry.
135    ///
136    /// `FunctionRewrite` rules are used to rewrite certain / operators in the
137    /// logical plan to function calls.  For example `a || b` might be written to
138    /// `array_concat(a, b)`.
139    ///
140    /// This allows the behavior of operators to be customized by the user.
141    fn register_function_rewrite(
142        &mut self,
143        _rewrite: Arc<dyn FunctionRewrite + Send + Sync>,
144    ) -> Result<()> {
145        not_impl_err!("Registering FunctionRewrite")
146    }
147
148    /// Set of all registered [`ExprPlanner`]s
149    fn expr_planners(&self) -> Vec<Arc<dyn ExprPlanner>>;
150
151    /// Registers a new [`ExprPlanner`] with the registry.
152    fn register_expr_planner(
153        &mut self,
154        _expr_planner: Arc<dyn ExprPlanner>,
155    ) -> Result<()> {
156        not_impl_err!("Registering ExprPlanner")
157    }
158}
159
160/// Serializer and deserializer registry for extensions like [UserDefinedLogicalNode].
161pub trait SerializerRegistry: Debug + Send + Sync {
162    /// Serialize this node to a byte array. This serialization should not include
163    /// input plans.
164    fn serialize_logical_plan(
165        &self,
166        node: &dyn UserDefinedLogicalNode,
167    ) -> Result<Vec<u8>>;
168
169    /// Deserialize user defined logical plan node ([UserDefinedLogicalNode]) from
170    /// bytes.
171    fn deserialize_logical_plan(
172        &self,
173        name: &str,
174        bytes: &[u8],
175    ) -> Result<Arc<dyn UserDefinedLogicalNode>>;
176}
177
178/// A  [`FunctionRegistry`] that uses in memory [`HashMap`]s
179#[derive(Default, Debug)]
180pub struct MemoryFunctionRegistry {
181    /// Scalar Functions
182    udfs: HashMap<String, Arc<ScalarUDF>>,
183    /// Aggregate Functions
184    udafs: HashMap<String, Arc<AggregateUDF>>,
185    /// Window Functions
186    udwfs: HashMap<String, Arc<WindowUDF>>,
187    /// Higher Order Functions
188    higher_order_functions: HashMap<String, Arc<HigherOrderUDF>>,
189}
190
191impl MemoryFunctionRegistry {
192    pub fn new() -> Self {
193        Self::default()
194    }
195}
196
197impl FunctionRegistry for MemoryFunctionRegistry {
198    fn udfs(&self) -> HashSet<String> {
199        self.udfs.keys().cloned().collect()
200    }
201
202    fn udf(&self, name: &str) -> Result<Arc<ScalarUDF>> {
203        self.udfs
204            .get(name)
205            .cloned()
206            .ok_or_else(|| plan_datafusion_err!("Function {name} not found"))
207    }
208
209    fn higher_order_function(&self, name: &str) -> Result<Arc<HigherOrderUDF>> {
210        self.higher_order_functions
211            .get(name)
212            .cloned()
213            .ok_or_else(|| plan_datafusion_err!("Higher Order Function {name} not found"))
214    }
215
216    fn udaf(&self, name: &str) -> Result<Arc<AggregateUDF>> {
217        self.udafs
218            .get(name)
219            .cloned()
220            .ok_or_else(|| plan_datafusion_err!("Aggregate Function {name} not found"))
221    }
222
223    fn udwf(&self, name: &str) -> Result<Arc<WindowUDF>> {
224        self.udwfs
225            .get(name)
226            .cloned()
227            .ok_or_else(|| plan_datafusion_err!("Window Function {name} not found"))
228    }
229
230    fn register_udf(&mut self, udf: Arc<ScalarUDF>) -> Result<Option<Arc<ScalarUDF>>> {
231        Ok(self.udfs.insert(udf.name().to_string(), udf))
232    }
233    fn register_higher_order_function(
234        &mut self,
235        function: Arc<HigherOrderUDF>,
236    ) -> Result<Option<Arc<HigherOrderUDF>>> {
237        Ok(self
238            .higher_order_functions
239            .insert(function.name().into(), function))
240    }
241    fn register_udaf(
242        &mut self,
243        udaf: Arc<AggregateUDF>,
244    ) -> Result<Option<Arc<AggregateUDF>>> {
245        Ok(self.udafs.insert(udaf.name().into(), udaf))
246    }
247    fn register_udwf(&mut self, udaf: Arc<WindowUDF>) -> Result<Option<Arc<WindowUDF>>> {
248        Ok(self.udwfs.insert(udaf.name().into(), udaf))
249    }
250
251    fn expr_planners(&self) -> Vec<Arc<dyn ExprPlanner>> {
252        vec![]
253    }
254
255    fn higher_order_function_names(&self) -> HashSet<String> {
256        self.higher_order_functions.keys().cloned().collect()
257    }
258
259    fn udafs(&self) -> HashSet<String> {
260        self.udafs.keys().cloned().collect()
261    }
262
263    fn udwfs(&self) -> HashSet<String> {
264        self.udwfs.keys().cloned().collect()
265    }
266}
267
268/// A cheaply cloneable pointer to an [ExtensionTypeRegistry].
269pub type ExtensionTypeRegistryRef = Arc<dyn ExtensionTypeRegistry>;
270
271/// Manages [`ExtensionTypeRegistration`]s, which allow users to register custom behavior for
272/// extension types.
273///
274/// Each registration is connected to the extension type name, which can also be looked up to get
275/// the registration.
276pub trait ExtensionTypeRegistry: Debug + Send + Sync {
277    /// Returns a reference to registration of an extension type named `name`.
278    ///
279    /// Returns an error if there is no extension type with that name.
280    fn extension_type_registration(
281        &self,
282        name: &str,
283    ) -> Result<ExtensionTypeRegistrationRef>;
284
285    /// Creates a [`DFExtensionTypeRef`] from the type information in the `field`.
286    ///
287    /// The result `Ok(None)` indicates that there is no extension type metadata. Returns an error
288    /// if the extension type in the metadata is not found.
289    fn create_extension_type_for_field(
290        &self,
291        field: &Field,
292    ) -> Result<Option<DFExtensionTypeRef>> {
293        let Some(extension_type_name) = field.extension_type_name() else {
294            return Ok(None);
295        };
296
297        let registration = self.extension_type_registration(extension_type_name)?;
298        registration
299            .create_df_extension_type(field.data_type(), field.extension_type_metadata())
300            .map(Some)
301    }
302
303    /// Returns all registered [ExtensionTypeRegistration].
304    fn extension_type_registrations(&self) -> Vec<ExtensionTypeRegistrationRef>;
305
306    /// Registers a new [ExtensionTypeRegistrationRef], returning any previously registered
307    /// implementation.
308    ///
309    /// Returns an error if the type cannot be registered, for example, if the registry is
310    /// read-only.
311    fn add_extension_type_registration(
312        &self,
313        extension_type: ExtensionTypeRegistrationRef,
314    ) -> Result<Option<ExtensionTypeRegistrationRef>>;
315
316    /// Extends the registry with the provided extension types.
317    ///
318    /// Returns an error if the type cannot be registered, for example, if the registry is
319    /// read-only.
320    fn extend(&self, extension_types: &[ExtensionTypeRegistrationRef]) -> Result<()> {
321        for extension_type in extension_types.iter().cloned() {
322            self.add_extension_type_registration(extension_type)?;
323        }
324        Ok(())
325    }
326
327    /// Deregisters an extension type registration with the name `name`, returning the
328    /// implementation that was deregistered.
329    ///
330    /// Returns an error if the type cannot be deregistered, for example, if the registry is
331    /// read-only.
332    fn remove_extension_type_registration(
333        &self,
334        name: &str,
335    ) -> Result<Option<ExtensionTypeRegistrationRef>>;
336}
337
338/// A factory that creates instances of extension types from a storage [`DataType`] and the
339/// metadata.
340pub type ExtensionTypeFactory =
341    dyn Fn(&DataType, Option<&str>) -> Result<DFExtensionTypeRef> + Send + Sync;
342
343/// A cheaply cloneable pointer to an [ExtensionTypeRegistration].
344pub type ExtensionTypeRegistrationRef = Arc<ExtensionTypeRegistration>;
345
346/// The registration of an extension type. Implementations of this trait are responsible for
347/// *creating* instances of [`DFExtensionType`] that represent the entire semantics of an extension
348/// type.
349///
350/// # Why do we need a Registration?
351///
352/// A good question is why this trait is even necessary. Why not directly register the
353/// [`DFExtensionType`] in a registry?
354///
355/// While this works for extension types requiring no additional metadata (e.g., `arrow.uuid`), it
356/// does not work for more complex extension types with metadata. For example, consider an extension
357/// type `custom.shortened(n)` that aims to short the pretty-printing string to `n` characters.
358/// Here, `n` is a parameter of the extension type and should be a field in the struct that
359/// implements the [`DFExtensionType`]. The job of the registration is to read the metadata from the
360/// field and create the corresponding [`DFExtensionType`] instance with the correct `n` set.
361///
362/// [`DFExtensionType`]: datafusion_common::types::DFExtensionType
363pub struct ExtensionTypeRegistration {
364    /// The name of the extension type.
365    name: String,
366    /// A function that creates an instance of [`DFExtensionTypeRef`] from the storage type and the
367    /// metadata.
368    factory: Box<ExtensionTypeFactory>,
369}
370
371impl ExtensionTypeRegistration {
372    /// Creates a new registration for an extension type. The factory is required to validate that
373    /// the storage [`DataType`] is compatible with the extension type.
374    pub fn new_arc(
375        name: impl Into<String>,
376        factory: impl Fn(&DataType, Option<&str>) -> Result<DFExtensionTypeRef>
377        + Send
378        + Sync
379        + 'static,
380    ) -> ExtensionTypeRegistrationRef {
381        Arc::new(Self {
382            name: name.into(),
383            factory: Box::new(factory),
384        })
385    }
386}
387
388impl ExtensionTypeRegistration {
389    /// The name of the extension type.
390    ///
391    /// This name will be used to find the correct [ExtensionTypeRegistration] when an extension
392    /// type is encountered.
393    pub fn type_name(&self) -> &str {
394        &self.name
395    }
396
397    /// Creates an extension type instance from the optional metadata. The name of the extension
398    /// type is not a parameter as it's already defined by the registration itself.
399    pub fn create_df_extension_type(
400        &self,
401        storage_type: &DataType,
402        metadata: Option<&str>,
403    ) -> Result<DFExtensionTypeRef> {
404        self.factory.as_ref()(storage_type, metadata)
405    }
406}
407
408impl Debug for ExtensionTypeRegistration {
409    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
410        f.debug_struct("DefaultExtensionTypeRegistration")
411            .field("type_name", &self.name)
412            .finish()
413    }
414}
415
416/// An [`ExtensionTypeRegistry`] that uses in memory [`HashMap`]s.
417#[derive(Clone, Debug)]
418pub struct MemoryExtensionTypeRegistry {
419    /// Holds a mapping between the name of an extension type and its logical type.
420    extension_types: Arc<RwLock<HashMap<String, ExtensionTypeRegistrationRef>>>,
421}
422
423impl Default for MemoryExtensionTypeRegistry {
424    fn default() -> Self {
425        Self::new_empty()
426    }
427}
428
429impl MemoryExtensionTypeRegistry {
430    /// Creates an empty [MemoryExtensionTypeRegistry].
431    pub fn new_empty() -> Self {
432        Self {
433            extension_types: Arc::new(RwLock::new(HashMap::new())),
434        }
435    }
436
437    /// Pre-registers the [canonical extension types](https://arrow.apache.org/docs/format/CanonicalExtensions.html)
438    /// in the extension type registry.
439    pub fn new_with_canonical_extension_types() -> Self {
440        let mapping = [
441            ExtensionTypeRegistration::new_arc(
442                FixedShapeTensor::NAME,
443                |storage_type, metadata| {
444                    Ok(Arc::new(DFFixedShapeTensor::try_new(
445                        storage_type,
446                        FixedShapeTensor::deserialize_metadata(metadata)?,
447                    )?))
448                },
449            ),
450            ExtensionTypeRegistration::new_arc(
451                VariableShapeTensor::NAME,
452                |storage_type, metadata| {
453                    Ok(Arc::new(DFVariableShapeTensor::try_new(
454                        storage_type,
455                        VariableShapeTensor::deserialize_metadata(metadata)?,
456                    )?))
457                },
458            ),
459            ExtensionTypeRegistration::new_arc(Json::NAME, |storage_type, metadata| {
460                Ok(Arc::new(DFJson::try_new(
461                    storage_type,
462                    Json::deserialize_metadata(metadata)?,
463                )?))
464            }),
465            ExtensionTypeRegistration::new_arc(Uuid::NAME, |storage_type, metadata| {
466                Ok(Arc::new(DFUuid::try_new(
467                    storage_type,
468                    Uuid::deserialize_metadata(metadata)?,
469                )?))
470            }),
471            ExtensionTypeRegistration::new_arc(Opaque::NAME, |storage_type, metadata| {
472                Ok(Arc::new(DFOpaque::try_new(
473                    storage_type,
474                    Opaque::deserialize_metadata(metadata)?,
475                )?))
476            }),
477            ExtensionTypeRegistration::new_arc(Bool8::NAME, |storage_type, metadata| {
478                Ok(Arc::new(DFBool8::try_new(
479                    storage_type,
480                    Bool8::deserialize_metadata(metadata)?,
481                )?))
482            }),
483            ExtensionTypeRegistration::new_arc(
484                TimestampWithOffset::NAME,
485                |storage_type, metadata| {
486                    Ok(Arc::new(DFTimestampWithOffset::try_new(
487                        storage_type,
488                        TimestampWithOffset::deserialize_metadata(metadata)?,
489                    )?))
490                },
491            ),
492        ];
493
494        let mut extension_types = HashMap::new();
495        for registration in mapping.into_iter() {
496            extension_types.insert(registration.type_name().to_owned(), registration);
497        }
498
499        Self {
500            extension_types: Arc::new(RwLock::new(HashMap::from(extension_types))),
501        }
502    }
503
504    /// Creates a new [MemoryExtensionTypeRegistry] with the provided `types`.
505    ///
506    /// # Errors
507    ///
508    /// Returns an error if one of the `types` is a native type.
509    pub fn new_with_types(
510        types: impl IntoIterator<Item = ExtensionTypeRegistrationRef>,
511    ) -> Result<Self> {
512        let extension_types = types
513            .into_iter()
514            .map(|t| (t.type_name().to_owned(), t))
515            .collect::<HashMap<_, _>>();
516        Ok(Self {
517            extension_types: Arc::new(RwLock::new(extension_types)),
518        })
519    }
520
521    /// Returns a list of all registered types.
522    pub fn all_extension_types(&self) -> Vec<ExtensionTypeRegistrationRef> {
523        self.extension_types
524            .read()
525            .expect("Extension type registry lock poisoned")
526            .values()
527            .cloned()
528            .collect()
529    }
530}
531
532impl ExtensionTypeRegistry for MemoryExtensionTypeRegistry {
533    fn extension_type_registration(
534        &self,
535        name: &str,
536    ) -> Result<ExtensionTypeRegistrationRef> {
537        self.extension_types
538            .write()
539            .expect("Extension type registry lock poisoned")
540            .get(name)
541            .ok_or_else(|| plan_datafusion_err!("Logical type not found."))
542            .cloned()
543    }
544
545    fn extension_type_registrations(&self) -> Vec<ExtensionTypeRegistrationRef> {
546        self.extension_types
547            .read()
548            .expect("Extension type registry lock poisoned")
549            .values()
550            .cloned()
551            .collect()
552    }
553
554    fn add_extension_type_registration(
555        &self,
556        extension_type: ExtensionTypeRegistrationRef,
557    ) -> Result<Option<ExtensionTypeRegistrationRef>> {
558        Ok(self
559            .extension_types
560            .write()
561            .expect("Extension type registry lock poisoned")
562            .insert(extension_type.type_name().to_owned(), extension_type))
563    }
564
565    fn remove_extension_type_registration(
566        &self,
567        name: &str,
568    ) -> Result<Option<ExtensionTypeRegistrationRef>> {
569        Ok(self
570            .extension_types
571            .write()
572            .expect("Extension type registry lock poisoned")
573            .remove(name))
574    }
575}
576
577impl From<HashMap<String, ExtensionTypeRegistrationRef>> for MemoryExtensionTypeRegistry {
578    fn from(value: HashMap<String, ExtensionTypeRegistrationRef>) -> Self {
579        Self {
580            extension_types: Arc::new(RwLock::new(value)),
581        }
582    }
583}