vladimirg-db commented on code in PR #53474:
URL: https://github.com/apache/spark/pull/53474#discussion_r2619732570


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/resolver/AutoGeneratedAliasProvider.scala:
##########
@@ -42,10 +42,12 @@ class AutoGeneratedAliasProvider(expressionIdAssigner: 
ExpressionIdAssigner) {
   /**
    * Create a new auto-generated [[Alias]]. If the `name` is not provided, 
[[toPrettySql]] is going
    * to be used to generate a proper alias name. We don't call
-   * [[ExpressionIdAssigner.mapExpression]] for outer aliases, because thy 
should be manually
-   * mapped in the context of an outer query.
+   * [[ExpressionIdAssigner.mapExpression]] for:
+   *  - Outer aliases, because thy should be manually mapped in the context of 
an outer query.
+   *  - [[Alias]]es created during fixed-point analysis 
([[ExpressionIdAssigner]] is used only in
+   *    the single-pass resolver).
    */
-  def newOuterAlias(
+  def newPlainAlias(

Review Comment:
   ```suggestion
     def newDanglingAlias(
   ```



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/PivotTransformer.scala:
##########
@@ -0,0 +1,231 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.catalyst.analysis
+
+import org.apache.spark.sql.catalyst.SQLConfHelper
+import 
org.apache.spark.sql.catalyst.analysis.resolver.AutoGeneratedAliasProvider
+import org.apache.spark.sql.catalyst.expressions.{
+  AliasHelper,
+  Attribute,
+  AttributeSet,
+  Cast,
+  EmptyRow,
+  EqualNullSafe,
+  Expression,
+  ExtractValue,
+  If,
+  Literal,
+  NamedExpression
+}
+import org.apache.spark.sql.catalyst.expressions.aggregate.{
+  AggregateExpression,
+  AggregateFunction,
+  ApproximatePercentile,
+  First,
+  Last,
+  PivotFirst
+}
+import org.apache.spark.sql.catalyst.plans.logical.{Aggregate, LogicalPlan, 
Project}
+import org.apache.spark.sql.catalyst.util.toPrettySQL
+import org.apache.spark.sql.errors.QueryCompilationErrors
+import org.apache.spark.sql.types.StringType
+
+/**
+ * Object used to transform [[Pivot]] node into a [[Project]] or [[Aggregate]] 
(based on the tree
+ * structure below the [[Pivot]]).
+ */
+object PivotTransformer extends AliasHelper with SQLConfHelper {
+
+  /**
+   * Transform a pivot operation into an [[Aggregate]] or a combination of 
[[Aggregate]]s and
+   * [[Project]] operators.
+   *
+   *  1. Check all pivot values are literal and match pivot column data type.
+   *
+   *  2. Deduce group-by expressions. Group-by expressions coming from SQL are 
implicit and need to
+   *     be deduced by filtering out pivot column and aggregate references 
from child output.
+   *     In case of:
+   *     {{{
+   *       SELECT year, region, q1, q2, q3, q4
+   *       FROM sales
+   *       PIVOT (sum(sales) AS sales
+   *         FOR quarter
+   *         IN (1 AS q1, 2 AS q2, 3 AS q3, 4 AS q4));
+   *     }}}
+   *     where table `sales` has `year`, `quarter`, `region`, `sales` as 
columns.
+   *     In this example: pivot column would be `quarter`, aggregate would be 
`sales` and because
+   *     of that, `year` and `region` would be grouping expressions.
+   *
+   *  3. Choose between two execution strategies based on aggregate data types:
+   *
+   *     a) If all aggregates support [[PivotFirst]] data types (fast path):
+   *        Since evaluating `pivotValues` `IF` statements for each input row 
can get slow, use an
+   *        alternate plan that instead uses two steps of aggregation:
+   *        - First aggregation: group by original grouping expressions + 
pivot column, compute
+   *          aggregates
+   *        - Second aggregation: group by original grouping expressions only, 
use [[PivotFirst]]
+   *          to extract values for each pivot value
+   *        - Final projection: extract individual pivot outputs using 
[[ExtractValue]]
+   *
+   *     b) Otherwise (standard path):
+   *        Create a single [[Aggregate]] with filtered aggregates for each 
pivot value. For each
+   *        aggregate and pivot value combination:
+   *        - Wrap aggregate children with `If(pivotColumn == pivotValue, 
expr, null)` expressions.
+   *        - Handle special cases for [[First]], [[Last]], and 
[[ApproximatePercentile]] which
+   *          have specific semantics around null handling.
+   */
+  def apply(
+      child: LogicalPlan,
+      pivotValues: Seq[Expression],
+      pivotColumn: Expression,
+      groupByExpressionsOpt: Option[Seq[NamedExpression]],
+      aggregates: Seq[Expression],
+      childOutput: Seq[Attribute],
+      autoGeneratedAliasProvider: AutoGeneratedAliasProvider,
+      fixedPointImplementation: Boolean): LogicalPlan = {
+    val evalPivotValues = pivotValues.map { value =>
+      val foldable = trimAliases(value).foldable
+      if (!foldable) {
+        throw QueryCompilationErrors.nonLiteralPivotValError(value)
+      }
+      if (!Cast.canCast(value.dataType, pivotColumn.dataType)) {
+        throw QueryCompilationErrors.pivotValDataTypeMismatchError(value, 
pivotColumn)
+      }
+      Cast(value, pivotColumn.dataType, 
Some(conf.sessionLocalTimeZone)).eval(EmptyRow)
+    }
+    val groupByExpressions = groupByExpressionsOpt.getOrElse {
+      val pivotColumnAndAggregatesRefs = pivotColumn.references ++ 
AttributeSet(aggregates)
+      childOutput.filterNot(pivotColumnAndAggregatesRefs.contains)
+    }
+    if (aggregates.forall(aggregate => 
PivotFirst.supportsDataType(aggregate.dataType))) {
+      val namedAggExps: Seq[NamedExpression] = aggregates.map { aggregate =>
+        autoGeneratedAliasProvider
+          .newPlainAlias(
+            child = aggregate,
+            name = Some(aggregate.sql)
+          )
+      }
+      val namedPivotCol = pivotColumn match {
+        case namedExpression: NamedExpression => namedExpression
+        case _ =>
+          autoGeneratedAliasProvider.newPlainAlias(
+            child = pivotColumn,
+            name = Some("__pivot_col")
+          )
+      }
+      val extendedGroupingExpressions = groupByExpressions :+ namedPivotCol
+      val firstAgg =
+        Aggregate(extendedGroupingExpressions, extendedGroupingExpressions ++ 
namedAggExps, child)
+      val pivotAggregates = namedAggExps.map { a =>
+        autoGeneratedAliasProvider.newPlainAlias(
+          child = PivotFirst(namedPivotCol.toAttribute, a.toAttribute, 
evalPivotValues)
+            .toAggregateExpression(),
+          name = Some("__pivot_" + a.sql)
+        )
+      }
+      val groupByExpressionsAttributes = groupByExpressions.map(_.toAttribute)
+      val secondAgg =
+        Aggregate(
+          groupByExpressionsAttributes,
+          groupByExpressionsAttributes ++ pivotAggregates,
+          firstAgg
+        )
+      val pivotAggregatesAttributes = pivotAggregates.map(_.toAttribute)
+      val pivotOutputs = pivotValues.zipWithIndex.flatMap {
+        case (value, i) =>
+          aggregates.zip(pivotAggregatesAttributes).map {
+            case (aggregate, pivotAtt) =>
+              autoGeneratedAliasProvider.newPlainAlias(

Review Comment:
   But do we plan to add it to the `ExpressionidAssigner` when calling this 
common code from single-pass analyzer?



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