peter-toth commented on code in PR #52474:
URL: https://github.com/apache/spark/pull/52474#discussion_r2387635927


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/FileFormatWriter.scala:
##########
@@ -153,10 +151,34 @@ object FileFormatWriter extends Logging {
       case p: SparkPlan => 
p.withNewChildren(p.children.map(materializeAdaptiveSparkPlan))
     }
 
+    val query = 
writeFilesOpt.map(_.child).getOrElse(materializeAdaptiveSparkPlan(plan))
+
     // the sort order doesn't matter
-    val actualOrdering = writeFilesOpt.map(_.child)
-      .getOrElse(materializeAdaptiveSparkPlan(plan))
-      .outputOrdering
+    val actualOrdering = query.outputOrdering
+
+    val queryOutput = query match {
+      case o: OrderPreservingUnaryExecNode => o.outputExpressions
+      case _ => query.output
+    }
+
+    @tailrec
+    def isLiteral(e: Expression, name: String): Option[String] =
+      e match {
+        case Alias(child, n) => isLiteral(child, n)
+        case _: Literal => Some(name)
+        case _ => None
+      }
+
+    val literalColumns = queryOutput.flatMap { ne => isLiteral(ne, ne.name) }
+
+    // We should first sort by dynamic partition columns, then bucket id, and 
finally sorting
+    // columns, then drop literal columns

Review Comment:
   So you basically change `requiredOrdering` and drop those columns that are 
defined as literals in `outputExpressions` of the top 
`OrderPreservingUnaryExecNode` node. But what if a literal definition is not in 
the top node?
   
   Shouldn't we do the other way around and fix `actualOrdering`? I mean if we 
have a query:
   ```
   +- Project [i, j, 0 AS k]
      + ...
         +- Sort [i]
            +- Relation
   ```
   Then shouldn't `actualOrdering` (`outputOrdering` of the `Project`) be 
`Seq(SortOrder(k), SortOrder(i))` as we know that `k` is a contant? I.e. 
`Project` could prepend its contants to the alias transformed 
`child.outputOrdering`.
   
   And similarly, when we have:
   ```
   +- Sort [i]
      + ...
         +- Project [i, j, 0 AS k]
            +- Relation
   ```
   Then shoudn't `outputOrdering` of the `Project` node be `Seq(SortOrder(k))`, 
and `outputOrdering` of the `Sort` be `Seq(SortOrder(k), SortOrder(i))`? I.e. 
`Project` could somehow mark that `SortOrder(k)` as "constant order", and 
`Sort` should just extend "constant order" expressions from 
`child.outputOrdering` with the new order expressions (`i`).



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