datafusion_functions_aggregate/
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
27//! Aggregate Function packages for [DataFusion].
28//!
29//! This crate contains a collection of various aggregate 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//! Each package also exports an `expr_fn` submodule to help create [`Expr`]s that invoke
46//! functions using a fluent style. For example:
47//!
48//![`Expr`]: datafusion_expr::Expr
49//!
50//! # Implementing A New Package
51//!
52//! To add a new package to this crate, you should follow the model of existing
53//! packages. The high level steps are:
54//!
55//! 1. Create a new module with the appropriate [AggregateUDF] implementations.
56//!
57//! 2. Use the macros in [`macros`] to create standard entry points.
58//!
59//! 3. Add a new feature to `Cargo.toml`, with any optional dependencies
60//!
61//! 4. Use the `make_package!` macro to expose the module when the
62//!    feature is enabled.
63
64#[macro_use]
65pub mod macros;
66
67pub mod approx_distinct;
68pub mod approx_median;
69pub mod approx_percentile_cont;
70pub mod approx_percentile_cont_with_weight;
71pub mod array_agg;
72pub mod average;
73pub mod bit_and_or_xor;
74pub mod bool_and_or;
75pub mod correlation;
76pub mod count;
77pub mod covariance;
78pub mod first_last;
79pub mod grouping;
80pub mod hyperloglog;
81pub mod median;
82pub mod min_max;
83pub mod nth_value;
84pub mod percentile_cont;
85pub mod regr;
86pub mod stddev;
87pub mod string_agg;
88pub mod sum;
89pub mod variance;
90
91pub mod planner;
92mod utils;
93
94use crate::approx_percentile_cont::approx_percentile_cont_udaf;
95use crate::approx_percentile_cont_with_weight::approx_percentile_cont_with_weight_udaf;
96use datafusion_common::Result;
97use datafusion_execution::FunctionRegistry;
98use datafusion_expr::AggregateUDF;
99use log::debug;
100use std::sync::Arc;
101
102/// Fluent-style API for creating `Expr`s
103pub mod expr_fn {
104    pub use super::approx_distinct::approx_distinct;
105    pub use super::approx_median::approx_median;
106    pub use super::approx_percentile_cont::approx_percentile_cont;
107    pub use super::approx_percentile_cont_with_weight::approx_percentile_cont_with_weight;
108    pub use super::array_agg::array_agg;
109    pub use super::average::avg;
110    pub use super::average::avg_distinct;
111    pub use super::bit_and_or_xor::bit_and;
112    pub use super::bit_and_or_xor::bit_or;
113    pub use super::bit_and_or_xor::bit_xor;
114    pub use super::bool_and_or::bool_and;
115    pub use super::bool_and_or::bool_or;
116    pub use super::correlation::corr;
117    pub use super::count::count;
118    pub use super::count::count_distinct;
119    pub use super::covariance::covar_pop;
120    pub use super::covariance::covar_samp;
121    pub use super::first_last::first_value;
122    pub use super::first_last::last_value;
123    pub use super::grouping::grouping;
124    pub use super::median::median;
125    pub use super::min_max::max;
126    pub use super::min_max::min;
127    pub use super::nth_value::nth_value;
128    pub use super::percentile_cont::percentile_cont;
129    pub use super::regr::regr_avgx;
130    pub use super::regr::regr_avgy;
131    pub use super::regr::regr_count;
132    pub use super::regr::regr_intercept;
133    pub use super::regr::regr_r2;
134    pub use super::regr::regr_slope;
135    pub use super::regr::regr_sxx;
136    pub use super::regr::regr_sxy;
137    pub use super::regr::regr_syy;
138    pub use super::stddev::stddev;
139    pub use super::stddev::stddev_pop;
140    pub use super::sum::sum;
141    pub use super::sum::sum_distinct;
142    pub use super::variance::var_pop;
143    pub use super::variance::var_sample;
144}
145
146/// Returns all default aggregate functions
147pub fn all_default_aggregate_functions() -> Vec<Arc<AggregateUDF>> {
148    vec![
149        array_agg::array_agg_udaf(),
150        first_last::first_value_udaf(),
151        first_last::last_value_udaf(),
152        covariance::covar_samp_udaf(),
153        covariance::covar_pop_udaf(),
154        correlation::corr_udaf(),
155        sum::sum_udaf(),
156        min_max::max_udaf(),
157        min_max::min_udaf(),
158        median::median_udaf(),
159        count::count_udaf(),
160        regr::regr_slope_udaf(),
161        regr::regr_intercept_udaf(),
162        regr::regr_count_udaf(),
163        regr::regr_r2_udaf(),
164        regr::regr_avgx_udaf(),
165        regr::regr_avgy_udaf(),
166        regr::regr_sxx_udaf(),
167        regr::regr_syy_udaf(),
168        regr::regr_sxy_udaf(),
169        variance::var_samp_udaf(),
170        variance::var_pop_udaf(),
171        stddev::stddev_udaf(),
172        stddev::stddev_pop_udaf(),
173        approx_median::approx_median_udaf(),
174        approx_distinct::approx_distinct_udaf(),
175        approx_percentile_cont_udaf(),
176        approx_percentile_cont_with_weight_udaf(),
177        percentile_cont::percentile_cont_udaf(),
178        string_agg::string_agg_udaf(),
179        bit_and_or_xor::bit_and_udaf(),
180        bit_and_or_xor::bit_or_udaf(),
181        bit_and_or_xor::bit_xor_udaf(),
182        bool_and_or::bool_and_udaf(),
183        bool_and_or::bool_or_udaf(),
184        average::avg_udaf(),
185        grouping::grouping_udaf(),
186        nth_value::nth_value_udaf(),
187    ]
188}
189
190/// Registers all enabled packages with a [`FunctionRegistry`]
191pub fn register_all(registry: &mut dyn FunctionRegistry) -> Result<()> {
192    let functions: Vec<Arc<AggregateUDF>> = all_default_aggregate_functions();
193
194    functions.into_iter().try_for_each(|udf| {
195        let existing_udaf = registry.register_udaf(udf)?;
196        if let Some(existing_udaf) = existing_udaf {
197            debug!("Overwrite existing UDAF: {}", existing_udaf.name());
198        }
199        Ok(()) as Result<()>
200    })?;
201
202    Ok(())
203}
204
205#[cfg(test)]
206mod tests {
207    use crate::all_default_aggregate_functions;
208    use datafusion_common::Result;
209    use std::collections::HashSet;
210
211    #[test]
212    fn test_no_duplicate_name() -> Result<()> {
213        let mut names = HashSet::new();
214        for func in all_default_aggregate_functions() {
215            assert!(
216                names.insert(func.name().to_string().to_lowercase()),
217                "duplicate function name: {}",
218                func.name()
219            );
220            for alias in func.aliases() {
221                assert!(
222                    names.insert(alias.to_string().to_lowercase()),
223                    "duplicate function name: {alias}"
224                );
225            }
226        }
227        Ok(())
228    }
229}