Common aggregation logic
(
&self,
group_by: &[Expression],
aggregates: &[crate::plan::physical::AggregateItem],
input_rows: Vec<Row>,
context: &mut ExecutionContext,
)
| 5737 | |
| 5738 | /// Common aggregation logic |
| 5739 | fn execute_aggregate( |
| 5740 | &self, |
| 5741 | group_by: &[Expression], |
| 5742 | aggregates: &[crate::plan::physical::AggregateItem], |
| 5743 | input_rows: Vec<Row>, |
| 5744 | context: &mut ExecutionContext, |
| 5745 | ) -> Result<Vec<Row>, ExecutionError> { |
| 5746 | use std::collections::HashMap; |
| 5747 | |
| 5748 | // Debug: Check input data |
| 5749 | log::debug!("AGGREGATE DEBUG: Received {} input rows", input_rows.len()); |
| 5750 | if !group_by.is_empty() { |
| 5751 | log::debug!( |
| 5752 | "AGGREGATE DEBUG: GROUP BY expressions: {:?}", |
| 5753 | group_by |
| 5754 | .iter() |
| 5755 | .map(|e| format!("{:?}", e)) |
| 5756 | .collect::<Vec<_>>() |
| 5757 | ); |
| 5758 | } |
| 5759 | |
| 5760 | // Group rows by the group_by expressions |
| 5761 | let mut groups: HashMap<String, Vec<Row>> = HashMap::new(); |
| 5762 | let mut group_key_to_values: HashMap<String, Vec<Value>> = HashMap::new(); |
| 5763 | |
| 5764 | for row in input_rows { |
| 5765 | // Clear local variables from previous row to prevent variable leakage |
| 5766 | context.clear_locals(); |
| 5767 | |
| 5768 | // Set row values in context for expression evaluation |
| 5769 | for (name, value) in &row.values { |
| 5770 | context.set_variable(name.clone(), value.clone()); |
| 5771 | } |
| 5772 | |
| 5773 | // Create group key from group_by expressions |
| 5774 | let mut group_key_values = Vec::new(); |
| 5775 | let mut group_key_strings = Vec::new(); |
| 5776 | for expr in group_by { |
| 5777 | let value = self.evaluate_expression(expr, context)?; |
| 5778 | log::debug!( |
| 5779 | "AGGREGATE DEBUG: GROUP BY expr {:?} evaluated to: {:?}", |
| 5780 | expr, |
| 5781 | value |
| 5782 | ); |
| 5783 | group_key_values.push(value.clone()); |
| 5784 | group_key_strings.push(value.to_string()); |
| 5785 | } |
| 5786 | let group_key = group_key_strings.join("|"); |
| 5787 | log::debug!("AGGREGATE DEBUG: Group key: '{}'", group_key); |
| 5788 | |
| 5789 | // Store the mapping from key to actual values for later use |
| 5790 | group_key_to_values.insert(group_key.clone(), group_key_values); |
| 5791 | |
| 5792 | // Add row to appropriate group |
| 5793 | groups.entry(group_key).or_default().push(row); |
| 5794 | } |
| 5795 | |
| 5796 | // Process each group |
no test coverage detected