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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ApplyCharTypePaddingHelper.scala:
##########
@@ -158,33 +189,130 @@ 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.
+      // Unlike the cases above, these don't truncate values longer than their 
CHAR length.
+      // A comparison of types that don't match is left to CheckAnalysis.
+      case b @ BinaryComparison(e @ CharScalarSubquery(metadata), lit)
+          if b.resolved && canEvaluate(lit) =>
+        padAttrLitCmp(e, metadata, padCharCol, lit, truncate = false)
+          .map(b.withNewChildren)
+          .getOrElse(b)
+
+      case b @ BinaryComparison(lit, e @ CharScalarSubquery(metadata))
+          if b.resolved && canEvaluate(lit) =>
+        padAttrLitCmp(e, metadata, padCharCol, lit, truncate = false)
+          .map(newChildren => b.withNewChildren(newChildren.reverse))
+          .getOrElse(b)
+
+      case b @ BinaryComparison(e1 @ CharOperand(m1), e2 @ CharOperand(m2))
+          if b.resolved && (e1.isInstanceOf[ScalarSubquery] || 
e2.isInstanceOf[ScalarSubquery]) =>
+        b.withNewChildren(CharVarcharUtils.addPaddingInStringComparison(
+          Seq(e1, e2), Seq(m1, m2).map(CharVarcharUtils.getRawType), 
padCharCol, truncate = false))
+
+      case i @ In(e @ CharScalarSubquery(metadata), list)
+          if i.resolved && list.forall(canEvaluate) =>
+        CharVarcharUtils.getRawType(metadata).collect {
+          case c: CharType => padInList(i, e, c, padCharCol)
+        }.getOrElse(i)
+
+      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, but without 
truncating values
+   * longer than their CHAR length, as read-side padding keeps 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(
+          Seq(value, col),
+          Seq(CharVarcharUtils.getRawType(metadata), 
CharVarcharUtils.getRawType(col.metadata)),
+          padCharCol,
+          truncate = false)
+        (newValue, Some(newCol).filterNot(_ eq col))
+      case (lit, col) if lit.dataType.isInstanceOf[StringType] && 
canEvaluate(lit) =>
+        padAttrLitCmp(col, col.metadata, padCharCol, lit, truncate = 
false).map {
+          case Seq(newCol, newLit) => (newLit, Some(newCol).filterNot(_ eq 
col))
+        }.getOrElse((lit, None))
+      case (value, _) => (value, None)
+    }
+    if (padded.forall(_._2.isEmpty)) {
+      i.copy(values = padded.map(_._1))
+    } else {
+      val plan = i.query.plan
+      // The plan can have more columns than values after de-correlation.
+      val projectList = plan.output.zipWithIndex.map { case (col, idx) =>
+        padded.lift(idx).flatMap(_._2).map { newCol =>
+          Alias(newCol, col.name)(
+            qualifier = col.qualifier,
+            explicitMetadata = 
Some(CharVarcharUtils.cleanMetadata(col.metadata)))
+        }.getOrElse(col)
+      }
+      i.copy(values = padded.map(_._1), query = 
i.query.withNewPlan(Project(projectList, plan)))
+    }
+  }
+
+  /**
+   * Like the IN case of a column, for a scalar subquery of a CHAR column 
compared with a list of
+   * constants, but without truncating the value of the subquery.
+   */
+  private def padInList(i: In, e: Expression, c: CharType, padCharCol: 
Boolean): In = {

Review Comment:
   **[P2] Design: padInList copies the existing IN-with-a-CHAR-column padding**
   
   The new `padInList` (ApplyCharTypePaddingHelper.scala:265-280) repeats the 
body of the existing `case i @ In(e @ AttrOrOuterRef(attr), list)` in the same 
file (lines 132-157) almost line for line. Both compute `literalCharLengths` 
from `lit.eval().asInstanceOf[UTF8String]`, take `targetLen = (c.length +: 
literalCharLengths.flatten).max`, and pad the list with `addPadding(lit, 
charLength, targetLen, alwaysPad = false)`, leaving NULL elements alone. The 
only difference is how the value is padded: `addPadding`/rpad, which truncates, 
for a column, and `createReadSidePadding` for a scalar subquery. For binary 
comparisons the file already handles this difference with one shared helper and 
a flag (`padAttrLitCmp(..., truncate: Boolean)`, line 289, called with 
`truncate = false` from the scalar-subquery cases at 198/204). Do the same 
here: move the column IN body into one helper that takes the value, its 
CharType and a `truncate` flag, and call it from both IN cases.
   
   **Why it matters:** With two copies of the IN-list padding, any change to 
how list constants are measured or padded (NULL elements, collations, the 
target-length rule) has to be made in both places. If one is missed, `c IN 
('a', ...)` and `(SELECT c ...) IN ('a', ...)` silently start matching 
different rows.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/CharVarcharUtils.scala:
##########
@@ -409,20 +442,285 @@ 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,
+          keepFieldNullability = true)
+        (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]] = {

Review Comment:
   **[P2] One non-CHAR attribute disables padding for every grouped position**
   
   widerCharRawTypes merges into one group every pair of positions that share a 
column in any child, then calls widerCharRawType once over all attributes of 
the group. widerCharRawType returns None as soon as any attribute lacks a raw 
type. So one STRING (or a different shape) at one grouped position turns 
padding off for every position in the group, including positions whose own 
children are all CHAR of different lengths. In the scenario below, padding 
position 0 alone would not conflict: the duplicated column t5.c is already the 
widest there.
   
   **Failure scenario:** SELECT c, c FROM t5 INTERSECT SELECT c3, s FROM t3s, 
where t5.c is CHAR(5) = 'a', t3s.c3 is CHAR(3) = 'a', and t3s.s is STRING = 'a  
  '. Positions 0 and 1 are grouped through t5.c. Because s has no raw type, the 
group gets None, and c3 at position 0 is never padded to CHAR(5). 'a    ' vs 'a 
 ' does not match, so the row is missing, even though position 0 on its own 
would have been padded and matched.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ApplyCharTypePaddingHelper.scala:
##########
@@ -158,33 +189,130 @@ 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.
+      // Unlike the cases above, these don't truncate values longer than their 
CHAR length.
+      // A comparison of types that don't match is left to CheckAnalysis.
+      case b @ BinaryComparison(e @ CharScalarSubquery(metadata), lit)
+          if b.resolved && canEvaluate(lit) =>
+        padAttrLitCmp(e, metadata, padCharCol, lit, truncate = false)
+          .map(b.withNewChildren)
+          .getOrElse(b)
+
+      case b @ BinaryComparison(lit, e @ CharScalarSubquery(metadata))
+          if b.resolved && canEvaluate(lit) =>
+        padAttrLitCmp(e, metadata, padCharCol, lit, truncate = false)
+          .map(newChildren => b.withNewChildren(newChildren.reverse))
+          .getOrElse(b)
+
+      case b @ BinaryComparison(e1 @ CharOperand(m1), e2 @ CharOperand(m2))
+          if b.resolved && (e1.isInstanceOf[ScalarSubquery] || 
e2.isInstanceOf[ScalarSubquery]) =>
+        b.withNewChildren(CharVarcharUtils.addPaddingInStringComparison(
+          Seq(e1, e2), Seq(m1, m2).map(CharVarcharUtils.getRawType), 
padCharCol, truncate = false))
+
+      case i @ In(e @ CharScalarSubquery(metadata), list)
+          if i.resolved && list.forall(canEvaluate) =>
+        CharVarcharUtils.getRawType(metadata).collect {
+          case c: CharType => padInList(i, e, c, padCharCol)
+        }.getOrElse(i)
+
+      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, but without 
truncating values
+   * longer than their CHAR length, as read-side padding keeps 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(
+          Seq(value, col),
+          Seq(CharVarcharUtils.getRawType(metadata), 
CharVarcharUtils.getRawType(col.metadata)),
+          padCharCol,
+          truncate = false)
+        (newValue, Some(newCol).filterNot(_ eq col))
+      case (lit, col) if lit.dataType.isInstanceOf[StringType] && 
canEvaluate(lit) =>
+        padAttrLitCmp(col, col.metadata, padCharCol, lit, truncate = 
false).map {
+          case Seq(newCol, newLit) => (newLit, Some(newCol).filterNot(_ eq 
col))
+        }.getOrElse((lit, None))
+      case (value, _) => (value, None)
+    }
+    if (padded.forall(_._2.isEmpty)) {
+      i.copy(values = padded.map(_._1))
+    } else {
+      val plan = i.query.plan
+      // The plan can have more columns than values after de-correlation.
+      val projectList = plan.output.zipWithIndex.map { case (col, idx) =>
+        padded.lift(idx).flatMap(_._2).map { newCol =>
+          Alias(newCol, col.name)(
+            qualifier = col.qualifier,
+            explicitMetadata = 
Some(CharVarcharUtils.cleanMetadata(col.metadata)))
+        }.getOrElse(col)
+      }
+      i.copy(values = padded.map(_._1), query = 
i.query.withNewPlan(Project(projectList, plan)))
+    }
+  }
+
+  /**
+   * Like the IN case of a column, for a scalar subquery of a CHAR column 
compared with a list of
+   * constants, but without truncating the value of the subquery.
+   */
+  private def padInList(i: In, e: Expression, c: CharType, padCharCol: 
Boolean): In = {
+    val literalCharLengths =
+      i.list.map(lit => 
Option(lit.eval().asInstanceOf[UTF8String]).map(_.numChars()))
+    val targetLen = (c.length +: literalCharLengths.flatten).max
+    val newValue = if (targetLen > c.length || padCharCol) {
+      CharVarcharUtils.createReadSidePadding(e, CharType(targetLen, 
c.collation))
+    } else {
+      e
+    }
+    i.copy(
+      value = newValue,
+      list = i.list.zip(literalCharLengths).map {
+        case (lit, Some(charLength)) => addPadding(lit, charLength, targetLen, 
alwaysPad = false)
+        case (lit, None) => lit
+      })
+  }
+
+  /**
+   * Whether a constant evaluates. As in ConstantFolding, a constant that 
fails, such as one in a
+   * branch that is never evaluated, is left to the evaluation of the query.
+   */
+  private def canEvaluate(e: Expression): Boolean =

