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


##########
datafusion/sql/src/query.rs:
##########
@@ -312,43 +322,65 @@ 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
-            .into_iter()
-            .map(|e| process_expr(e, planner_context))
-            .collect::<Result<Vec<_>>>()?;
-
-        let group_by_exprs: Vec<Expr> = group_by_expr
+        // A SELECT reads an integer literal in GROUP BY as an ordinal, which 
pipe
+        // syntax doesn't allow. Grouping by it as a constant instead would be
+        // surprising, so reject it
+        if let Some(literal) = group_by_expr
+            .iter()
+            .map(|item| &item.expr.expr)
+            .find(|expr| is_integer_literal(expr))
+        {
+            return plan_err!(
+                "Integer literals are not allowed in the GROUP BY of |> 
AGGREGATE: {literal}"
+            );
+        }
+        let group_by = group_by_expr
+            .iter()
+            .map(|item| item.expr.expr.clone())
+            .collect();

Review Comment:
   Rejecting integer literals breaks queries that return rows on 56.0.0: `|> 
AGGREGATE count(*) AS c GROUP BY 2` and `GROUP BY k, 5` group by the constant 
there, and on #5492 alamb's rule is that "we shouldn't be breaking queries that 
worked (and produced correct rows) in previous releases". The check also misses 
`GROUP BY (2)`, `+2` and `-1`, which still go through ordinal resolution and 
fail with "Aggregate function 'count(Int64(1))' is not supported in this 
position" or "Cannot find column with position -1". Grouping by position fixes 
all of them and lets you drop `is_integer_literal` and the `plan_err` import:
   
   ```suggestion
           // 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();
   ```
   
   <details>
   <summary>slt replacing the integer-literal error test (each case errors on 
this head and returns these rows on 56.0.0)</summary>
   
   ```
   # Pipe syntax has no column ordinals, so integer literals in AGGREGATE's
   # GROUP BY group by a constant, like other literals
   query II
   SELECT * FROM (VALUES (1, 10), (2, 20)) AS t(k, v)
   |> AGGREGATE count(*) AS c GROUP BY 2
   ----
   2 2
   
   query II
   SELECT * FROM (VALUES (1, 10), (2, 20)) AS t(k, v)
   |> AGGREGATE count(*) AS c GROUP BY (2)
   ----
   2 2
   
   query II
   SELECT * FROM (VALUES (1, 10), (2, 20)) AS t(k, v)
   |> AGGREGATE count(*) AS c GROUP BY -1
   ----
   -1 2
   
   query III rowsort
   SELECT * FROM (VALUES (1, 10), (2, 20)) AS t(k, v)
   |> AGGREGATE count(*) AS c GROUP BY k, 5
   ----
   1 5 1
   2 5 1
   ```
   </details>
   



##########
datafusion/sql/src/select.rs:
##########
@@ -410,6 +496,31 @@ impl<S: ContextProvider> SqlToRel<'_, S> {
             }
         }
 
