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