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_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#![cfg_attr(test, allow(clippy::needless_pass_by_value))]
27// https://github.com/apache/datafusion/issues/18881
28#![deny(clippy::allow_attributes)]
29
30//! Function packages for [DataFusion].
31//!
32//! This crate contains a collection of various function packages for DataFusion,
33//! implemented using the extension API. Users may wish to control which functions
34//! are available to control the binary size of their application as well as
35//! use dialect specific implementations of functions (e.g. Spark vs Postgres)
36//!
37//! Each package is implemented as a separate
38//! module, activated by a feature flag.
39//!
40//! [DataFusion]: https://crates.io/crates/datafusion
41//!
42//! # Available Packages
43//! See the list of [modules](#modules) in this crate for available packages.
44//!
45//! # Using A Package
46//! You can register all functions in all packages using the [`register_all`] function.
47//!
48//! To access and use only the functions in a certain package, use the
49//! `functions()` method in each module.
50//!
51//! ```
52//! # fn main() -> datafusion_common::Result<()> {
53//! # let mut registry = datafusion_execution::registry::MemoryFunctionRegistry::new();
54//! # use datafusion_execution::FunctionRegistry;
55//! // get the encoding functions
56//! use datafusion_functions::encoding;
57//! for udf in encoding::functions() {
58//!   registry.register_udf(udf)?;
59//! }
60//! # Ok(())
61//! # }
62//! ```
63//!
64//! Each package also exports an `expr_fn` submodule to help create [`Expr`]s that invoke
65//! functions using a fluent style. For example:
66//!
67//! ```
68//! // create an Expr that will invoke the encode function
69//! use datafusion_expr::{col, lit};
70//! use datafusion_functions::expr_fn;
71//! // Equivalent to "encode(my_data, 'hex')" in SQL:
72//! let expr = expr_fn::encode(col("my_data"), lit("hex"));
73//! ```
74//!
75//![`Expr`]: datafusion_expr::Expr
76//!
77//! # Implementing A New Package
78//!
79//! To add a new package to this crate, you should follow the model of existing
80//! packages. The high level steps are:
81//!
82//! 1. Create a new module with the appropriate [`ScalarUDF`] implementations.
83//!
84//! 2. Use the macros in [`macros`] to create standard entry points.
85//!
86//! 3. Add a new feature to `Cargo.toml`, with any optional dependencies
87//!
88//! 4. Use the `make_package!` macro to expose the module when the
89//!    feature is enabled.
90//!
91//! [`ScalarUDF`]: datafusion_expr::ScalarUDF
92use datafusion_common::Result;
93use datafusion_execution::FunctionRegistry;
94use datafusion_expr::ScalarUDF;
95use log::debug;
96use std::sync::Arc;
97
98#[macro_use]
99pub mod macros;
100
101#[cfg(feature = "string_expressions")]
102pub mod string;
103make_stub_package!(string, "string_expressions");
104
105/// Core datafusion expressions
106/// These are always available and not controlled by a feature flag
107pub mod core;
108
109/// Date and time expressions.
110/// Contains functions such as to_timestamp
111/// Enabled via feature flag `datetime_expressions`
112#[cfg(feature = "datetime_expressions")]
113pub mod datetime;
114make_stub_package!(datetime, "datetime_expressions");
115
116/// Encoding expressions.
117/// Contains Hex and binary `encode` and `decode` functions.
118/// Enabled via feature flag `encoding_expressions`
119#[cfg(feature = "encoding_expressions")]
120pub mod encoding;
121make_stub_package!(encoding, "encoding_expressions");
122
123/// Mathematical functions.
124/// Enabled via feature flag `math_expressions`
125#[cfg(feature = "math_expressions")]
126pub mod math;
127make_stub_package!(math, "math_expressions");
128
129/// Regular expression functions.
130/// Enabled via feature flag `regex_expressions`
131#[cfg(feature = "regex_expressions")]
132pub mod regex;
133make_stub_package!(regex, "regex_expressions");
134
135#[cfg(feature = "crypto_expressions")]
136pub mod crypto;
137make_stub_package!(crypto, "crypto_expressions");
138
139#[cfg(feature = "unicode_expressions")]
140pub mod unicode;
141make_stub_package!(unicode, "unicode_expressions");
142
143#[cfg(any(feature = "datetime_expressions", feature = "unicode_expressions"))]
144pub mod planner;
145
146pub mod strings;
147
148pub mod utils;
149
150/// Fluent-style API for creating `Expr`s
151pub mod expr_fn {
152    pub use super::core::expr_fn::*;
153    #[cfg(feature = "crypto_expressions")]
154    pub use super::crypto::expr_fn::*;
155    #[cfg(feature = "datetime_expressions")]
156    pub use super::datetime::expr_fn::*;
157    #[cfg(feature = "encoding_expressions")]
158    pub use super::encoding::expr_fn::*;
159    #[cfg(feature = "math_expressions")]
160    pub use super::math::expr_fn::*;
161    #[cfg(feature = "regex_expressions")]
162    pub use super::regex::expr_fn::*;
163    #[cfg(feature = "string_expressions")]
164    pub use super::string::expr_fn::*;
165    #[cfg(feature = "unicode_expressions")]
166    pub use super::unicode::expr_fn::*;
167}
168
169/// Return all default functions
170pub fn all_default_functions() -> Vec<Arc<ScalarUDF>> {
171    core::functions()
172        .into_iter()
173        .chain(datetime::functions())
174        .chain(encoding::functions())
175        .chain(math::functions())
176        .chain(regex::functions())
177        .chain(crypto::functions())
178        .chain(unicode::functions())
179        .chain(string::functions())
180        .collect::<Vec<_>>()
181}
182
183/// Registers all enabled packages with a [`FunctionRegistry`]
184pub fn register_all(registry: &mut dyn FunctionRegistry) -> Result<()> {
185    let all_functions = all_default_functions();
186
187    all_functions.into_iter().try_for_each(|udf| {
188        let existing_udf = registry.register_udf(udf)?;
189        if let Some(existing_udf) = existing_udf {
190            debug!("Overwrite existing UDF: {}", existing_udf.name());
191        }
192        Ok(()) as Result<()>
193    })?;
194    Ok(())
195}
196
197#[cfg(test)]
198#[ctor::ctor]
199fn init() {
200    // Enable RUST_LOG logging configuration for test
201    let _ = env_logger::try_init();
202}
203
204#[cfg(test)]
205mod tests {
206    use crate::all_default_functions;
207    use datafusion_common::Result;
208    use std::collections::HashSet;
209
210    #[test]
211    fn test_no_duplicate_name() -> Result<()> {
212        let mut names = HashSet::new();
213        for func in all_default_functions() {
214            assert!(
215                names.insert(func.name().to_string().to_lowercase()),
216                "duplicate function name: {}",
217                func.name()
218            );
219            for alias in func.aliases() {
220                assert!(
221                    names.insert(alias.to_string().to_lowercase()),
222                    "duplicate function name: {alias}"
223                );
224            }
225        }
226        Ok(())
227    }
228}