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


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/ApplyCharTypePadding.scala:
##########
@@ -88,10 +91,197 @@ object ApplyCharTypePadding extends Rule[LogicalPlan] {
           })
       }, skipCond = p => p.analyzed || p.isInstanceOf[DeleteFromTable], 
canGetOutput = _.resolved)
       padRowLevelConditions(padDeleteConditions(
-        ApplyCharTypePaddingHelper.paddingForStringComparison(newPlan, 
padCharCol = false)))
+        ApplyCharTypePaddingHelper.paddingForStringComparison(
+          padSetOperations(newPlan, padAllChildren = false), padCharCol = 
false)))
     } else {
       ApplyCharTypePaddingHelper.paddingForStringComparison(
-        plan, padCharCol = 
!conf.getConf(SQLConf.LEGACY_NO_CHAR_PADDING_IN_PREDICATE))
+        padSetOperations(plan, padAllChildren = true),
+        padCharCol = 
!conf.getConf(SQLConf.LEGACY_NO_CHAR_PADDING_IN_PREDICATE))
+    }
+  }
+
+  /**
+   * When the children of a Union, Intersect or Except have CHAR columns or 
fields of different
+   * lengths at the same position, its output has the widest length, see
+   * [[Union.mergeChildOutputs]], as the SQL standard does for set operations 
of CHAR(n) and
+   * CHAR(m). This pads the values of the shorter children to that length, so 
that they match the
+   * values of the other children and comparisons padded to it. Like read-side 
padding, it does not
+   * truncate longer values. Without read-side padding, the values of the 
widest children can be
+   * shorter too, so `padAllChildren` pads them as well. Then it narrows the 
values of recursive
+   * CTEs and views that have shorter lengths.
+   */
+  private def padSetOperations(plan: LogicalPlan, padAllChildren: Boolean): 
LogicalPlan = {
+    val newPlan = plan.transformUpWithNewOutput({
+      // An unresolved set operation, or one with children of different arity, 
fails in
+      // CheckAnalysis.
+      case op @ (_: Union | _: Intersect | _: Except) if op.resolved =>
+        val rawTypes = Union.widerCharRawTypes(op.children)
+        if (rawTypes.forall(_.isEmpty)) {
+          op -> Nil
+        } else {
+          val newOp = op.withNewChildren(op.children.map(padChild(_, rawTypes, 
padAllChildren)))
+          newOp -> op.output.zip(newOp.output)
+            .distinctBy { case (a, _) => a.exprId }
+            .filterNot { case (a, b) => a.exprId == b.exprId }
+        }
+    }, skipCond = p => p.analyzed || !p.containsAnyPattern(UNION, INTERSECT, 
EXCEPT),
+      canGetOutput = _.resolved)
+    narrowViewColumns(narrowRecursiveTerms(newPlan))
+  }
+
+  /**
+   * Pads the columns of a child of a set operation to the given raw types. A 
column is padded
+   * where it is produced if it can be, see [[padAtSource]], so that it keeps 
its expression ID,
+   * and otherwise in a Project over the child, which gives it a new one.
+   */
+  private def padChild(
+      child: LogicalPlan,
+      rawTypes: Seq[Option[DataType]],
+      padAllChildren: Boolean): LogicalPlan = {
+    // A column at more than one position has one raw type, see 
widerCharRawTypes.
+    val columns = child.output.zip(rawTypes).collect {
+      case (attr, Some(rawType)) => attr.exprId -> rawType
+    }.distinctBy(_._1)
+    val (newChild, paddedAtSource) = columns.foldLeft((child, 
Set.empty[ExprId])) {
+      case ((plan, padded), (exprId, rawType)) =>
+        padAtSource(plan, exprId, rawType, padAllChildren)
+          .map(newPlan => (newPlan, padded + exprId))
+          .getOrElse((plan, padded))
+    }
+    val paddedColumns = mutable.HashMap.empty[ExprId, NamedExpression]
+    val projectList = newChild.output.zip(rawTypes).map {
+      case (attr, Some(rawType)) if !paddedAtSource.contains(attr.exprId) =>
+        paddedColumns.getOrElseUpdate(attr.exprId,
+          CharVarcharUtils.padCharToWiderLength(attr, rawType, 
padAllChildren).map {
+            case (padded, paddedRawType) =>
+              Alias(padded, attr.name)(
+                qualifier = attr.qualifier,
+                explicitMetadata =
+                  Some(CharVarcharUtils.withRawType(attr.metadata, 
paddedRawType)))
+          }.getOrElse(attr))
+      case (attr, _) => attr
+    }
+    if (projectList == newChild.output) newChild else Project(projectList, 
newChild)
+  }
+
+  /**
+   * Pads the column of the plan with the given expression ID to the CHAR 
lengths of `rawType`
+   * where it is produced, in an alias of a Project under operators that pass 
the column through,
+   * and gives the references to it in them the new raw type. The column keeps 
its expression ID,
+   * so that a set operation keeps the output of its first child, which 
references to the columns
+   * of the child's DataFrame resolve to. Returns None if the column is 
produced elsewhere, or does
+   * not need padding.
+   */
+  private def padAtSource(
+      plan: LogicalPlan,
+      exprId: ExprId,
+      rawType: DataType,
+      alwaysPad: Boolean): Option[LogicalPlan] = {
+    def withNewChild(p: LogicalPlan, newChild: LogicalPlan): LogicalPlan = {
+      val metadata = newChild.output.find(_.exprId == exprId).get.metadata
+      p.withNewChildren(Seq(newChild)).transformExpressions {
+        case a: AttributeReference if a.exprId == exprId => 
a.withMetadata(metadata)
+      }
+    }
+    plan match {
+      case p @ Project(projectList, child) =>
+        projectList.find(_.exprId == exprId) match {
+          case Some(a: Alias) =>
+            CharVarcharUtils.getRawType(a.metadata).flatMap { aliasRawType =>
+              CharVarcharUtils.padCharToWiderLength(a.child, aliasRawType, 
rawType, alwaysPad)
+            }.map { case (padded, paddedRawType) =>
+              val newAlias = Alias(padded, a.name)(
+                a.exprId,
+                a.qualifier,
+                Some(CharVarcharUtils.withRawType(a.metadata, paddedRawType)),
+                a.nonInheritableMetadataKeys)
+              p.copy(projectList = projectList.map {
+                case ne if ne.exprId == exprId => newAlias
+                case ne => ne
+              })
+            }
+          case Some(_: Attribute) =>

Review Comment:
   **[P0] padAtSource widens a column below the Project/Filter/Sort operators 
that use it in the child**
   
   padAtSource finds where the column is produced, below every Project, Filter, 
Sort, SubqueryAlias and Limit it passes through, and widens the padding there 
(readSidePadding(c,3) becomes readSidePadding(c,5)). Every other expression in 
those operators then sees the widened value instead of the child's own CHAR(3) 
value. Comparisons are re-padded later from the updated metadata, but 
non-comparison expressions are not: `length`, `LIKE`, `substr`, `concat` and so 
on. A set operation should only change what its children output, not what is 
computed inside them. The PR's tests only filter above the union, never inside 
a child, so they don't catch this.
   
   **Failure scenario:** t3.c CHAR(3)='a', t5.c CHAR(5)='a'. `SELECT c, 
length(c) FROM t3 UNION ALL SELECT c, length(c) FROM t5` now returns length 5 
for the t3 row instead of 3. `SELECT c FROM t3 WHERE length(c) = 3 UNION ALL 
SELECT c FROM t5` and `SELECT c FROM t3 WHERE c LIKE 'a__' UNION ALL SELECT c 
FROM t5` drop the t3 row, which both returned before this PR.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/ApplyCharTypePadding.scala:
##########
@@ -88,10 +91,197 @@ object ApplyCharTypePadding extends Rule[LogicalPlan] {
           })
       }, skipCond = p => p.analyzed || p.isInstanceOf[DeleteFromTable], 
canGetOutput = _.resolved)
       padRowLevelConditions(padDeleteConditions(
-        ApplyCharTypePaddingHelper.paddingForStringComparison(newPlan, 
padCharCol = false)))
+        ApplyCharTypePaddingHelper.paddingForStringComparison(
+          padSetOperations(newPlan, padAllChildren = false), padCharCol = 
false)))
     } else {
       ApplyCharTypePaddingHelper.paddingForStringComparison(
-        plan, padCharCol = 
!conf.getConf(SQLConf.LEGACY_NO_CHAR_PADDING_IN_PREDICATE))
+        padSetOperations(plan, padAllChildren = true),
+        padCharCol = 
!conf.getConf(SQLConf.LEGACY_NO_CHAR_PADDING_IN_PREDICATE))
+    }
+  }
+
+  /**
+   * When the children of a Union, Intersect or Except have CHAR columns or 
fields of different
+   * lengths at the same position, its output has the widest length, see
+   * [[Union.mergeChildOutputs]], as the SQL standard does for set operations 
of CHAR(n) and
+   * CHAR(m). This pads the values of the shorter children to that length, so 
that they match the
+   * values of the other children and comparisons padded to it. Like read-side 
padding, it does not
+   * truncate longer values. Without read-side padding, the values of the 
widest children can be
+   * shorter too, so `padAllChildren` pads them as well. Then it narrows the 
values of recursive
+   * CTEs and views that have shorter lengths.
+   */
+  private def padSetOperations(plan: LogicalPlan, padAllChildren: Boolean): 
LogicalPlan = {
+    val newPlan = plan.transformUpWithNewOutput({
+      // An unresolved set operation, or one with children of different arity, 
fails in
+      // CheckAnalysis.
+      case op @ (_: Union | _: Intersect | _: Except) if op.resolved =>
+        val rawTypes = Union.widerCharRawTypes(op.children)
+        if (rawTypes.forall(_.isEmpty)) {
+          op -> Nil
+        } else {
+          val newOp = op.withNewChildren(op.children.map(padChild(_, rawTypes, 
padAllChildren)))
+          newOp -> op.output.zip(newOp.output)
+            .distinctBy { case (a, _) => a.exprId }
+            .filterNot { case (a, b) => a.exprId == b.exprId }
+        }
+    }, skipCond = p => p.analyzed || !p.containsAnyPattern(UNION, INTERSECT, 
EXCEPT),
+      canGetOutput = _.resolved)
+    narrowViewColumns(narrowRecursiveTerms(newPlan))
+  }
+
+  /**
+   * Pads the columns of a child of a set operation to the given raw types. A 
column is padded
+   * where it is produced if it can be, see [[padAtSource]], so that it keeps 
its expression ID,
+   * and otherwise in a Project over the child, which gives it a new one.
+   */
+  private def padChild(
+      child: LogicalPlan,
+      rawTypes: Seq[Option[DataType]],
+      padAllChildren: Boolean): LogicalPlan = {
+    // A column at more than one position has one raw type, see 
widerCharRawTypes.
+    val columns = child.output.zip(rawTypes).collect {
+      case (attr, Some(rawType)) => attr.exprId -> rawType
+    }.distinctBy(_._1)
+    val (newChild, paddedAtSource) = columns.foldLeft((child, 
Set.empty[ExprId])) {
+      case ((plan, padded), (exprId, rawType)) =>
+        padAtSource(plan, exprId, rawType, padAllChildren)
+          .map(newPlan => (newPlan, padded + exprId))
+          .getOrElse((plan, padded))
+    }
+    val paddedColumns = mutable.HashMap.empty[ExprId, NamedExpression]
+    val projectList = newChild.output.zip(rawTypes).map {
+      case (attr, Some(rawType)) if !paddedAtSource.contains(attr.exprId) =>
+        paddedColumns.getOrElseUpdate(attr.exprId,
+          CharVarcharUtils.padCharToWiderLength(attr, rawType, 
padAllChildren).map {
+            case (padded, paddedRawType) =>
+              Alias(padded, attr.name)(
+                qualifier = attr.qualifier,
+                explicitMetadata =
+                  Some(CharVarcharUtils.withRawType(attr.metadata, 
paddedRawType)))
+          }.getOrElse(attr))
+      case (attr, _) => attr
+    }
+    if (projectList == newChild.output) newChild else Project(projectList, 
newChild)
+  }
+
+  /**
+   * Pads the column of the plan with the given expression ID to the CHAR 
lengths of `rawType`
+   * where it is produced, in an alias of a Project under operators that pass 
the column through,
+   * and gives the references to it in them the new raw type. The column keeps 
its expression ID,
+   * so that a set operation keeps the output of its first child, which 
references to the columns
+   * of the child's DataFrame resolve to. Returns None if the column is 
produced elsewhere, or does
+   * not need padding.
+   */
+  private def padAtSource(
+      plan: LogicalPlan,
+      exprId: ExprId,
+      rawType: DataType,
+      alwaysPad: Boolean): Option[LogicalPlan] = {
+    def withNewChild(p: LogicalPlan, newChild: LogicalPlan): LogicalPlan = {
+      val metadata = newChild.output.find(_.exprId == exprId).get.metadata
+      p.withNewChildren(Seq(newChild)).transformExpressions {

Review Comment:
   **[P1] Re-padded column keeps its old raw type in OuterReferences inside 
subqueries**
   
   withNewChild updates the metadata of references to the widened column only 
in the operator's own expressions. transformExpressions does not go into 
subquery plans, and OuterReference is a leaf. A correlated subquery in a Filter 
of the union child still sees the outer column as CHAR(3), while its value is 
now 5-padded. withRawTypesOfInput doesn't fix this either, because the outer 
column is not in the subquery operator's input. The comparison in the subquery 
is then not padded (or padded to the wrong length) and misses.
   
   **Failure scenario:** t3 and t3b have c CHAR(3)='a'; t5.c is CHAR(5). In 
`SELECT c FROM t3 WHERE EXISTS (SELECT 1 FROM t3b WHERE t3b.c = t3.c) UNION ALL 
SELECT c FROM t5`, the outer t3.c becomes 'a    '. The subquery compares 
CHAR(3) with CHAR(3), so nothing is padded and 'a  ' = 'a    ' is false. EXISTS 
becomes false and t3's row is dropped; it was returned before this PR.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/basicLogicalOperators.scala:
##########
@@ -504,20 +527,64 @@ object Union {
     Union (left :: right :: Nil)
   }
 
-  // updating nullability to make all the children consistent
-  def mergeChildOutputs(childOutputs: Seq[Seq[Attribute]]): Seq[Attribute] = {
-    childOutputs.transpose.map { attrs =>
+  // updating nullability to make all the children consistent, and the raw 
types to
+  // `charRawTypes`, the raw types with the widest CHAR lengths of the 
children, see
+  // widerCharRawTypes. ApplyCharTypePadding pads the values of the shorter 
ones.
+  def mergeChildOutputs(

Review Comment:
   **[P1] Design: widened CHAR metadata is in the node's output, but padding is 
left to a later rule**
   
   mergeChildOutputs puts the widest CHAR length into the set operation's 
output metadata whenever the node is built. The values are only padded later, 
by ApplyCharTypePadding in sql/core. Any path that builds or keeps the node 
without that rule ends up with metadata that does not match its values. So far 
this needs separate special cases: readsRecursiveReference, withRawTypesOfInput 
for stale DataFrame references, view and recursive-term narrowing, and 
padAtSource to keep expression IDs. Some paths are still not covered: 
SequentialStreamingUnion, the early return for legacy charVarcharAsString, and 
the Project-over-union case in finding 5. WidenSetOperationTypes already shows 
another approach: it adds Projects to the children during analysis, so the 
node's output still comes from its first child.
   
   **Failure scenario:** In a sequential streaming union of CHAR(3) and CHAR(5) 
sources, the output reports CHAR(5) because UnionBase.computeOutput widens it, 
but no rule pads the children. `c = 'a'` then misses the first child's rows. 
`a.union(b).select(a("c"))` likewise keeps CHAR(3) over 5-padded values. Each 
such path needs another special case.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ApplyCharTypePaddingHelper.scala:
##########
@@ -68,16 +90,46 @@ object ApplyCharTypePaddingHelper {
   private[sql] def paddingForStringComparison(
       plan: LogicalPlan,
       padCharCol: Boolean): LogicalPlan = {
-    
plan.resolveOperatorsUpWithSubqueriesAndPruning(_.containsAnyPattern(BINARY_COMPARISON,
 IN)) {
+    plan.resolveOperatorsUpWithSubqueriesAndPruning(
+        _.containsAnyPattern(BINARY_COMPARISON, IN, IN_SUBQUERY)) {
       case operator =>
-        
operator.transformExpressionsUpWithPruning(_.containsAnyPattern(BINARY_COMPARISON,
 IN)) {
+        withRawTypesOfInput(operator).transformExpressionsUpWithPruning(
+            _.containsAnyPattern(BINARY_COMPARISON, IN, IN_SUBQUERY)) {
           case e if !e.childrenResolved => e
           case withChildrenResolved =>
             singleNodePaddingForStringComparison(withChildrenResolved, 
padCharCol)
         }
     }
   }
 
+  /**
+   * A reference resolved before its operator, such as a column of a 
DataFrame, keeps the raw type
+   * its column had then, which a set operation can widen since. This gives 
the CHAR references of
+   * the operator the raw types of the columns of its children, which 
comparisons pad to.
+   */
+  private def withRawTypesOfInput(operator: LogicalPlan): LogicalPlan = {

Review Comment:
   **[P1] Stale DataFrame references keep the old CHAR length in a Project over 
a set operation**
   
   Since padAtSource keeps the first child's expression IDs, a Classic `a("c")` 
reference (resolved through queryExecution.analyzed, so it has CHAR(3) 
metadata) now resolves against the union. The stale metadata is only fixed by 
withRawTypesOfInput, which runs inside paddingForStringComparison. That is 
pruned to operators whose subtree has a comparison, and only applies to the 
operator's own references. A Project over the union with no comparison keeps 
CHAR(3) and outputs it as its schema, while the values are 5-padded. A Filter 
added on top later takes the raw type from that Project's stale output.
   
   **Failure scenario:** t3.c CHAR(3)='a', t5.c CHAR(5)='a'; a = 
spark.table("t3"), b = spark.table("t5"). `a.union(b).select(a("c"))` reports c 
as CHAR(3) while every value is 'a    ', so CTAS and views get the wrong 
schema. `a.union(b).select(a("c")).filter($"c" === "a")` pads 'a' to 3 and 
returns 0 rows; before this PR it returned t3's row.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/ApplyCharTypePadding.scala:
##########
@@ -88,10 +91,197 @@ object ApplyCharTypePadding extends Rule[LogicalPlan] {
           })
       }, skipCond = p => p.analyzed || p.isInstanceOf[DeleteFromTable], 
canGetOutput = _.resolved)
       padRowLevelConditions(padDeleteConditions(
-        ApplyCharTypePaddingHelper.paddingForStringComparison(newPlan, 
padCharCol = false)))
+        ApplyCharTypePaddingHelper.paddingForStringComparison(
+          padSetOperations(newPlan, padAllChildren = false), padCharCol = 
false)))
     } else {
       ApplyCharTypePaddingHelper.paddingForStringComparison(
-        plan, padCharCol = 
!conf.getConf(SQLConf.LEGACY_NO_CHAR_PADDING_IN_PREDICATE))
+        padSetOperations(plan, padAllChildren = true),
+        padCharCol = 
!conf.getConf(SQLConf.LEGACY_NO_CHAR_PADDING_IN_PREDICATE))
+    }
+  }
+
+  /**
+   * When the children of a Union, Intersect or Except have CHAR columns or 
fields of different
+   * lengths at the same position, its output has the widest length, see
+   * [[Union.mergeChildOutputs]], as the SQL standard does for set operations 
of CHAR(n) and
+   * CHAR(m). This pads the values of the shorter children to that length, so 
that they match the
+   * values of the other children and comparisons padded to it. Like read-side 
padding, it does not
+   * truncate longer values. Without read-side padding, the values of the 
widest children can be
+   * shorter too, so `padAllChildren` pads them as well. Then it narrows the 
values of recursive
+   * CTEs and views that have shorter lengths.
+   */
+  private def padSetOperations(plan: LogicalPlan, padAllChildren: Boolean): 
LogicalPlan = {
+    val newPlan = plan.transformUpWithNewOutput({
+      // An unresolved set operation, or one with children of different arity, 
fails in
+      // CheckAnalysis.
+      case op @ (_: Union | _: Intersect | _: Except) if op.resolved =>
+        val rawTypes = Union.widerCharRawTypes(op.children)
+        if (rawTypes.forall(_.isEmpty)) {
+          op -> Nil
+        } else {
+          val newOp = op.withNewChildren(op.children.map(padChild(_, rawTypes, 
padAllChildren)))
+          newOp -> op.output.zip(newOp.output)
+            .distinctBy { case (a, _) => a.exprId }
+            .filterNot { case (a, b) => a.exprId == b.exprId }
+        }
+    }, skipCond = p => p.analyzed || !p.containsAnyPattern(UNION, INTERSECT, 
EXCEPT),
+      canGetOutput = _.resolved)
+    narrowViewColumns(narrowRecursiveTerms(newPlan))
+  }
+
+  /**
+   * Pads the columns of a child of a set operation to the given raw types. A 
column is padded
+   * where it is produced if it can be, see [[padAtSource]], so that it keeps 
its expression ID,
+   * and otherwise in a Project over the child, which gives it a new one.
+   */
+  private def padChild(
+      child: LogicalPlan,
+      rawTypes: Seq[Option[DataType]],
+      padAllChildren: Boolean): LogicalPlan = {
+    // A column at more than one position has one raw type, see 
widerCharRawTypes.
+    val columns = child.output.zip(rawTypes).collect {
+      case (attr, Some(rawType)) => attr.exprId -> rawType
+    }.distinctBy(_._1)
+    val (newChild, paddedAtSource) = columns.foldLeft((child, 
Set.empty[ExprId])) {
+      case ((plan, padded), (exprId, rawType)) =>
+        padAtSource(plan, exprId, rawType, padAllChildren)
+          .map(newPlan => (newPlan, padded + exprId))
+          .getOrElse((plan, padded))
+    }
+    val paddedColumns = mutable.HashMap.empty[ExprId, NamedExpression]
+    val projectList = newChild.output.zip(rawTypes).map {
+      case (attr, Some(rawType)) if !paddedAtSource.contains(attr.exprId) =>
+        paddedColumns.getOrElseUpdate(attr.exprId,
+          CharVarcharUtils.padCharToWiderLength(attr, rawType, 
padAllChildren).map {
+            case (padded, paddedRawType) =>
+              Alias(padded, attr.name)(
+                qualifier = attr.qualifier,
+                explicitMetadata =
+                  Some(CharVarcharUtils.withRawType(attr.metadata, 
paddedRawType)))
+          }.getOrElse(attr))
+      case (attr, _) => attr
+    }
+    if (projectList == newChild.output) newChild else Project(projectList, 
newChild)
+  }
+
+  /**
+   * Pads the column of the plan with the given expression ID to the CHAR 
lengths of `rawType`
+   * where it is produced, in an alias of a Project under operators that pass 
the column through,
+   * and gives the references to it in them the new raw type. The column keeps 
its expression ID,
+   * so that a set operation keeps the output of its first child, which 
references to the columns
+   * of the child's DataFrame resolve to. Returns None if the column is 
produced elsewhere, or does
+   * not need padding.
+   */
+  private def padAtSource(
+      plan: LogicalPlan,
+      exprId: ExprId,
+      rawType: DataType,
+      alwaysPad: Boolean): Option[LogicalPlan] = {
+    def withNewChild(p: LogicalPlan, newChild: LogicalPlan): LogicalPlan = {
+      val metadata = newChild.output.find(_.exprId == exprId).get.metadata
+      p.withNewChildren(Seq(newChild)).transformExpressions {
+        case a: AttributeReference if a.exprId == exprId => 
a.withMetadata(metadata)
+      }
+    }
+    plan match {
+      case p @ Project(projectList, child) =>
+        projectList.find(_.exprId == exprId) match {
+          case Some(a: Alias) =>
+            CharVarcharUtils.getRawType(a.metadata).flatMap { aliasRawType =>
+              CharVarcharUtils.padCharToWiderLength(a.child, aliasRawType, 
rawType, alwaysPad)
+            }.map { case (padded, paddedRawType) =>
+              val newAlias = Alias(padded, a.name)(
+                a.exprId,
+                a.qualifier,
+                Some(CharVarcharUtils.withRawType(a.metadata, paddedRawType)),
+                a.nonInheritableMetadataKeys)
+              p.copy(projectList = projectList.map {
+                case ne if ne.exprId == exprId => newAlias
+                case ne => ne
+              })
+            }
+          case Some(_: Attribute) =>
+            padAtSource(child, exprId, rawType, alwaysPad).map(withNewChild(p, 
_))
+          case _ => None
+        }
+      case _: SubqueryAlias | _: Filter | _: Sort | _: LocalLimit | _: 
GlobalLimit =>
+        padAtSource(plan.children.head, exprId, rawType, 
alwaysPad).map(withNewChild(plan, _))
+      case _ => None
+    }
+  }
+
+  /**
+   * The columns of a recursive CTE have the CHAR lengths of its anchor. This 
narrows values of the
+   * recursive term with longer CHAR lengths, such as those of a set operation 
in it, to them, as
+   * [[narrowViewColumns]] does for a view.
+   */
+  private def narrowRecursiveTerms(plan: LogicalPlan): LogicalPlan = {
+    plan.resolveOperatorsUp {
+      case loop: UnionLoop if loop.resolved =>
+        val recursion = loop.recursion
+        val projectList = recursion.output.zip(loop.anchor.output).map { case 
(attr, anchorAttr) =>
+          (for {
+            rawType <- CharVarcharUtils.getRawType(attr.metadata, 
attr.dataType)
+            anchorType <- CharVarcharUtils.getRawType(anchorAttr.metadata, 
anchorAttr.dataType)
+            narrowed <- narrowToLength(attr, rawType, anchorType)
+          } yield Alias(narrowed, attr.name)(
+            qualifier = attr.qualifier,
+            explicitMetadata = 
Some(CharVarcharUtils.withRawType(attr.metadata, anchorType))
+          )).getOrElse(attr)
+        }
+        if (projectList == recursion.output) {
+          loop
+        } else {
+          loop.copy(recursion = Project(projectList, recursion))
+        }
+    }
+  }
+
+  // The value narrowed to the CHAR lengths of `toType`, with the data type of 
the value. A rebuilt
+  // struct loses the metadata of its fields, which holds their raw types.
+  private def narrowToLength(
+      expr: Expression,
+      fromType: DataType,
+      toType: DataType): Option[Expression] = {
+    CharVarcharUtils.narrowCharToLength(expr, fromType, toType).map { narrowed 
=>
+      if (narrowed.dataType == expr.dataType) {
+        narrowed
+      } else {
+        Cast(narrowed, expr.dataType, Some(conf.sessionLocalTimeZone))

Review Comment:
   **[P1] Narrowing a nullable struct with a NOT NULL field adds a Cast that 
fails analysis**
   
   narrowCharToLength rebuilds a struct with GetStructField, whose nullability 
is child.nullable || field.nullable. For a nullable struct, a NOT NULL field 
becomes nullable in the rebuilt type. narrowToLength then adds Cast(narrowed, 
expr.dataType) back to the original type. Cast.canCast rejects casting a 
nullable struct field to a NOT NULL one, so the query fails CheckAnalysis.
   
   **Failure scenario:** A view (or recursive CTE) with a nullable column of 
type STRUCT<k INT NOT NULL, c CHAR(3)> whose query now outputs c as CHAR(5), 
for example an existing view over a union of CHAR(3) and CHAR(5) structs. 
narrowViewColumns adds Cast(struct<k:int,c:string>, struct<k:int not 
null,c:string>), and querying the view throws a DATATYPE_MISMATCH cast error 
instead of returning rows.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ApplyCharTypePaddingHelper.scala:
##########
@@ -68,16 +90,46 @@ object ApplyCharTypePaddingHelper {
   private[sql] def paddingForStringComparison(
       plan: LogicalPlan,
       padCharCol: Boolean): LogicalPlan = {
-    
plan.resolveOperatorsUpWithSubqueriesAndPruning(_.containsAnyPattern(BINARY_COMPARISON,
 IN)) {
+    plan.resolveOperatorsUpWithSubqueriesAndPruning(
+        _.containsAnyPattern(BINARY_COMPARISON, IN, IN_SUBQUERY)) {
       case operator =>
-        
operator.transformExpressionsUpWithPruning(_.containsAnyPattern(BINARY_COMPARISON,
 IN)) {
+        withRawTypesOfInput(operator).transformExpressionsUpWithPruning(
+            _.containsAnyPattern(BINARY_COMPARISON, IN, IN_SUBQUERY)) {
           case e if !e.childrenResolved => e
           case withChildrenResolved =>
             singleNodePaddingForStringComparison(withChildrenResolved, 
padCharCol)
         }
     }
   }
 
+  /**
+   * A reference resolved before its operator, such as a column of a 
DataFrame, keeps the raw type
+   * its column had then, which a set operation can widen since. This gives 
the CHAR references of
+   * the operator the raw types of the columns of its children, which 
comparisons pad to.
+   */
+  private def withRawTypesOfInput(operator: LogicalPlan): LogicalPlan = {

Review Comment:
   **[P2] Design: Raw-type refresh of stale references is implemented twice, 
and neither covers operator outputs**
   
   This commit adds two separate ways to re-sync the CHAR raw-type metadata of 
a reference with the child output that has the same exprId:
   (1) `padAtSource.withNewChild` (ApplyCharTypePadding.scala:180-185) copies 
the child attribute's metadata into the references of the pass-through 
operators it walks (Project, SubqueryAlias, Filter, Sort, limits).
   (2) `withRawTypesOfInput` (ApplyCharTypePaddingHelper.scala:110-131) 
rebuilds the raw-type key for each CHAR AttributeReference of an operator from 
`operator.children.flatMap(_.output)`. It also builds the metadata by hand with 
`MetadataBuilder...putString(CHAR_VARCHAR_TYPE_STRING_METADATA_KEY, ...)` 
instead of using the `CharVarcharUtils.withRawType` helper added in the same PR 
(CharVarcharUtils.scala:608).
   
   Approach (2) only runs inside `paddingForStringComparison`, whose 
`resolveOperatorsUpWithSubqueriesAndPruning(_.containsAnyPattern(BINARY_COMPARISON,
 IN, IN_SUBQUERY))` visits an operator only when its subtree contains a 
comparison. So whether an operator's output gets the widened raw type depends 
on whether there is a comparison below it.
   
   Example: `a.union(b).select(a("c"))`, with `a` = t3 CHAR(3) and `b` = t5 
CHAR(5). The Project over the analyzed Union holds `c#X` with the CHAR(3) 
metadata that `a("c")` was resolved with. It has no comparison, so it is never 
refreshed, and its output says CHAR(3) while the values are padded to 5. A 
later `.filter($"c" === "a")` takes CHAR(3) from that Project: 
`withRawTypesOfInput` sees the same stale type in the child output, the literal 
is padded to 3, and the row is missed. The test `a.union(b).filter(a("c") === 
"a")` passes only because its Filter sits directly on the Union.
   
   The codebase already handles this class of problem, a Dataset-resolved 
reference whose attribute properties changed below it, with one plan-wide step: 
UpdateAttributeNullability.scala:27-60 refreshes every resolved non-leaf 
operator from its children's outputs by exprId. Suggested change: drop both 
ad-hoc copies and run one refresh of that shape over all resolved operators in 
ApplyCharTypePadding, right after `padSetOperations`, so that outputs above a 
widened set operation also carry the new raw type. Use 
`CharVarcharUtils.withRawType` (or copy the child's metadata) instead of 
hand-building the key.
   
   **Why it matters:** The stale-metadata fix lives in two places with 
different coverage. Every new consumer of a reference's raw type (projections, 
views, writes, the next padding step) needs a third patch. The gap already 
gives wrong results: comparisons on a DataFrame that projects a column above a 
set operation of CHAR columns of different lengths miss matching rows.



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