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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/basicLogicalOperators.scala:
##########
@@ -504,16 +504,26 @@ object Union {
     Union (left :: right :: Nil)
   }
 
-  // updating nullability to make all the children consistent
-  def mergeChildOutputs(childOutputs: Seq[Seq[Attribute]]): Seq[Attribute] = {
+  // updating nullability to make all the children consistent, and the CHAR 
lengths of the raw
+  // types if the children have CHAR columns of different lengths, see
+  // CharVarcharUtils.widerCharRawType. ApplyCharTypePadding pads the values 
of the shorter ones.
+  def mergeChildOutputs(childOutputs: Seq[Seq[Attribute]]): Seq[Attribute] =
+    mergeChildOutputs(childOutputs, widenCharLengths = true)
+
+  private[logical] def mergeChildOutputs(
+      childOutputs: Seq[Seq[Attribute]],
+      widenCharLengths: Boolean): Seq[Attribute] = {
     childOutputs.transpose.map { attrs =>
       val firstAttr = attrs.head
       val nullable = attrs.exists(_.nullable)
       val newDt = attrs.map(_.dataType).reduce(StructType.unionLikeMerge)
-      if (firstAttr.dataType == newDt) {
+      val widerRawType = if (widenCharLengths) 
CharVarcharUtils.widerCharRawType(attrs) else None
+      val metadata = 
widerRawType.map(CharVarcharUtils.withRawType(firstAttr.metadata, _))

Review Comment:
   **[P0] Persisted views keep their stored CHAR(n) schema while the union 
values are now padded wider**
   
   A view stores its schema with CharVarcharUtils.getRawSchema (views.scala). 
When read, SessionCatalog.castColToType applies the stored field metadata as 
explicitMetadata, so the stored type wins (see the existing TODO there). A view 
created before this change over a union whose first child is the shorter CHAR 
keeps CHAR(3) in its stored schema. After the upgrade, the re-analyzed body 
pads every value to CHAR(5). Literal comparisons against the view column are 
then padded to 3 and never match the 5-wide values.
   
   **Failure scenario:** On an older version: `CREATE VIEW v AS SELECT c FROM 
t3 UNION ALL SELECT c FROM t5` (stored type CHAR(3)). After upgrading, `SELECT 
* FROM v WHERE c = 'a'` pads the literal to 'a  ' while every value is 'a    ', 
so it returns 0 rows where it used to return the t3 row. DESCRIBE still reports 
CHAR(3), and V2 writes from the view into a CHAR(3) column count as 
type-compatible and skip the length check.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/CharVarcharUtils.scala:
##########
@@ -426,6 +426,65 @@ object CharVarcharUtils extends Logging with 
SparkCharVarcharUtils {
     }
   }
 
+  /**
+   * 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 {
+      rawTypeStrings.map(s => 
Option(CatalystSqlParser.parseDataType(s.get))).reduce {
+        (left, right) => for (l <- left; r <- right; wider <- widerCharType(l, 
r)) yield wider
+      }
+    }
+  }
+
+  /**
+   * 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.
+   */
+  def padCharToWiderLength(attr: Attribute, rawType: DataType): 
Option[(Expression, DataType)] = {
+    getRawType(attr.metadata).flatMap { attrRawType =>
+      widerCharType(attrRawType, rawType).filter(_ != attrRawType).map { wider 
=>
+        val padded = processStringForCharVarchar(
+          attr, wider, charFuncName = Some(READ_SIDE_PADDING), varcharFuncName 
= None)
+        (padded, wider)
+      }
+    }
+  }
+
+  /** The metadata with the given raw type, for a value padded to the CHAR 
lengths of that type. */
+  def withRawType(metadata: Metadata, rawType: DataType): Metadata = {
+    new MetadataBuilder()
+      .withMetadata(metadata)
+      .putString(CHAR_VARCHAR_TYPE_STRING_METADATA_KEY, rawType.catalogString)
+      .build()
+  }
+
+  // Like typeWithWiderCharLength, but keeps the field names of type1, and 
None for types that are
+  // not both CHAR types, or structs and arrays of them, with the same shape.
+  private def widerCharType(type1: DataType, type2: DataType): 
Option[DataType] = {
+    (type1, type2) match {
+      case (c1: CharType, c2: CharType) if c1.collation == c2.collation =>

Review Comment:
   **[P1] Collation check treats implicit and explicit UTF8_BINARY as 
incompatible**
   
   CharType.collation is an Option[Int], where None means the default 
UTF8_BINARY. Comparing `c1.collation == c2.collation` makes CHAR(3) (None) and 
CHAR(5) COLLATE UTF8_BINARY (Some(0)) look incompatible, although their 
effective collation, collationId, is the same. widerCharType then returns None 
and the fix doesn't apply. Comparing collationId, or treating None as 
UTF8_BINARY, would fix it.
   
   **Failure scenario:** Union of `c CHAR(3)` and `c CHAR(5) COLLATE 
UTF8_BINARY`: widerCharRawType returns None, the output keeps CHAR(3) from the 
first child, and `WHERE c = 'a'` over the union still drops the CHAR(5) rows, 
or the CHAR(3) rows if the children are swapped.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/ApplyCharTypePadding.scala:
##########
@@ -88,13 +88,47 @@ object ApplyCharTypePadding extends Rule[LogicalPlan] {
           })
       }, skipCond = p => p.analyzed || p.isInstanceOf[DeleteFromTable], 
canGetOutput = _.resolved)
       padRowLevelConditions(padDeleteConditions(
-        ApplyCharTypePaddingHelper.paddingForStringComparison(newPlan, 
padCharCol = false)))
+        ApplyCharTypePaddingHelper.paddingForStringComparison(
+          padUnionChildren(newPlan), padCharCol = false)))
     } else {
       ApplyCharTypePaddingHelper.paddingForStringComparison(
-        plan, padCharCol = 
!conf.getConf(SQLConf.LEGACY_NO_CHAR_PADDING_IN_PREDICATE))
+        padUnionChildren(plan),
+        padCharCol = 
!conf.getConf(SQLConf.LEGACY_NO_CHAR_PADDING_IN_PREDICATE))
     }
   }
 
