datafusion_functions/
lib.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18#![doc(
19    html_logo_url = "https://raw.githubusercontent.com/apache/datafusion/19fe44cf2f30cbdd63d4a4f52c74055163c6cc38/docs/logos/standalone_logo/logo_original.svg",
20    html_favicon_url = "https://raw.githubusercontent.com/apache/datafusion/19fe44cf2f30cbdd63d4a4f52c74055163c6cc38/docs/logos/standalone_logo/logo_original.svg"
21)]
22#![cfg_attr(docsrs, feature(doc_auto_cfg))]
23// Make sure fast / cheap clones on Arc are explicit:
24// https://github.com/apache/datafusion/issues/11143
25#![deny(clippy::clone_on_ref_ptr)]
26
27//! Function packages for [DataFusion].
28//!
29//! This crate contains a collection of various function packages for DataFusion,
30//! implemented using the extension API. Users may wish to control which functions
31//! are available to control the binary size of their application as well as
32//! use dialect specific implementations of functions (e.g. Spark vs Postgres)
33//!
34//! Each package is implemented as a separate
35//! module, activated by a feature flag.
36//!
37//! [DataFusion]: https://crates.io/crates/datafusion
38//!
39//! # Available Packages
40//! See the list of [modules](#modules) in this crate for available packages.
41//!
42//! # Using A Package
43//! You can register all functions in all packages using the [`register_all`] function.
44//!
45//! To access and use only the functions in a certain package, use the
46//! `functions()` method in each module.
47//!
48//! ```
49//! # fn main() -> datafusion_common::Result<()> {
50//! # let mut registry = datafusion_execution::registry::MemoryFunctionRegistry::new();
51//! # use datafusion_execution::FunctionRegistry;
52//! // get the encoding functions
53//! use datafusion_functions::encoding;
54//! for udf in encoding::functions() {
55//!   registry.register_udf(udf)?;
56//! }
57//! # Ok(())
58//! # }
59//! ```
60//!
61//! Each package also exports an `expr_fn` submodule to help create [`Expr`]s that invoke
62//! functions using a fluent style. For example:
63//!
64//! ```
65//! // create an Expr that will invoke the encode function
66//! use datafusion_expr::{col, lit};
67//! use datafusion_functions::expr_fn;
68//! // Equivalent to "encode(my_data, 'hex')" in SQL:
69//! let expr = expr_fn::encode(col("my_data"), lit("hex"));
70//! ```
71//!
72//![`Expr`]: datafusion_expr::Expr
73//!
74//! # Implementing A New Package
75//!
76//! To add a new package to this crate, you should follow the model of existing
77//! packages. The high level steps are:
78//!
79//! 1. Create a new module with the appropriate [`ScalarUDF`] implementations.
80//!
81//! 2. Use the macros in [`macros`] to create standard entry points.
82//!
83//! 3. Add a new feature to `Cargo.toml`, with any optional dependencies
84//!
85//! 4. Use the `make_package!` macro to expose the module when the
86//!    feature is enabled.
87//!
88//! [`ScalarUDF`]: datafusion_expr::ScalarUDF
89use datafusion_common::Result;
90use datafusion_execution::FunctionRegistry;
91use datafusion_expr::ScalarUDF;
92use log::debug;
93use std::sync::Arc;
94
95#[macro_use]
96pub mod macros;
97
98#[cfg(feature = "string_expressions")]
99pub mod string;
100make_stub_package!(string, "string_expressions");
101
102/// Core datafusion expressions
103/// These are always available and not controlled by a feature flag
104pub mod core;
105
106/// Date and time expressions.
107/// Contains functions such as to_timestamp
108/// Enabled via feature flag `datetime_expressions`
109#[cfg(feature = "datetime_expressions")]
110pub mod datetime;
111make_stub_package!(datetime, "datetime_expressions");
112
113/// Encoding expressions.
114/// Contains Hex and binary `encode` and `decode` functions.
115/// Enabled via feature flag `encoding_expressions`
116#[cfg(feature = "encoding_expressions")]
117pub mod encoding;
118make_stub_package!(encoding, "encoding_expressions");
119
120/// Mathematical functions.
121/// Enabled via feature flag `math_expressions`
122#[cfg(feature = "math_expressions")]
123pub mod math;
124make_stub_package!(math, "math_expressions");
125
126/// Regular expression functions.
127/// Enabled via feature flag `regex_expressions`
128#[cfg(feature = "regex_expressions")]
129pub mod regex;
130make_stub_package!(regex, "regex_expressions");
131
132#[cfg(feature = "crypto_expressions")]
133pub mod crypto;
134make_stub_package!(crypto, "crypto_expressions");
135
136#[cfg(feature = "unicode_expressions")]
137pub mod unicode;
138make_stub_package!(unicode, "unicode_expressions");
139
140#[cfg(any(feature = "datetime_expressions", feature = "unicode_expressions"))]
141pub mod planner;
142
143pub mod strings;
144
145pub mod utils;
146
147/// Fluent-style API for creating `Expr`s
148pub mod expr_fn {
149    pub use super::core::expr_fn::*;
150    #[cfg(feature = "crypto_expressions")]
151    pub use super::crypto::expr_fn::*;
152    #[cfg(feature = "datetime_expressions")]
153    pub use super::datetime::expr_fn::*;
154    #[cfg(feature = "encoding_expressions")]
155    pub use super::encoding::expr_fn::*;
156    #[cfg(feature = "math_expressions")]
157    pub use super::math::expr_fn::*;
158    #[cfg(feature = "regex_expressions")]
159    pub use super::regex::expr_fn::*;
160    #[cfg(feature = "string_expressions")]
161    pub use super::string::expr_fn::*;
162    #[cfg(feature = "unicode_expressions")]
163    pub use super::unicode::expr_fn::*;
164}
165
166/// Return all default functions
167pub fn all_default_functions() -> Vec<Arc<ScalarUDF>> {
168    core::functions()
169        .into_iter()
170        .chain(datetime::functions())
171        .chain(encoding::functions())
172        .chain(math::functions())
173        .chain(regex::functions())
174        .chain(crypto::functions())
175        .chain(unicode::functions())
176        .chain(string::functions())
177        .collect::<Vec<_>>()
178}
179
180/// Registers all enabled packages with a [`FunctionRegistry`]
181pub fn register_all(registry: &mut dyn FunctionRegistry) -> Result<()> {
182    let all_functions = all_default_functions();
183
184    all_functions.into_iter().try_for_each(|udf| {
185        let existing_udf = registry.register_udf(udf)?;
186        if let Some(existing_udf) = existing_udf {
187            debug!("Overwrite existing UDF: {}", existing_udf.name());
188        }
189        Ok(()) as Result<()>
190    })?;
191    Ok(())
192}
193
194#[cfg(test)]
195mod tests {
196    use crate::all_default_functions;
197    use datafusion_common::Result;
198    use std::collections::HashSet;
199
200    #[test]
201    fn test_no_duplicate_name() -> Result<()> {
202        let mut names = HashSet::new();
203        for func in all_default_functions() {
204            assert!(
205                names.insert(func.name().to_string().to_lowercase()),
206                "duplicate function name: {}",
207                func.name()
208            );
209            for alias in func.aliases() {
210                assert!(
211                    names.insert(alias.to_string().to_lowercase()),
212                    "duplicate function name: {}",
213                    alias
214                );
215            }
216        }
217        Ok(())
218    }
219}