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


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/ApplyCharTypePadding.scala:
##########
@@ -88,10 +88,94 @@ 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 
columns of views that
+   * store a shorter length.
+   */
+  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 = 
op.children.map(_.output).transpose.map(CharVarcharUtils.widerCharRawType)
+        if (rawTypes.forall(_.isEmpty)) {
+          op -> Nil
+        } else {
+          val newChildren = op.children.map { child =>
+            val projectList = child.output.zip(rawTypes).map {
+              case (attr, Some(rawType)) =>
+                CharVarcharUtils.padCharToWiderLength(attr, rawType, 
padAllChildren).map {
+                  case (padded, paddedRawType) =>
+                    Alias(padded, attr.name)(

Review Comment:
   **[P1] [P1] Handle duplicate attributes before padding set-operation 
children**
   
   INTERSECT and EXCEPT permit repeated attributes within a child's output; 
DeduplicateRelations only separates their branches. Creating a fresh Alias for 
each occurrence makes the mapping at line 134 map one old exprId to two new 
IDs. An enclosing Project then triggers the `Found duplicate rewrite 
attributes` assertion in QueryPlan.transformUpWithNewOutput. Handle repeated 
outputs so their attribute mappings remain unambiguous.
   
   **Failure scenario:** With t3(c CHAR(3)) and t5(c CHAR(5)) each containing 
'a', `SELECT * FROM (SELECT c, c FROM t3 INTERSECT SELECT c, c FROM t5) u` 
crashes during analysis instead of returning one padded row. The EXCEPT variant 
also crashes.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ApplyCharTypePaddingHelper.scala:
##########
@@ -158,9 +180,61 @@ object ApplyCharTypePaddingHelper {
           i.copy(value = newChildren.head, list = newChildren.tail)
         }
 
+      // Like the cases above, for a scalar subquery of a CHAR column compared 
with a string
+      // literal, a column, or another scalar subquery.
+      case b @ BinaryComparison(e @ CharScalarSubquery(metadata), lit) if 
lit.foldable =>
+        padAttrLitCmp(e, metadata, padCharCol, 
lit).map(b.withNewChildren).getOrElse(b)
+
+      case b @ BinaryComparison(lit, e @ CharScalarSubquery(metadata)) if 
lit.foldable =>
+        padAttrLitCmp(e, metadata, padCharCol, lit)
+          .map(newChildren => b.withNewChildren(newChildren.reverse))
+          .getOrElse(b)
+
+      case b @ BinaryComparison(e1 @ CharOperand(m1), e2 @ CharOperand(m2))
+          if e1.isInstanceOf[ScalarSubquery] || 
e2.isInstanceOf[ScalarSubquery] =>
+        b.withNewChildren(CharVarcharUtils.addPaddingInStringComparison(
+          Seq(e1, e2), Seq(m1, m2).map(CharVarcharUtils.getRawType), 
padCharCol))
+
+      case i: InSubquery if i.resolved => padInSubquery(i, padCharCol)
+
       case other => other
     }
 
+  /**
+   * Pads each CHAR value or string literal of an IN subquery and the CHAR 
column of the subquery
+   * it is compared with, as a comparison with a column pads them. The columns 
are padded in a
+   * Project over the subquery, without the raw type, so that they are padded 
only once.
+   */
+  private def padInSubquery(i: InSubquery, padCharCol: Boolean): InSubquery = {
+    val padded = i.values.zip(i.query.childOutputs).map {
+      case (value @ CharOperand(metadata), col) =>
+        val Seq(newValue, newCol) = 
CharVarcharUtils.addPaddingInStringComparison(

Review Comment:
   **[P1] [P1] Preserve overlength values when padding subquery operands**
   
   The newly invoked addPaddingInStringComparison delegates to 
padCharToTargetLength, which generates StringRPad for the shorter declared CHAR 
type. Unlike readSidePadding, UTF8String.rpad truncates inputs exceeding its 
target length. Consequently, identical overlength values preserved by their 
scans become unequal before RewritePredicateSubquery constructs its semi-join. 
The new scalar-subquery comparison path shares this problem. Use non-truncating 
padding for these operands.
   
   **Failure scenario:** Create external Parquet tables t3(c CHAR(3)) and t5(c 
CHAR(5)) over STRING storage containing 'abcdef', using default settings. 
`SELECT c FROM t3 WHERE c IN (SELECT c FROM t5)` previously returned 'abcdef'; 
it now returns nothing because the comparison becomes 'abcde' = 'abcdef'.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/CharVarcharUtils.scala:
##########
@@ -409,23 +412,168 @@ 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.
+   */
+  def addPaddingInStringComparison(
+      exprs: Seq[Expression],
+      rawTypes: Seq[Option[DataType]],
+      alwaysPad: Boolean): 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).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 {
+      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, 
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))
+  }
+
+  /** The metadata of the first attribute, with the raw type of 
[[widerCharRawType]] if any. */
+  def widerCharMetadata(attrs: Seq[Attribute]): Metadata = {
+    widerCharRawType(attrs).map(withRawType(attrs.head.metadata, 
_)).getOrElse(attrs.head.metadata)
+  }
+
+  /**
+   * 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] = {
+    narrowerCharType(fromType, toType).map { narrower =>
+      processStringForCharVarchar(
+        expr, narrower, charFuncName = Some(CHAR_TYPE_NARROWING), 
varcharFuncName = None)
+    }.filterNot(_.fastEquals(expr))
+  }
+
+  // The CHAR types of toType where fromType is longer, and STRING elsewhere, 
with the field names
+  // of toType. None if they are not both CHAR types, or structs and arrays of 
them, of one shape.
+  // Fields of other types must be the same.
+  private def narrowerCharType(fromType: DataType, toType: DataType): 
Option[DataType] = {
+    (fromType, toType) match {
+      case (c1: CharType, c2: CharType) if c1.collationId == c2.collationId =>
+        Some(if (c1.length > c2.length) c2 else c2.toStringType)
+      case (StructType(fields1), StructType(fields2)) if fields1.length == 
fields2.length =>
+        val narrowerFields = fields1.zip(fields2).map { case (from, to) =>
+          narrowerCharType(from.dataType, to.dataType).map(dt => 
to.copy(dataType = dt))
+        }
+        if (narrowerFields.forall(_.isDefined)) {
+          Some(StructType(narrowerFields.map(_.get)))
+        } else {
+          None
+        }
+      case (ArrayType(et1, _), ArrayType(et2, containsNull)) =>
+        narrowerCharType(et1, et2).map(ArrayType(_, containsNull))
+      // other fields of a struct, such as an INT next to a CHAR
+      case _ if fromType == toType && !hasCharVarchar(toType) => Some(toType)

Review Comment:
   **[P1] [P1] Preserve unchanged VARCHAR fields during view narrowing**
   
   This fallback rejects identical VARCHAR types because hasCharVarchar returns 
true for them. When getRawType reconstructs a persisted struct containing CHAR 
and VARCHAR fields, the unchanged VARCHAR field therefore makes 
narrowerFields.forall fail, skipping narrowing of the entire struct. 
SessionCatalog.castColToType restores the stored metadata while its physical 
STRING-to-STRING cast preserves the widened values. Extracted CHAR fields 
consequently advertise the old length and lose comparison matches. Preserve 
identical VARCHAR fields while narrowing their CHAR siblings.
   
   **Failure scenario:** Before upgrading, create t3(c CHAR(3), v VARCHAR(10)) 
and t5(c CHAR(5), v VARCHAR(10)), each containing ('a','x'), and persist 
`CREATE VIEW old_v AS SELECT named_struct('c', c, 'v', v) AS s FROM (SELECT c, 
v FROM t3 UNION ALL SELECT c, v FROM t5) u`. After upgrading, `SELECT c FROM 
(SELECT s.c AS c FROM old_v) q WHERE c = 'a'` returns no rows, losing the 
previously matching t3 row.



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