+  /**
+   * When the children of a Union have CHAR columns or fields of different 
lengths at the same
+   * position, the output of the Union has the widest length, see 
[[Union.mergeChildOutputs]], as
+   * the SQL standard does for the union of CHAR(n) and CHAR(m). This pads the 
values of the
+   * shorter children to that length, so that comparisons padded to it match 
them.
+   */
+  private def padUnionChildren(plan: LogicalPlan): LogicalPlan = {
+    plan.transformUpWithNewOutput({
+      // An unresolved Union, or one with children of different arity, fails 
in CheckAnalysis.
+      case u: Union if u.resolved =>
+        val rawTypes = 
u.children.map(_.output).transpose.map(CharVarcharUtils.widerCharRawType)
+        if (rawTypes.forall(_.isEmpty)) {
+          u -> Nil
+        } else {
+          val newChildren = u.children.map { child =>
+            val projectList = child.output.zip(rawTypes).map {
+              case (attr, Some(rawType)) =>
+                CharVarcharUtils.padCharToWiderLength(attr, rawType).map {

Review Comment:
   **[P0] Padding shorter union children breaks IN-subquery/INTERSECT/EXCEPT 
against the shorter CHAR column**
   
   padUnionChildren pads the values of the shorter union children to the widest 
CHAR length. Comparisons that 
ApplyCharTypePaddingHelper.paddingForStringComparison never pads still compare 
these values with the original, shorter column. That helper only handles 
BinaryComparison and In with literal or attribute lists, so 
InSubquery/ListQuery (turned into a semi-join by RewritePredicateSubquery), 
INTERSECT and EXCEPT get no padding. Before this change, values from a child 
with the same CHAR length as the outer column kept that length and matched. Now 
every value has the widest length, so those matches are lost. This is a 
wrong-result regression for queries that used to work.
   
   **Failure scenario:** t3 CHAR(3)='a', t5 CHAR(5)='a'. `SELECT id FROM t3 
WHERE c IN (SELECT c FROM t3 UNION ALL SELECT c FROM t5)` used to return 1. Now 
every subquery value is 'a    ' while t3.c is 'a  ', and the unpadded semi-join 
returns no rows. `SELECT c FROM t3 INTERSECT (<same union>)` goes from 'a  ' to 
empty, and the matching EXCEPT goes from empty to 'a  '.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/ApplyCharTypePadding.scala:
##########
@@ -88,13 +88,47 @@ object ApplyCharTypePadding extends Rule[LogicalPlan] {
           })
       }, skipCond = p => p.analyzed || p.isInstanceOf[DeleteFromTable], 
canGetOutput = _.resolved)
       padRowLevelConditions(padDeleteConditions(
-        ApplyCharTypePaddingHelper.paddingForStringComparison(newPlan, 
padCharCol = false)))
+        ApplyCharTypePaddingHelper.paddingForStringComparison(
+          padUnionChildren(newPlan), padCharCol = false)))
     } else {
       ApplyCharTypePaddingHelper.paddingForStringComparison(
-        plan, padCharCol = 
!conf.getConf(SQLConf.LEGACY_NO_CHAR_PADDING_IN_PREDICATE))
+        padUnionChildren(plan),
+        padCharCol = 
!conf.getConf(SQLConf.LEGACY_NO_CHAR_PADDING_IN_PREDICATE))
     }
   }
 
