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