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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/basicLogicalOperators.scala:
##########
@@ -712,7 +712,8 @@ case class Union(
     !(byName || allowMissingCol) &&
     childrenResolved &&
     allChildrenCompatible &&
-    (!conf.unionIsResolvedWhenDuplicatesPerChildResolved || 
duplicatesResolvedPerBranch)
+    (!conf.unionIsResolvedWhenDuplicatesPerChildResolved || 
duplicatesResolvedPerBranch) &&
+    SetOperationCharPadding.isAligned(children)

Review Comment:
   **[P2] CHAR-misaligned union now runs WidenSetOperationTypes, whose Casts 
drop CHAR raw types of nested fields**
   
   Before this PR, a union whose children differ only in nested nullability 
(struct field `nullable`, array `containsNull`) was resolved, because 
`allChildrenCompatible` ignores nullability, and WidenSetOperationTypes skipped 
it. Now a CHAR-length mismatch makes the union unresolved, so 
WidenSetOperationTypes, which runs before PadSetOperationCharLengths, casts 
those columns with `Alias(Cast(e, dt), e.name)()`. Alias of a Cast gets empty 
metadata (namedExpressions.scala:177), so the raw CHAR type is lost. 
PadSetOperationCharLengths then sees a child without raw type, 
`widerCharRawType` returns None, and nothing is padded. The output type 
degrades to STRING.
   
   **Failure scenario:** s3.s is STRUCT<c: CHAR(3) NOT NULL> and s5.s is 
STRUCT<c: CHAR(5)>. `SELECT s FROM s3 UNION ALL SELECT s FROM s5` used to 
resolve without casts, with output struct<c:char(3)>. Now child 0 is cast to 
struct<c:string>, its raw-type metadata is dropped, no padding is applied, and 
the output schema is struct<c:string>, so a CTAS over it writes a STRING field 
instead of CHAR. The PR's struct tests do not cover a nullability difference.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/SetOperationCharPadding.scala:
##########
@@ -0,0 +1,150 @@
+/*
+ * 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, 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.
+ *
+ * Until its children are padded, such a set operation is not resolved, see 
[[isAligned]], so that
+ * nothing above it is resolved with the shorter length of its first child. 
The fixed-point
+ * analyzer pads them in [[PadSetOperationCharLengths]], and the single-pass 
resolver in
+ * `SetOperationLikeResolver`, 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. True if its children are not resolved yet.
+   */
+  def isAligned(children: Seq[LogicalPlan]): Boolean = {
+    !children.forall(_.resolved) ||
+      widerCharRawTypes(children, children.map(_.output)).forall(_.isEmpty)
+  }
+
+  /**
+   * Pads the columns of the children of a set operation that have CHAR 
lengths shorter than the
+   * widest at their position, see [[CharVarcharUtils.widerCharRawTypes]]. 
Without read-side
+   * padding, the values of the widest children can be shorter too, so they 
are padded as well.
+   * `newAlias` builds the alias of a padded column from the padded value, the 
column, and the
+   * raw type of the padded value. Returns the children and their outputs, 
which are the given
+   * ones if no column needs padding.
+   */
+  def padChildren(
+      children: Seq[LogicalPlan],
+      childOutputs: Seq[Seq[Attribute]],
+      newAlias: (Expression, Attribute, DataType) => Alias)
+      : (Seq[LogicalPlan], Seq[Seq[Attribute]]) = {
+    val rawTypes = widerCharRawTypes(children, childOutputs)
+    if (rawTypes.forall(_.isEmpty)) {
+      (children, childOutputs)
+    } else {
+      val alwaysPad = !SQLConf.get.readSideCharPadding
+      children.zip(childOutputs).map { case (child, output) =>
+        // A column at more than one position has one raw type, and gets one 
padded column.
+        val paddedColumns = mutable.HashMap.empty[ExprId, NamedExpression]
+        val projectList = output.zip(rawTypes).map {
+          case (attr, Some(rawType)) =>
+            paddedColumns.getOrElseUpdate(attr.exprId,

Review Comment:
   **[P2] CHAR length of a repeated UNION ALL column depends on whether another 
column needs widening**
   
   In the fixed-point analyzer, ResolveReferences deduplicates a union child's 
repeated output only when `u.allChildrenCompatible` (Analyzer.scala:1726). If 
another column needs type widening, deduplication is deferred, and 
PadSetOperationCharLengths runs on the still-duplicated output. 
`widerCharRawTypes` then groups the repeated positions and gives them one 
widest CHAR length. Without the widening column, deduplication runs first and 
the positions keep separate lengths. The single-pass resolver always 
deduplicates before padding, so the fixed-point and single-pass plans and 
schemas diverge.
   
   **Failure scenario:** t3.c is CHAR(3), and t35 has c3 CHAR(3) and c5 
CHAR(5). `SELECT c, c, 1 FROM t3 UNION ALL SELECT c3, c5, 1L FROM t35`: column 
0 becomes CHAR(5) and t3 values are padded to 'a    '. `SELECT c, c FROM t3 
UNION ALL SELECT c3, c5 FROM t35`: column 0 is CHAR(3) with value 'a  ', as the 
PR's own test asserts (CharVarcharTestSuite line 788). Under the single-pass 
resolver the first query gives CHAR(3), which a HybridAnalyzer dual run reports 
as a mismatch.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/basicLogicalOperators.scala:
##########
@@ -712,7 +712,8 @@ case class Union(
     !(byName || allowMissingCol) &&
     childrenResolved &&
     allChildrenCompatible &&
-    (!conf.unionIsResolvedWhenDuplicatesPerChildResolved || 
duplicatesResolvedPerBranch)
+    (!conf.unionIsResolvedWhenDuplicatesPerChildResolved || 
duplicatesResolvedPerBranch) &&
+    SetOperationCharPadding.isAligned(children)

Review Comment:
   **[P1] Union.resolved now depends on CHAR metadata, which optimizer rules 
can make unequal across children**
   
   `Union.resolved` (and `SetOperation.resolved` at line 411) now requires 
`SetOperationCharPadding.isAligned`, which compares the CHAR raw-type metadata 
of each child's output. Optimizer rules do not keep that metadata the same 
across children. `PushProjectionThroughUnion.pushToRight` 
(Optimizer.scala:1523) copies the Project's Alias, with its explicit metadata, 
into the first child, but rebuilds it as `Alias(child, alias)()` in the other 
children, so they inherit their own column's raw type. The pushed-down Union is 
then misaligned and unresolved, and lightweight plan-change validation (on by 
default, LogicalPlan.scala:553) fails the query with INTERNAL_ERROR: "The plan 
was previously resolved and now became unresolved".
   
   **Failure scenario:** Tables a5 and b5 both have CHAR(5) column c, and t10 
has CHAR(10) column c. 
`spark.table("a5").union(spark.table("b5")).select(col("c").as("c", 
spark.table("t10").schema("c").metadata)).collect()`: analysis passes because 
the children agree. PushProjectionThroughUnion gives child 0 the explicit 
char(10) metadata and child 1 char(5) from b5.c, so isAligned is false and the 
optimizer throws INTERNAL_ERROR. A second path: a view stored as CHAR(5) over a 
union whose tables were later recreated as CHAR(3). Its Project with explicit 
char(5) metadata is pushed through the union in the same way.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/CharVarcharUtils.scala:
##########
@@ -409,23 +424,228 @@ object CharVarcharUtils extends Logging with 
SparkCharVarcharUtils {
    * attributes. When comparing two char type columns/fields, we need to pad 
the shorter one to
    * the longer length.
    */
-  def addPaddingInStringComparison(attrs: Seq[Attribute], alwaysPad: Boolean): 
Seq[Expression] = {
-    val rawTypes = attrs.map(attr => getRawType(attr.metadata))
+  def addPaddingInStringComparison(attrs: Seq[Attribute], alwaysPad: Boolean): 
Seq[Expression] =
+    addPaddingInStringComparison(attrs, attrs.map(attr => 
getRawType(attr.metadata)), alwaysPad)
+
+  /**
+   * Like the method above, for expressions with the given raw types, such as 
a scalar subquery or
+   * a column of an IN subquery, whose raw type is the one of their column. 
With `truncate = false`,
+   * it pads like read-side padding, which keeps longer values instead of 
truncating them.
+   */
+  def addPaddingInStringComparison(
+      exprs: Seq[Expression],
+      rawTypes: Seq[Option[DataType]],
+      alwaysPad: Boolean,
+      truncate: Boolean = true): Seq[Expression] = {
     if (rawTypes.exists(_.isEmpty)) {
-      attrs
-    } else if (attrs.exists(attr => !RowOrdering.isOrderable(attr.dataType))) {
+      exprs
+    } else if (exprs.exists(expr => !RowOrdering.isOrderable(expr.dataType))) {
       // Comparing a non-orderable type, such as a struct holding a MAP, is 
rejected later by
       // CheckAnalysis. Leave it alone so the error names the attribute the 
user wrote rather
       // than the rewritten struct.
-      attrs
+      exprs
     } else {
       val typeWithTargetCharLength = 
rawTypes.map(_.get).reduce(typeWithWiderCharLength)
-      attrs.zip(rawTypes.map(_.get)).map { case (attr, rawType) =>
-        padCharToTargetLength(attr, rawType, typeWithTargetCharLength, 
alwaysPad).getOrElse(attr)
+      exprs.zip(rawTypes.map(_.get)).map { case (expr, rawType) =>
+        padCharToTargetLength(expr, rawType, typeWithTargetCharLength, 
alwaysPad, truncate)
+          .getOrElse(expr)
+      }
+    }
+  }
+
+  /**
+   * The raw type of the output of a UNION at one position, given the outputs 
of its children
+   * there, if they are CHAR types, or structs and arrays of them, with 
different lengths at the
+   * same places: the widest lengths, as the SQL standard gives the union of 
CHAR(n) and CHAR(m)
+   * the length max(n, m). Keeps the names of the first attribute's fields. 
Returns None if the
+   * raw types are the same, or not all CHAR types of the same shape.
+   */
+  def widerCharRawType(attrs: Seq[Attribute]): Option[DataType] = {
+    val rawTypeStrings = attrs.map(attr => getRawTypeString(attr.metadata))
+    if (rawTypeStrings.exists(_.isEmpty) || rawTypeStrings.distinct.length == 
1) {
+      None
+    } else {
+      val rawTypes = rawTypeStrings.map(s => 
CatalystSqlParser.parseDataType(s.get))
+      // Raw types can differ only in how they print, such as with the default 
collation given
+      // explicitly or with other names of struct fields. They have the same 
lengths already.
+      if (rawTypes.map(normalizeCharType).distinct.length == 1) {
+        None
+      } else {
+        rawTypes.map(Option(_)).reduce {
+          (left, right) => for (l <- left; r <- right; wider <- 
widerCharType(l, r)) yield wider
+        }
       }
     }
   }
 
+  // The type with the collation of each CHAR type given explicitly, and 
without field names.
+  private def normalizeCharType(dt: DataType): DataType = dt match {
+    case c: CharType => CharType(c.length, Some(c.collationId))
+    case StructType(fields) =>
+      StructType(fields.map(f => StructField("", 
normalizeCharType(f.dataType))))
+    case ArrayType(et, _) => ArrayType(normalizeCharType(et))
+    case other => other
+  }
+
+  /**
+   * Pads the CHAR columns and fields of the given attribute that are shorter 
than those at the
+   * same places of the given raw type, see [[widerCharRawType]]. Like 
read-side padding, it does
+   * not truncate longer values. Returns the padded value and its raw type, 
which keeps the names
+   * of the attribute's fields, or None if the attribute is already as long, 
unless `alwaysPad`,
+   * for values that the scan does not pad.
+   */
+  def padCharToWiderLength(
+      attr: Attribute,
+      rawType: DataType,
+      alwaysPad: Boolean = false): Option[(Expression, DataType)] = {
+    getRawType(attr.metadata).flatMap { attrRawType =>
+      widerCharType(attrRawType, rawType).filter(alwaysPad || _ != 
attrRawType).map { wider =>
+        val padded = processStringForCharVarchar(
+          attr, wider, charFuncName = Some(READ_SIDE_PADDING), varcharFuncName 
= None)
+        (padded, wider)
+      }
+    }
+  }
+
+
+  /**
+   * The raw type of a value with the given metadata and data type. The raw 
type of a column is in
+   * its metadata, and the raw types of fields of a struct built from columns, 
such as by
+   * `named_struct`, are in the metadata of the fields. None if neither has a 
CHAR or VARCHAR type.
+   */
+  def getRawType(metadata: Metadata, dataType: DataType): Option[DataType] = {
+    def nested(dt: DataType): Option[DataType] = dt match {
+      case StructType(fields) =>
+        val rawFields = fields.map(f => 
getRawType(f.metadata).orElse(nested(f.dataType)))
+        if (rawFields.forall(_.isEmpty)) {
+          None
+        } else {
+          Some(StructType(fields.zip(rawFields).map { case (f, raw) =>
+            f.copy(dataType = raw.getOrElse(f.dataType), metadata = 
cleanMetadata(f.metadata))
+          }))
+        }
+      case ArrayType(et, containsNull) => nested(et).map(ArrayType(_, 
containsNull))
+      case _ => None
+    }
+    getRawType(metadata).orElse(nested(dataType))
+  }
+
+  /**
+   * [[widerCharRawType]] for each position of the outputs of the children of 
a set operation. A
+   * child can output a column at more than one position, and a reference to 
the column can't tell
+   * them apart, so the positions that share a column in any child get one raw 
type: the widest of
+   * all of them. Returns None for every position if the outputs have 
different lengths.
+   */
+  def widerCharRawTypes(childOutputs: Seq[Seq[Attribute]]): 
Seq[Option[DataType]] = {
+    val width = childOutputs.head.length
+    if (childOutputs.exists(_.length != width)) {
+      Seq.fill(width)(None)
+    } else {
+      val columns = childOutputs.transpose
+      // The first position of each group of positions that share a column.
+      val group = Array.tabulate(width)(identity)
+      def find(i: Int): Int = if (group(i) == i) i else find(group(i))
+      childOutputs.foreach { output =>
+        output.indices.groupBy(i => output(i).exprId).values.foreach { 
positions =>
+          positions.tail.foreach(i => group(find(i)) = find(positions.head))
+        }
+      }
+      val rawTypes = columns.indices.groupBy(find).map { case (first, 
positions) =>
+        first -> widerCharRawType(positions.flatMap(columns))
+      }
+      columns.indices.map(i => rawTypes(find(i)))
+    }
+  }
+
+  /**
+   * Narrows the CHAR columns and fields of the given expression, whose raw 
type is `fromType`, that
+   * are longer than those at the same places of `toType`, by removing the 
trailing spaces past the
+   * length of `toType`. Values with other characters past that length are 
kept, as read-side
+   * padding keeps them. A view stores the CHAR type of its columns, which can 
be shorter than the
+   * CHAR type of the same column of its query, such as for a view of a UNION 
created before the
+   * union had the widest length of its children. Returns None if no column or 
field is longer.
+   */
+  def narrowCharToLength(
+      expr: Expression,
+      fromType: DataType,
+      toType: DataType): Option[Expression] = {
+    // A rebuilt struct reads its fields only where the struct is not null, so 
a field that is not
+    // nullable stays so, and the narrowed value has the nullability of the 
given one.
+    def keepNotNull(e: Expression): Expression = e match {

Review Comment:
   **[P2] Design: keepNotNull pattern-matches nullSafeRebuiltStruct's private 
output shape instead of fixing nullability where the struct is built**
   
   The new `keepNotNull` in `narrowCharToLength` 
(CharVarcharUtils.scala:574-590) walks the result of 
`processStringForCharVarchar` after the fact. It looks for 
`CaseWhen(Seq((IsNull, Literal(null, _))), Some(struct))`, the exact shape that 
the private `nullSafeRebuiltStruct` emits (CharVarcharUtils.scala:358-360), 
rebuilds it, and wraps `GetStructField`s of NOT NULL fields in `KnownNotNull`. 
The nullability loss comes from the struct rebuild itself: 
`processStringForCharVarchar` builds `GetStructField(expr, i)` over a nullable 
`expr` (around line 321). The code base already keeps nullability at the 
construction site. `reconcileColumnType` (basicLogicalOperators.scala:141-145) 
reads fields as `GetStructField(KnownNotNull(col), index)` inside its 
`If(IsNull(col), null, struct)` guard, and Analyzer.scala:3949 wraps checked 
inputs in `KnownNotNull` the same way. Fix: give the StructType branch of 
`processStringForCharVarchar` (or `nullSafeRebuiltStruct`) an option to read 
fields through
  `KnownNotNull(expr)` when `expr.nullable`, and have `narrowCharToLength` turn 
it on. Then the post-pass and its copy of the CaseWhen shape can go.
   
   **Why it matters:** Two places now encode the internal shape of 
`nullSafeRebuiltStruct`, and only one of them builds it. That shape changed a 
month ago in SPARK-60090 (b4e88aa1f11, If replaced by CaseWhen). If it changes 
again, `keepNotNull` silently stops matching. The narrowed struct then gets 
nullable fields, and the `Cast` back to the view's or anchor's type in 
`ApplyCharTypePadding.narrowToLength` can't cast them to NOT NULL fields, so 
views and recursive CTEs over structs with NOT NULL CHAR fields break, and no 
compile error points at the cause. The two other callers of 
`nullSafeRebuiltStruct`, `padCharToTargetLength` (line 701) and the new 
set-operation padding through `padCharToWiderLength`, still drop NOT NULL on 
fields. Every caller that needs nullability kept will have to fix it a second 
time.



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