jayzhan211 commented on code in PR #27682:
URL: https://github.com/apache/datafusion/pull/27682#discussion_r4808357967


##########
datafusion/sql/src/query.rs:
##########
@@ -312,43 +322,55 @@ impl<S: ContextProvider> SqlToRel<'_, S> {
         }
     }
 
-    /// Handle AGGREGATE pipe operator
+    /// Plans `|> AGGREGATE a GROUP BY g` as `SELECT g, a GROUP BY g`, ordered
+    /// by the items that have an ordering suffix, grouping items first
     fn pipe_operator_aggregate(
         &self,
         plan: LogicalPlan,
         full_table_exprs: Vec<ExprWithAliasAndOrderBy>,
         group_by_expr: Vec<ExprWithAliasAndOrderBy>,
         planner_context: &mut PlannerContext,
     ) -> Result<LogicalPlan> {
-        let plan_schema = plan.schema();
-        let process_expr =
-            |expr_with_alias_and_order_by: ExprWithAliasAndOrderBy,
-             planner_context: &mut PlannerContext| {
-                let expr_with_alias = expr_with_alias_and_order_by.expr;
-                let sql_expr = expr_with_alias.expr;
-                let alias = expr_with_alias.alias;
-
-                let df_expr = self.sql_to_expr(sql_expr, plan_schema, 
planner_context)?;
-
-                match alias {
-                    Some(alias_ident) => 
df_expr.alias_if_changed(alias_ident.value),
-                    None => Ok(df_expr),
-                }
-            };
-
-        let aggr_exprs: Vec<Expr> = full_table_exprs
+        // Grouping by position keeps each grouping item an expression, as pipe
+        // syntax requires: a SELECT reads an integer literal in GROUP BY as an
+        // ordinal, but here `GROUP BY 2` groups by the constant 2
+        let group_by = (1..=group_by_expr.len())
+            .map(|position| SQLExpr::value(Value::Number(position.to_string(), 
false)))
+            .collect();
+        let mut projection = vec![];
+        let mut order_by = vec![];
+        for (index, item) in group_by_expr
             .into_iter()
-            .map(|e| process_expr(e, planner_context))
-            .collect::<Result<Vec<_>>>()?;
-
-        let group_by_exprs: Vec<Expr> = group_by_expr
-            .into_iter()
-            .map(|e| process_expr(e, planner_context))
-            .collect::<Result<Vec<_>>>()?;
-
-        LogicalPlanBuilder::from(plan)
-            .aggregate(group_by_exprs, aggr_exprs)?
-            .build()
+            .chain(full_table_exprs)
+            .enumerate()
+        {
+            let ExprWithAliasAndOrderBy {
+                expr: ExprWithAlias { expr, alias },
+                order_by: options,
+            } = item;
+            if options.sort.is_some() || options.nulls_first.is_some() {
+                order_by.push(OrderByExpr {
+                    expr: SQLExpr::value(Value::Number((index + 
1).to_string(), false)),
+                    options,
+                    with_fill: None,
+                });
+            }
+            projection.push(match alias {
+                Some(alias) => SelectItem::ExprWithAlias { expr, alias },

Review Comment:
   Going through the SELECT path also normalizes aliases, so `|> AGGREGATE 
sum(v) AS Total` now names its column `total`, where 56.0.0 named it `Total`. 
As a result, `|> WHERE Total > 10` now works (it failed on 56.0.0), but `|> 
SELECT "Total"` and code that looks the column up by its old name now fail. The 
new behavior matches a SELECT, so could you list it under user-facing changes 
and pin it with a test?
   
   ```
   # AGGREGATE pipe normalizes aliases like a SELECT, so a later pipe can refer 
to them
   query II
   SELECT * FROM (VALUES (1, 10), (2, 20)) AS t(k, v)
   |> AGGREGATE sum(v) AS Total GROUP BY k
   |> WHERE Total > 10
   |> SELECT k, total
   ----
   2 20
   ```
   



##########
datafusion/sql/src/query.rs:
##########
@@ -312,43 +322,55 @@ impl<S: ContextProvider> SqlToRel<'_, S> {
         }
     }
 
-    /// Handle AGGREGATE pipe operator
+    /// Plans `|> AGGREGATE a GROUP BY g` as `SELECT g, a GROUP BY g`, ordered
+    /// by the items that have an ordering suffix, grouping items first
     fn pipe_operator_aggregate(
         &self,
         plan: LogicalPlan,
         full_table_exprs: Vec<ExprWithAliasAndOrderBy>,
         group_by_expr: Vec<ExprWithAliasAndOrderBy>,
         planner_context: &mut PlannerContext,
     ) -> Result<LogicalPlan> {
-        let plan_schema = plan.schema();
-        let process_expr =
-            |expr_with_alias_and_order_by: ExprWithAliasAndOrderBy,
-             planner_context: &mut PlannerContext| {
-                let expr_with_alias = expr_with_alias_and_order_by.expr;
-                let sql_expr = expr_with_alias.expr;
-                let alias = expr_with_alias.alias;
-
-                let df_expr = self.sql_to_expr(sql_expr, plan_schema, 
planner_context)?;
-
-                match alias {
-                    Some(alias_ident) => 
df_expr.alias_if_changed(alias_ident.value),
-                    None => Ok(df_expr),
-                }
-            };
-
-        let aggr_exprs: Vec<Expr> = full_table_exprs
+        // Grouping by position keeps each grouping item an expression, as pipe
+        // syntax requires: a SELECT reads an integer literal in GROUP BY as an
+        // ordinal, but here `GROUP BY 2` groups by the constant 2
+        let group_by = (1..=group_by_expr.len())
+            .map(|position| SQLExpr::value(Value::Number(position.to_string(), 
false)))
+            .collect();
+        let mut projection = vec![];
+        let mut order_by = vec![];
+        for (index, item) in group_by_expr
             .into_iter()
-            .map(|e| process_expr(e, planner_context))
-            .collect::<Result<Vec<_>>>()?;
-
-        let group_by_exprs: Vec<Expr> = group_by_expr
-            .into_iter()
-            .map(|e| process_expr(e, planner_context))
-            .collect::<Result<Vec<_>>>()?;
-
-        LogicalPlanBuilder::from(plan)
-            .aggregate(group_by_exprs, aggr_exprs)?
-            .build()
+            .chain(full_table_exprs)
+            .enumerate()
+        {
+            let ExprWithAliasAndOrderBy {
+                expr: ExprWithAlias { expr, alias },
+                order_by: options,
+            } = item;
+            if options.sort.is_some() || options.nulls_first.is_some() {
+                order_by.push(OrderByExpr {
+                    expr: SQLExpr::value(Value::Number((index + 
1).to_string(), false)),
+                    options,
+                    with_fill: None,
+                });
+            }
+            projection.push(match alias {
+                Some(alias) => SelectItem::ExprWithAlias { expr, alias },
+                None => SelectItem::UnnamedExpr(expr),
+            });
+        }

Review Comment:
   `GROUP BY a, a`, `GROUP BY a, t.a`, `GROUP BY a AS x, a AS x` and `GROUP BY 
a, a DESC` returned one group key on 56.0.0, but now fail with "Projections 
require unique expression names", because each repeat becomes its own 
projection item. Keeping one item per (expression, normalized alias) and 
pointing a repeat's ASC/DESC at the first one's position restores the 56.0.0 
rows. It passes `pipe_operator.slt`, the `datafusion-sql` tests and clippy:
   
   ```suggestion
           let ordinal =
               |position: usize| 
SQLExpr::value(Value::Number(position.to_string(), false));
           let mut keys = vec![];
           let mut projection = vec![];
           let mut suffixes = vec![];
           for item in group_by_expr {
               let ExprWithAliasAndOrderBy {
                   expr: ExprWithAlias { expr, alias },
                   order_by: options,
               } = item;
               // A repeated grouping item (`GROUP BY a, t.a`) is one group 
key, as
               // it is in a SELECT's GROUP BY; projecting it twice would fail 
on
               // the repeated column name
               let key = (
                   self.sql_to_expr(expr.clone(), plan.schema(), 
planner_context)?,
                   alias
                       .clone()
                       .map(|alias| self.ident_normalizer.normalize(alias)),
               );
               let position = match keys.iter().position(|k| *k == key) {
                   Some(index) => index + 1,
                   None => {
                       keys.push(key);
                       projection.push(match alias {
                           Some(alias) => SelectItem::ExprWithAlias { expr, 
alias },
                           None => SelectItem::UnnamedExpr(expr),
                       });
                       projection.len()
                   }
               };
               suffixes.push((position, options));
           }
           // Grouping by position keeps each grouping item an expression, as 
pipe
           // syntax requires: a SELECT reads an integer literal in GROUP BY as 
an
           // ordinal, but here `GROUP BY 2` groups by the constant 2
           let group_by = (1..=keys.len()).map(ordinal).collect();
           for item in full_table_exprs {
               let ExprWithAliasAndOrderBy {
                   expr: ExprWithAlias { expr, alias },
                   order_by: options,
               } = item;
               projection.push(match alias {
                   Some(alias) => SelectItem::ExprWithAlias { expr, alias },
                   None => SelectItem::UnnamedExpr(expr),
               });
               suffixes.push((projection.len(), options));
           }
           let order_by = suffixes
               .into_iter()
               .filter(|(_, options)| {
                   options.sort.is_some() || options.nulls_first.is_some()
               })
               .map(|(position, options)| OrderByExpr {
                   expr: ordinal(position),
                   options,
                   with_fill: None,
               })
               .collect();
   ```
   
   <details>
   <summary>slt for pipe_operator.slt (both fail on this head; each fails again 
if the dedup, the repeat's ASC/DESC or the alias normalization is 
removed)</summary>
   
   ```
   # A repeated grouping item is one group key, as in a SELECT's GROUP BY
   query II
   SELECT * FROM (VALUES (1, 10), (2, 20), (3, 30), (1, 40)) AS t(k, v)
   |> AGGREGATE sum(v) AS s GROUP BY k, t.k ASC
   ----
   1 50
   2 20
   3 30
   
   query II
   SELECT * FROM (VALUES (1, 10), (2, 20), (3, 30), (1, 40)) AS t(k, v)
   |> AGGREGATE sum(v) AS s GROUP BY k AS X, k AS x DESC
   ----
   3 30
   2 20
   1 50
   ```
   </details>
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to