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


##########
datafusion/sql/src/query.rs:
##########
@@ -119,16 +118,13 @@ impl<S: ContextProvider> SqlToRel<'_, S> {
             PipeOperator::Where { expr } => {
                 self.plan_selection(Some(expr), plan, planner_context)
             }
-            PipeOperator::OrderBy { exprs } => {
-                let sort_exprs = self.order_by_to_sort_expr(
-                    exprs,
-                    plan.schema(),
-                    planner_context,
-                    true,
-                    None,
-                )?;
-                self.order_by(plan, sort_exprs)
-            }
+            PipeOperator::OrderBy { exprs } => self.select_parts_to_plan(

Review Comment:
   After a `USING` join, `|> ORDER BY` now returns one copy of the join column. 
Before this PR it returned both: `SELECT * FROM t |> JOIN u USING (k) |> ORDER 
BY v` gave `k, v, k, w` and now gives `k, v, w`, while `|> WHERE` on the same 
input still returns 4 columns. The cause is the `SELECT *` expansion, which 
removes duplicate USING columns. The new output matches how USING works in a 
regular `SELECT`, so could you list it under user-facing changes and pin it 
with a test?
   
   ```
   # After a USING join, ORDER BY pipe keeps one copy of the join column
   query IIT
   SELECT * FROM (VALUES (1, 10), (2, 20)) AS t(k, v)
   |> JOIN (SELECT * FROM (VALUES (1, 'a'), (2, 'b')) AS u(k, w)) AS u USING (k)
   |> ORDER BY v DESC
   ----
   2 20 b
   1 10 a
   ```



##########
datafusion/sql/src/query.rs:
##########
@@ -312,43 +308,43 @@ 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
+        let group_by = group_by_expr
+            .iter()
+            .map(|item| item.expr.expr.clone())
+            .collect();

Review Comment:
   An integer literal in the GROUP BY of `|> AGGREGATE` is now read as an 
ordinal, so `|> AGGREGATE count(*) AS c GROUP BY 2` fails with "Aggregate 
function 'count(Int64(1))' is not supported in this position", and `GROUP BY 5` 
fails with "Cannot find column with position 5". Both returned a constant group 
before. The pipe syntax doesn't allow ordinals there. Since the grouping items 
are the first `n` projection items, grouping by their positions keeps literals 
constant and also drops the clone:
   
   ```suggestion
           // Group by position so that an integer literal grouping item is a
           // constant, as in the pipe syntax, rather than an ordinal
           let group_by = (1..=group_by_expr.len())
               .map(|position| 
SQLExpr::value(Value::Number(position.to_string(), false)))
               .collect();
   ```
   
   With a test (it fails on the current head and passes with the change):
   ```
   # An integer literal in the AGGREGATE pipe GROUP BY is a constant, not an 
ordinal
   query II
   SELECT * FROM (VALUES (1, 10), (2, 20)) AS t(k, v)
   |> AGGREGATE count(*) AS c GROUP BY 2
   ----
   2 2
   ```



##########
datafusion/sql/src/query.rs:
##########
@@ -142,20 +138,20 @@ impl<S: ContextProvider> SqlToRel<'_, S> {
                 planner_context,
             ),
             PipeOperator::Select { exprs } => {

Review Comment:
   Question: the pipe syntax spec says `|> SELECT` "doesn't perform 
aggregation" and that window functions "aren't allowed" in `|> AGGREGATE`. With 
this PR, `|> SELECT count(*)` aggregates and `|> AGGREGATE sum(v), row_number() 
OVER (ORDER BY k) GROUP BY k` plans. Is that intended? Rejecting both keeps us 
aligned with the spec, and an error can be relaxed later, but once users rely 
on the permissive form we can't take it back.



##########
datafusion/sqllogictest/test_files/pipe_operator.slt:
##########
@@ -72,6 +72,66 @@ FROM test
 ----
 1 1.1 2.1
 
+# Window functions in SELECT and EXTEND pipes
+query III rowsort
+SELECT * FROM (VALUES (1, 10), (1, 20), (2, 30)) AS t(k, v)
+|> EXTEND ROW_NUMBER() OVER (PARTITION BY k ORDER BY v DESC) AS rn
+|> WHERE rn = 1
+----
+1 20 1
+2 30 1
+
+query II rowsort
+SELECT * FROM (VALUES (1, 10), (1, 20), (2, 30)) AS t(k, v)
+|> SELECT k, ROW_NUMBER() OVER (PARTITION BY k ORDER BY v) AS rn
+----
+1 1
+1 2
+2 1
+
+query IIII rowsort
+SELECT * FROM (VALUES (1, 10), (1, 20), (2, 30)) AS t(k, v)
+|> EXTEND LAG(v) OVER (PARTITION BY k ORDER BY v) AS prev_v,
+          LEAD(v) OVER (PARTITION BY k ORDER BY v) AS next_v
+----
+1 10 NULL 20
+1 20 10 NULL
+2 30 NULL NULL
+
+query III rowsort
+SELECT * FROM (VALUES (1, 10), (1, 20), (2, 30)) AS t(k, v)
+|> SELECT k, v - LAG(v) OVER (PARTITION BY k ORDER BY v) AS dv, LEAD(v, 1, 0) 
OVER (ORDER BY v) AS next_v
+----
+1 10 30
+1 NULL 20
+2 NULL 0
+
+# unnest in SELECT and EXTEND pipes
+query I
+SELECT [1, 2, 3] AS xs
+|> SELECT unnest(xs) AS x
+----
+1
+2
+3
+
+query ?I
+SELECT [1, 2, 3] AS xs
+|> EXTEND unnest(xs) AS x
+----
+[1, 2, 3] 1
+[1, 2, 3] 2
+[1, 2, 3] 3
+
+# Window functions in ORDER BY pipe
+query II
+SELECT * FROM (VALUES (1, 10), (1, 20), (2, 30)) AS t(k, v)
+|> ORDER BY row_number() OVER (ORDER BY v DESC)
+----
+2 30
+1 20
+1 10

Review Comment:
   This PR also fixes wrong rows on main: when the input is a `DISTINCT ON` 
with its own `ORDER BY`, `|> ORDER BY` used to replace the sort that decides 
which row `DISTINCT ON` keeps. The query below returns `2 30 / 1 10` on main 
instead of `2 40 / 1 20`. Could you add it as a regression test, and mention it 
in the description?
   
   ```
   # ORDER BY pipe sorts the DISTINCT ON output; it does not replace the ORDER 
BY
   # that picks which row DISTINCT ON keeps
   query II
   SELECT DISTINCT ON (k) k, v
   FROM (VALUES (1, 10), (1, 20), (1, 5), (2, 30), (2, 40)) AS t(k, v)
   ORDER BY k, v DESC
   |> ORDER BY k DESC
   ----
   2 40
   1 20
   ```



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