shivadarshan-devadiga commented on code in PR #60756:
URL: https://github.com/apache/spark/pull/60756#discussion_r4651417336


##########
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:
   Fixed by the rework. Nothing inside a child is changed any more, so the 
correlated subquery compares the t3 column with its own CHAR(3) value. Your 
`EXISTS (SELECT 1 FROM t3b WHERE t3b.c = t3.c)` query is in the set-operations 
test and keeps the t3 row.
   



##########
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:
   With the padding during analysis, the set operation's output is the padded 
column, so there's no reference that keeps the old length. A DataFrame of the 
union, and a Project over it, have CHAR(5), and a filter on it matches both 
rows (in the set-operations test). As I wrote above, `a("c")` of the shorter 
first child no longer resolves against the union, as with type widening.



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