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