Skip to main content

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