+  /**
+   * When the children of a Union have CHAR columns or fields of different 
lengths at the same
+   * position, the output of the Union has the widest length, see 
[[Union.mergeChildOutputs]], as
+   * the SQL standard does for the union of CHAR(n) and CHAR(m). This pads the 
values of the
+   * shorter children to that length, so that comparisons padded to it match 
them.
+   */
+  private def padUnionChildren(plan: LogicalPlan): LogicalPlan = {
+    plan.transformUpWithNewOutput({
+      // An unresolved Union, or one with children of different arity, fails 
in CheckAnalysis.
+      case u: Union if u.resolved =>
+        val rawTypes = 
u.children.map(_.output).transpose.map(CharVarcharUtils.widerCharRawType)
+        if (rawTypes.forall(_.isEmpty)) {
+          u -> Nil
+        } else {
+          val newChildren = u.children.map { child =>
+            val projectList = child.output.zip(rawTypes).map {
+              case (attr, Some(rawType)) =>
+                CharVarcharUtils.padCharToWiderLength(attr, rawType).map {
+                  case (padded, paddedRawType) =>
+                    Alias(padded, attr.name)(explicitMetadata =

Review Comment:
   **[P2] Padding Alias drops the first child's qualifier from the Union 
output**
   
   The padding Alias is built without `qualifier = attr.qualifier`, so its 
output attribute has an empty qualifier. When the first child is padded, the 
Union output loses the table qualifier that mergeChildOutputs used to carry 
over from the first child. SQL queries resolve qualified references before this 
post-hoc rule runs, so they are unaffected. DataFrame code that resolves a 
qualified name against an already analyzed union breaks.
   
   **Failure scenario:** 
`spark.table("t3").union(spark.table("t5")).select("t3.c")` (or 
`.orderBy("t3.c")`) used to resolve through the qualified first-child 
attribute. After the padding, the output attribute has no qualifier and 
resolution fails with UNRESOLVED_COLUMN.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/ApplyCharTypePadding.scala:
##########
@@ -88,13 +88,47 @@ object ApplyCharTypePadding extends Rule[LogicalPlan] {
           })
       }, skipCond = p => p.analyzed || p.isInstanceOf[DeleteFromTable], 
canGetOutput = _.resolved)
       padRowLevelConditions(padDeleteConditions(
-        ApplyCharTypePaddingHelper.paddingForStringComparison(newPlan, 
padCharCol = false)))
+        ApplyCharTypePaddingHelper.paddingForStringComparison(
+          padUnionChildren(newPlan), padCharCol = false)))
     } else {
       ApplyCharTypePaddingHelper.paddingForStringComparison(
-        plan, padCharCol = 
!conf.getConf(SQLConf.LEGACY_NO_CHAR_PADDING_IN_PREDICATE))
+        padUnionChildren(plan),
+        padCharCol = 
!conf.getConf(SQLConf.LEGACY_NO_CHAR_PADDING_IN_PREDICATE))
     }
   }
 
+  /**
+   * When the children of a Union have CHAR columns or fields of different 
lengths at the same
+   * position, the output of the Union has the widest length, see 
[[Union.mergeChildOutputs]], as
+   * the SQL standard does for the union of CHAR(n) and CHAR(m). This pads the 
values of the
+   * shorter children to that length, so that comparisons padded to it match 
them.
+   */
+  private def padUnionChildren(plan: LogicalPlan): LogicalPlan = {
+    plan.transformUpWithNewOutput({
+      // An unresolved Union, or one with children of different arity, fails 
in CheckAnalysis.
+      case u: Union if u.resolved =>
+        val rawTypes = 
u.children.map(_.output).transpose.map(CharVarcharUtils.widerCharRawType)
+        if (rawTypes.forall(_.isEmpty)) {
+          u -> Nil
+        } else {
+          val newChildren = u.children.map { child =>
+            val projectList = child.output.zip(rawTypes).map {
+              case (attr, Some(rawType)) =>
+                CharVarcharUtils.padCharToWiderLength(attr, rawType).map {
+                  case (padded, paddedRawType) =>
+                    Alias(padded, attr.name)(explicitMetadata =

Review Comment:
   **[P1] Padding the first child gives the Union output new exprIds, breaking 
Classic DataFrame references**
   
   When the first child is the shorter one, it is wrapped in a Project whose 
Alias gets a new exprId. Union.output comes from the first child, so it no 
longer keeps the left child's attribute ids, which mergeChildOutputs used to 
preserve. In Classic, `a.union(b)` is analyzed eagerly. A later 
`.select(a("c"))` holds the old attribute, which is no longer in the union's 
output. test_resolve_after_union in python/pyspark/sql/tests/test_column.py 
documents that Classic relies on this id preservation.
   
   **Failure scenario:** `val a = spark.table("t3"); val b = spark.table("t5"); 
a.union(b).select(a("c"))` (or `.where(a("c") === "a")`) used to work. The 
union output is now c#new, so c#<old> is missing and analysis fails with 
MISSING_ATTRIBUTES. The same code with t5 as the first child still works, so 
the failure depends on child order.



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