+        match select.disallowed {
+            Disallowed::Nothing => {}
+            Disallowed::Aggregates { operator } => {
+                if let Some(aggr) = aggr_exprs.first() {
+                    return plan_err!(
+                        "Aggregate function calls are not allowed in 
{operator}: '{aggr}'. Use |> AGGREGATE instead"
+                    );
+                }
+            }
+            Disallowed::WindowFunctions { operator, help } => {
+                let window = find_window_exprs(
+                    select_exprs
+                        .iter()
+                        .chain(order_by_rex.iter().map(|s| &s.expr)),
+                )
+                .into_iter()
+                .next();

Review Comment:
   Optional cleanup: the ORDER BY of `|> AGGREGATE` only holds ordinals of the 
projection, so any window function it could reach is already in `select_exprs`. 
Removing the chain passes every test, and without it a reader won't look for an 
ORDER BY case that can't happen.
   
   ```suggestion
                   let window = 
find_window_exprs(select_exprs.iter()).into_iter().next();
   ```
   



##########
datafusion/sqllogictest/test_files/pipe_operator.slt:
##########
@@ -160,6 +220,104 @@ query TII rowsort
 ----
 apples 2 9
 
+# Ordering suffixes in AGGREGATE pipe
+query II
+SELECT * FROM (VALUES (3, 1), (1, 2), (2, 3), (NULL, 4)) AS t(k, v)
+|> AGGREGATE sum(v) AS s GROUP BY k DESC
+----
+NULL 4
+3 1
+2 3
+1 2
+
+query II
+SELECT * FROM (VALUES (3, 1), (1, 2), (2, 3), (NULL, 4)) AS t(k, v)
+|> AGGREGATE sum(v) AS s DESC GROUP BY k
+----
+NULL 4
+2 3
+1 2
+3 1
+
+query III
+SELECT * FROM (VALUES (1, 1, 10), (1, 2, 30), (2, 1, 5), (2, 2, 7)) AS t(a, b, 
v)
+|> AGGREGATE sum(v) AS s DESC GROUP BY a ASC, b
+----
+1 2 30
+1 1 10
+2 2 7
+2 1 5
+
+# unnest in AGGREGATE pipe GROUP BY
+query II
+SELECT * FROM (VALUES (1, [1, 2]), (2, [3]), (3, [1])) AS t(k, xs)
+|> AGGREGATE count(*) AS c GROUP BY unnest(xs) AS x ASC
+----
+1 2
+2 1
+3 1
+
+# Pipe syntax doesn't allow column ordinals in AGGREGATE's GROUP BY, which a
+# SELECT would read an integer literal as, so integer literals are rejected
+statement error DataFusion error: Error during planning: Integer literals are 
not allowed in the GROUP BY of \|> AGGREGATE: 2
+SELECT * FROM (VALUES (1, 10), (2, 20)) AS t(k, v)
+|> AGGREGATE count(*) AS c GROUP BY 2
+
+# but other literals group by a constant
+query TI
+SELECT * FROM (VALUES (1, 10), (2, 20)) AS t(k, v)
+|> AGGREGATE count(*) AS c GROUP BY 'x'
+----
+x 2
+
+query RI
+SELECT * FROM (VALUES (1, 10), (2, 20)) AS t(k, v)
+|> AGGREGATE count(*) AS c GROUP BY 2.5
+----
+2.5 2
+
+# Window functions aren't allowed in AGGREGATE pipe
+statement error DataFusion error: Error during planning: Window function calls 
are not allowed in \|> AGGREGATE
+SELECT * FROM (VALUES (1, 10), (2, 20)) AS t(k, v)
+|> AGGREGATE sum(v) AS s, row_number() OVER (ORDER BY k) AS rn GROUP BY k
+
+statement error DataFusion error: Error during planning: Window function calls 
are not allowed in GROUP BY
+SELECT * FROM (VALUES (1, 10), (2, 20)) AS t(k, v)
+|> AGGREGATE count(*) AS c GROUP BY row_number() OVER (ORDER BY k) AS rn
+
+# Aggregate functions aren't allowed in SELECT, EXTEND and ORDER BY pipes
+statement error DataFusion error: Error during planning: Aggregate function 
calls are not allowed in \|> SELECT
+SELECT * FROM (VALUES (1, 10), (2, 20)) AS t(k, v)
+|> SELECT sum(v) AS s
+

Review Comment:
   Optional cleanup: the plain-text form avoids the `\|` escapes and also pins 
the "Use |> AGGREGATE instead" hint. The same applies to the EXTEND and ORDER 
BY cases below (I ran all three this way).
   
   ```suggestion
   statement error
   SELECT * FROM (VALUES (1, 10), (2, 20)) AS t(k, v)
   |> SELECT sum(v) AS s
   ----
   DataFusion error: Error during planning: Aggregate function calls are not 
allowed in |> SELECT: 'sum(t.v)'. Use |> AGGREGATE instead
   
   
   ```
   



-- 
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