datafusion_python/expr/
aggregate_expr.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
18use crate::expr::PyExpr;
19use datafusion::logical_expr::expr::AggregateFunction;
20use pyo3::prelude::*;
21use std::fmt::{Display, Formatter};
22
23#[pyclass(
24    frozen,
25    name = "AggregateFunction",
26    module = "datafusion.expr",
27    subclass
28)]
29#[derive(Clone)]
30pub struct PyAggregateFunction {
31    aggr: AggregateFunction,
32}
33
34impl From<PyAggregateFunction> for AggregateFunction {
35    fn from(aggr: PyAggregateFunction) -> Self {
36        aggr.aggr
37    }
38}
39
40impl From<AggregateFunction> for PyAggregateFunction {
41    fn from(aggr: AggregateFunction) -> PyAggregateFunction {
42        PyAggregateFunction { aggr }
43    }
44}
45
46impl Display for PyAggregateFunction {
47    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
48        let args: Vec<String> = self
49            .aggr
50            .params
51            .args
52            .iter()
53            .map(|expr| expr.to_string())
54            .collect();
55        write!(f, "{}({})", self.aggr.func.name(), args.join(", "))
56    }
57}
58
59#[pymethods]
60impl PyAggregateFunction {
61    /// Get the aggregate type, such as "MIN", or "MAX"
62    fn aggregate_type(&self) -> String {
63        self.aggr.func.name().to_string()
64    }
65
66    /// is this a distinct aggregate such as `COUNT(DISTINCT expr)`
67    fn is_distinct(&self) -> bool {
68        self.aggr.params.distinct
69    }
70
71    /// Get the arguments to the aggregate function
72    fn args(&self) -> Vec<PyExpr> {
73        self.aggr
74            .params
75            .args
76            .iter()
77            .map(|expr| PyExpr::from(expr.clone()))
78            .collect()
79    }
80
81    /// Get a String representation of this column
82    fn __repr__(&self) -> String {
83        format!("{self}")
84    }
85}