Review Comment:
   **[P2] Design: canEvaluate duplicates ExprUtils.tryEvalFoldable**
   
   The new `private def canEvaluate(e: Expression) = e.foldable && 
Try(e.eval()).isSuccess` (ApplyCharTypePaddingHelper.scala:286-287) is 
`ExprUtils.tryEvalFoldable(e).isDefined`. That helper 
(sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/ExprUtils.scala:107)
 returns the value of a foldable expression, or None if it is not foldable or 
fails with a NonFatal error. Its doc comment gives the same ConstantFolding 
rationale as the new doc comment (a constant that fails in a conditional branch 
must be left for row evaluation). It is already the shared helper for this 
check in datetimeExpressions.scala:96/1701/2689, 
regexpExpressions.scala:405/750, jsonExpressions.scala:106 and 
collectionOperations.scala:5635. Use `ExprUtils.tryEvalFoldable` and pass its 
value on, instead of evaluating once inside `Try` and again with `lit.eval()` 
in `padAttrLitCmp` (line 304) and `padInList` (line 267).
   
   **Why it matters:** This adds a second definition of "a foldable that 
evaluates" next to the documented one. Each constant is also evaluated twice. 
If the shared helper's semantics change (for example, which exceptions it 
treats as non-fatal, or stateful expressions), CHAR padding will quietly stop 
following them.



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