-
Notifications
You must be signed in to change notification settings - Fork 8
/
aggregate.rs
281 lines (254 loc) · 9.43 KB
/
aggregate.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
// SPDX-License-Identifier: Apache-2.0
//! Module providing parse/validation functions for aggregate relations.
//!
//! The aggregate operation groups input data on one or more sets of grouping
//! keys, calculating each measure for each combination of grouping key.
//!
//! See <https://substrait.io/relations/logical_relations/#aggregate-operation>
use crate::input::proto::substrait;
use crate::output::comment;
use crate::output::diagnostic;
use crate::output::type_system::data;
use crate::parse::context;
use crate::parse::expressions;
use crate::parse::expressions::functions;
use std::collections::HashSet;
/// Type of output field.
enum FieldType {
/// A field passed straight on from the input, but uniquified.
GroupedField,
/// Like GroupedField, but grouping sets exist that this field is not a
/// part of. Null will be returned for such rows.
NullableGroupedField,
/// An aggregate function applied to the input rows that were combined for
/// the current output row.
Measure,
/// The index of the grouping set that the result corresponds to.
GroupingSetIndex,
}
/// A grouping or aggregate expression returned by the aggregate relation.
struct Field {
/// Description of the grouping or aggregate expression.
expression: expressions::Expression,
/// Data type returned by the expression.
data_type: data::Type,
/// The type of field.
field_type: FieldType,
}
/// Parse a measure.
fn parse_measure(
x: &substrait::aggregate_rel::Measure,
y: &mut context::Context,
) -> diagnostic::Result<expressions::Expression> {
// Parse the aggregate function.
let (n, e) = proto_required_field!(x, y, measure, functions::parse_aggregate_function);
let data_type = n.data_type();
let expression = e.unwrap_or_default();
y.set_data_type(data_type.clone());
// Parse the filter and describe the node.
if x.filter.is_some() {
let (n, e) = proto_required_field!(x, y, filter, expressions::parse_predicate);
let filter = e.unwrap_or_default();
let filter_type = n.data_type();
summary!(
y,
"Applies aggregate function {expression:#} to all rows for \
which {filter:#} returns true."
);
let filtered_expression = expressions::Expression::Function(
String::from("filter"),
vec![
expressions::functions::FunctionArgument::Value(filter_type, filter),
expressions::functions::FunctionArgument::Value(data_type, expression),
],
);
describe!(
y,
Expression,
"Filtered aggregate function: {filtered_expression}"
);
Ok(filtered_expression)
} else {
summary!(y, "Applies aggregate function {expression:#} to all rows.");
describe!(y, Expression, "Aggregate function: {expression}");
Ok(expression)
}
}
/// Parse aggregate relation.
pub fn parse_aggregate_rel(
x: &substrait::AggregateRel,
y: &mut context::Context,
) -> diagnostic::Result<()> {
// Parse input.
let in_type = handle_rel_input!(x, y);
// Set schema context for the grouping and measure expressions.
y.set_schema(in_type);
// Parse grouping sets.
let mut grouping_set_expressions: Vec<substrait::Expression> = vec![];
let mut fields = vec![];
let mut sets = vec![];
proto_repeated_field!(x, y, groupings, |x, y| {
sets.push(vec![]);
proto_repeated_field!(x, y, grouping_expressions, |x, y| {
let result = expressions::parse_expression(x, y);
// See if we parsed this expression before. If not, add it to the
// field list. Return the index in the field list.
let index = grouping_set_expressions
.iter()
.enumerate()
.find(|(_, e)| e == &x)
.map(|(i, _)| i)
.unwrap_or_else(|| {
// Create new field.
grouping_set_expressions.push(x.clone());
fields.push(Field {
expression: result.as_ref().cloned().unwrap_or_default(),
data_type: y.data_type(),
field_type: FieldType::NullableGroupedField,
});
fields.len() - 1
});
// Add index of uniquified field to grouping set.
sets.last_mut().unwrap().push(index);
result
});
match x.grouping_expressions.len() {
0 => summary!(y, "A grouping set that aggregates all rows."),
1 => summary!(
y,
"A grouping set that aggregates all rows for which \
the expression yields the same value."
),
x => summary!(
y,
"A grouping set that aggregates all rows for which \
the {x} expressions yield the same tuple of values."
),
}
Ok(())
});
drop(grouping_set_expressions);
let sets = sets;
// Each field that is part of all sets will never be made nullable by the
// aggregate relation, so its type does not need to be made nullable.
let mut set_iter = sets.iter();
if let Some(first_set) = set_iter.next() {
let mut fields_in_all_sets = first_set.iter().cloned().collect::<HashSet<_>>();
for set in set_iter {
fields_in_all_sets = &fields_in_all_sets & &set.iter().cloned().collect::<HashSet<_>>();
}
for index in fields_in_all_sets {
fields[index].field_type = FieldType::GroupedField;
}
}
// Parse measures.
proto_repeated_field!(x, y, measures, |x, y| {
let result = parse_measure(x, y);
fields.push(Field {
expression: result.as_ref().cloned().unwrap_or_default(),
data_type: y.data_type(),
field_type: FieldType::Measure,
});
result
});
// The relation is invalid if no fields result from it.
if fields.is_empty() {
diagnostic!(
y,
Error,
RelationInvalid,
"aggregate relations must have at least one grouping expression or measure"
);
}
// Add the column for the grouping set index if there is more than one
// grouping set.
if sets.len() > 1 {
fields.push(Field {
expression: expressions::Expression::Function(String::from("group_index"), vec![]),
data_type: data::new_integer(),
field_type: FieldType::GroupingSetIndex,
});
}
let fields = fields;
// Derive schema.
y.set_schema(data::new_struct(
fields.iter().map(|x| {
if matches!(x.field_type, FieldType::NullableGroupedField) {
x.data_type.make_nullable()
} else {
x.data_type.clone()
}
}),
false,
));
// Describe the relation.
if x.groupings.is_empty() {
describe!(y, Relation, "Aggregate");
summary!(
y,
"This relation computes {} aggregate function(s) over all rows, \
returning a single row.",
x.measures.len()
);
} else if x.measures.is_empty() {
describe!(y, Relation, "Group");
summary!(
y,
"This relation groups rows from the input by the result of some \
expression(s)."
);
} else {
describe!(y, Relation, "Group & aggregate");
summary!(
y,
"This relation groups rows from the input by the result of some \
expression(s), and also compures {} aggregate function(s) over \
each group.",
x.measures.len()
);
}
let mut comment = comment::Comment::new()
.plain("The significance of the returned field(s) is:")
.lo();
for (index, field) in fields.iter().enumerate() {
comment = comment.li().plain(match field.field_type {
FieldType::GroupedField => format!(
"Field {index}: value of grouping expression {:#}.",
field.expression
),
FieldType::NullableGroupedField => format!(
"Field {index}: value of grouping expression {:#} if it is \
part of the grouping set being returned, null otherwise.",
field.expression
),
FieldType::Measure => {
if x.groupings.is_empty() {
format!(
"Field {index}: result of aggregate function {:#} \
applied to all input rows.",
field.expression
)
} else {
format!(
"Field {index}: result of aggregate function {:#} \
applied to the rows from the current group.",
field.expression
)
}
}
FieldType::GroupingSetIndex => {
format!(
"Field {index}: integer between 0 and {} inclusive, \
representing the index of the matched grouping set.",
x.groupings.len() - 1
)
}
});
}
y.push_summary(comment.lc());
// Handle the common field.
handle_rel_common!(x, y);
// Handle the advanced extension field.
handle_advanced_extension!(x, y);
Ok(())
}