gengliangwang commented on code in PR #60756:
URL: https://github.com/apache/spark/pull/60756#discussion_r4652298916


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/SetOperationCharPadding.scala:
##########
@@ -0,0 +1,161 @@
+/*
+ * 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 scala.collection.mutable
+
+import org.apache.spark.sql.catalyst.expressions.{Alias, Attribute, 
Expression, ExprId, NamedExpression}
+import org.apache.spark.sql.catalyst.plans.logical.{CTERelationRef, Except, 
Intersect, LogicalPlan, Project, SetOperation, Union, UnionLoop, UnionLoopRef}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.util.CharVarcharUtils
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.DataType
+
+/**
+ * The SQL standard gives a set operation of CHAR(n) and CHAR(m) the length 
max(n, m). When the
+ * children of a Union, Intersect or Except have CHAR columns or fields of 
different lengths at
+ * the same position, this pads the values of the shorter children to the 
widest length, in a
+ * Project over each child that needs it, as 
[[TypeCoercionBase.WidenSetOperationTypes]] casts
+ * them to the widest type. The output of the set operation, which comes from 
its first child,
+ * then has the widest length. Like read-side padding, the padding does not 
truncate longer values.
+ *
+ * During analysis, such a set operation is not resolved until its children 
are padded, see
+ * [[isAligned]], so that nothing above it is resolved with the shorter length 
of its first child.
+ * The children are padded once the set operation is resolved otherwise, after 
the widening of
+ * their types and the deduplication of their output: in 
[[PadSetOperationCharLengths]] by the
+ * fixed-point analyzer, and in `SetOperationLikeResolver` by the single-pass 
resolver, both with
+ * [[padChildren]].
+ */
+object SetOperationCharPadding {
+
+  /**
+   * Whether the CHAR lengths of the children of a set operation are the same 
at each position, so
+   * that it needs no padding. As their types, the CHAR types of the children 
of a set operation
+   * stay the same after analysis, which optimizer rules keep. True if the 
children are not
+   * resolved yet.
+   */
+  def isAligned(children: Seq[LogicalPlan]): Boolean = !needsPadding(children)

Review Comment:
   **[P1] Handle inherited CHAR metadata exposed by optimizer simplification**
   
   Optimizer rules can still introduce unequal CHAR metadata without changing 
explicit metadata. Alias.metadata is empty for an IF expression but inherits 
its child's metadata after SimplifyConditionals replaces that IF with an 
Attribute. In the query below, retaining c3 and c5 as additional outputs 
prevents CollapseProject from inlining their multiply referenced scan-padding 
expressions. SimplifyConditionals therefore exposes CHAR(3) in the first branch 
and CHAR(5) in the second. The unconditional alignment check makes the 
previously resolved Union unresolved, and the default lightweight optimizer 
validation throws PLAN_VALIDATION_FAILED_RULE_IN_BATCH. Preserving explicit 
metadata in PushProjectionThroughUnion does not address these implicit aliases.
   
   **Failure scenario:** With default settings and a Parquet table t(c3 
CHAR(3), c5 CHAR(5)) containing ('a', 'a'), run SELECT IF(true, c3, c5) AS x, 
c3, c5 FROM t UNION ALL SELECT IF(false, c3, c5) AS x, c3, c5 FROM t. Analysis 
succeeds, but optimization fails instead of returning two rows.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/Optimizer.scala:
##########
@@ -1519,8 +1519,13 @@ object PushProjectionThroughUnion extends 
Rule[LogicalPlan] {
     val result = e transform {
       case a: Attribute => rewrites(a)
     } match {
-      // Make sure exprId is unique in each child of Union.
-      case Alias(child, alias) => Alias(child, alias)()
+      // Make sure exprId is unique in each child of Union. The alias keeps 
its explicit metadata,
+      // as in the first child, so that the CHAR types of the children stay 
the same, see
+      // SetOperationCharPadding.
+      case a @ Alias(child, alias) =>
+        Alias(child, alias)(

Review Comment:
   **[P2] Design: Reuse Alias.newInstance for the metadata-preserving copy**
   
   The expanded reconstruction duplicates `Alias.newInstance()` in 
`sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/namedExpressions.scala:190-194`,
 which already creates a fresh expression ID while preserving explicit 
metadata, non-inheritable metadata keys, and the qualifier. 
`analysis/DeduplicateRelations.scala:543-544` uses that helper for the same 
alias-refresh operation. Replace this branch with `case a: Alias => 
a.newInstance()`.
   
   **Why it matters:** UNION pushdown now maintains a separate list of alias 
fields to preserve. Changes to the canonical copying policy must also be 
applied here, risking another metadata-loss regression in the CHAR alignment 
this change introduces.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/CharVarcharUtils.scala:
##########
@@ -393,12 +415,26 @@ object CharVarcharUtils extends Logging with 
SparkCharVarcharUtils {
 
   /**
    * Matches the read-side CHAR padding that [[addPaddingForScan]] wraps a 
column in (when
-   * standard semantics are off) and extracts the padded expression and the 
CHAR length.
+   * standard semantics are off) and extracts the padded expression and the 
CHAR length. A padding
+   * over another one to a length that is not longer, or a narrowing to a 
length that is not longer,
+   * matches as one padding of its value.
    */
   private[sql] object ReadSidePadding {
     def unapply(e: Expression): Option[(Expression, Int)] = e match {
       case s @ StaticInvoke(_, _, READ_SIDE_PADDING, Seq(child, Literal(n: 
Int, _)), _, _, _, _,
           None) if s.staticObject == classOf[CharVarcharCodegenUtils] =>
+        child match {
+          // The padding of a set operation over the padding of a scan, to a 
length that is at
+          // least as long, is the padding of the scan to that length.
+          case ReadSidePadding(grandChild, m) if m <= n => Some((grandChild, 
n))
+          case _ => Some((child, n))
+        }
+      // The narrowing of a view or a recursive CTE over the padding to a 
longer length: for a value
+      // that fits in the shorter length, which is all a string of that length 
can be equal to, it
+      // is the padding of the value to that length.
+      case s @ StaticInvoke(_, _, CHAR_TYPE_NARROWING,

Review Comment:
   **[P0] Preserve narrowing semantics when translating pushed predicates**
   
   Narrowing is not equivalent to read-side padding at the shorter length, 
including when compared with a literal of exactly that length. For a stored 
value 'a    ', charTypeNarrowing(readSidePadding(value, 5), 3) returns 'a  ', 
whereas readSidePadding(value, 3) preserves all five characters. This extractor 
makes V2ExpressionBuilder.generateCharPadLiteralCmp translate the former into 
CHAR_READ_SIDE_PADDING(value, 3) = 'a  '. A V2 source evaluating that function 
according to its documented semantics rejects a matching row, even if Spark 
also retains a residual filter. Preserve the narrowing operation in the 
translation or decline this pushdown.
   
   **Failure scenario:** An existing view v over t3 UNION ALL t5 stores 
CHAR(3), while t5.c is CHAR(5) and stores 'a    '. On a V2 source implementing 
CHAR_READ_SIDE_PADDING, SELECT * FROM v WHERE c = 'a' loses the t5 row when its 
newly narrowed filter is pushed down.



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