datafusion_functions_aggregate/
grouping.rs1use std::any::Any;
21use std::fmt;
22
23use arrow::datatypes::Field;
24use arrow::datatypes::{DataType, FieldRef};
25use datafusion_common::{not_impl_err, Result};
26use datafusion_expr::function::AccumulatorArgs;
27use datafusion_expr::function::StateFieldsArgs;
28use datafusion_expr::utils::format_state_name;
29use datafusion_expr::{
30 Accumulator, AggregateUDFImpl, Documentation, Signature, Volatility,
31};
32use datafusion_macros::user_doc;
33
34make_udaf_expr_and_func!(
35 Grouping,
36 grouping,
37 expression,
38 "Returns 1 if the data is aggregated across the specified column or 0 for not aggregated in the result set.",
39 grouping_udaf
40);
41
42#[user_doc(
43 doc_section(label = "General Functions"),
44 description = "Returns 1 if the data is aggregated across the specified column, or 0 if it is not aggregated in the result set.",
45 syntax_example = "grouping(expression)",
46 sql_example = r#"```sql
47> SELECT column_name, GROUPING(column_name) AS group_column
48 FROM table_name
49 GROUP BY GROUPING SETS ((column_name), ());
50+-------------+-------------+
51| column_name | group_column |
52+-------------+-------------+
53| value1 | 0 |
54| value2 | 0 |
55| NULL | 1 |
56+-------------+-------------+
57```"#,
58 argument(
59 name = "expression",
60 description = "Expression to evaluate whether data is aggregated across the specified column. Can be a constant, column, or function."
61 )
62)]
63#[derive(PartialEq, Eq, Hash)]
64pub struct Grouping {
65 signature: Signature,
66}
67
68impl fmt::Debug for Grouping {
69 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
70 f.debug_struct("Grouping")
71 .field("name", &self.name())
72 .field("signature", &self.signature)
73 .finish()
74 }
75}
76
77impl Default for Grouping {
78 fn default() -> Self {
79 Self::new()
80 }
81}
82
83impl Grouping {
84 pub fn new() -> Self {
86 Self {
87 signature: Signature::variadic_any(Volatility::Immutable),
88 }
89 }
90}
91
92impl AggregateUDFImpl for Grouping {
93 fn as_any(&self) -> &dyn Any {
94 self
95 }
96
97 fn name(&self) -> &str {
98 "grouping"
99 }
100
101 fn signature(&self) -> &Signature {
102 &self.signature
103 }
104
105 fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
106 Ok(DataType::Int32)
107 }
108
109 fn state_fields(&self, args: StateFieldsArgs) -> Result<Vec<FieldRef>> {
110 Ok(vec![Field::new(
111 format_state_name(args.name, "grouping"),
112 DataType::Int32,
113 true,
114 )
115 .into()])
116 }
117
118 fn accumulator(&self, _acc_args: AccumulatorArgs) -> Result<Box<dyn Accumulator>> {
119 not_impl_err!(
120 "physical plan is not yet implemented for GROUPING aggregate function"
121 )
122 }
123
124 fn documentation(&self) -> Option<&Documentation> {
125 self.doc()
126 }
127}