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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ApplyCharTypePaddingHelper.scala:
##########
@@ -158,9 +161,49 @@ object ApplyCharTypePaddingHelper {
           i.copy(value = newChildren.head, list = newChildren.tail)
         }
 
+      case i: InSubquery if i.resolved => padInSubquery(i)
+
       case other => other
     }
 
+  /**
+   * For CHAR values compared with CHAR columns of a different length of an IN 
subquery, pads the
+   * shorter of each to the longer length. Like read-side padding, it does not 
truncate longer
+   * values. The columns are padded in a Project over the subquery.
+   */
+  private def padInSubquery(i: InSubquery): InSubquery = {
+    val rawTypes = i.values.zip(i.query.childOutputs).map {
+      case (AttrOrOuterRef(attr), col) => 
CharVarcharUtils.widerCharRawType(Seq(attr, col))
+      case _ => None
+    }
+    if (rawTypes.forall(_.isEmpty)) {
+      i
+    } else {
+      val newValues = i.values.zip(rawTypes).map {
+        case (e @ AttrOrOuterRef(attr), Some(rawType)) =>
+          CharVarcharUtils.padCharToWiderLength(attr, rawType).map {

Review Comment:
   **[P1] Pad both IN operands when read-side padding is disabled**
   
   padInSubquery ignores padCharCol and calls padCharToWiderLength, which 
returns None for the operand whose declared length already equals the target. 
That assumes the wider column was padded during its scan. With 
spark.sql.readSideCharPadding=false, external tables can return shorter stored 
strings, so this rewrite changes two equal strings into unequal ones. Unlike 
the existing attribute-comparison path, it never pads the wider operand even 
when predicate padding is enabled.
   
   **Failure scenario:** Create external Parquet tables t3(c CHAR(3)) and t5(c 
CHAR(5)) over a file containing the STRING value 'a'. With 
readSideCharPadding=false and standard semantics disabled, SELECT c FROM t3 
WHERE c IN (SELECT c FROM t5) previously returns 'a'. This patch compares 
padded 'a    ' against unpadded 'a' and returns no rows.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/ApplyCharTypePadding.scala:
##########
@@ -88,10 +88,84 @@ 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), padCharCol = false)))
     } else {
       ApplyCharTypePaddingHelper.paddingForStringComparison(
-        plan, padCharCol = 
!conf.getConf(SQLConf.LEGACY_NO_CHAR_PADDING_IN_PREDICATE))
+        padSetOperations(plan),
+        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. Then it narrows the columns of views that store a 
shorter length.
+   */
+  private def padSetOperations(plan: LogicalPlan): 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).map {

Review Comment:
   **[P0] Pad CHAR operands in scalar-subquery comparisons**
   
   Widening the union values removes previously working scalar-subquery 
matches. ApplyCharTypePaddingHelper handles BinaryComparison only for an 
attribute against a foldable expression or another attribute. ScalarSubquery is 
Unevaluable and non-foldable, so its CHAR output never receives comparison 
padding. With the scenario below, the union now produces only five-character 
values while the scalar subquery still produces 'a  '; the equality returns 
false for every row. Handle the scalar subquery's output metadata and pad the 
shorter operand before introducing the wider union values.
   
   **Failure scenario:** With t3(id INT, c CHAR(3)) containing (1, 'a') and 
t5(id INT, c CHAR(5)) containing (2, 'a'), SELECT id FROM (SELECT id, c FROM t3 
UNION ALL SELECT id, c FROM t5) u WHERE c = (SELECT c FROM t3) previously 
returned id 1 and now returns nothing. CHAR comparison should match both rows.



##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/ApplyCharTypePadding.scala:
##########
@@ -88,10 +88,84 @@ 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), padCharCol = false)))
     } else {
       ApplyCharTypePaddingHelper.paddingForStringComparison(
-        plan, padCharCol = 
!conf.getConf(SQLConf.LEGACY_NO_CHAR_PADDING_IN_PREDICATE))
+        padSetOperations(plan),
+        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. Then it narrows the columns of views that store a 
shorter length.
+   */
+  private def padSetOperations(plan: LogicalPlan): 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).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 == child.output) child else Project(projectList, 
child)
+          }
+          val newOp = op.withNewChildren(newChildren)
+          newOp -> op.output.zip(newOp.output).filterNot { case (a, b) => a == 
b }
+        }
+    }, skipCond = p => p.analyzed || !p.containsAnyPattern(UNION, INTERSECT, 
EXCEPT),
+      canGetOutput = _.resolved)
+    narrowViewColumns(newPlan)
+  }
+
+  /**
+   * A view stores the CHAR types of its columns, and keeps them for the 
values of its query. A view
+   * of a set operation created before the output had the widest length of its 
children stores the
+   * length of the first child. This narrows the values back to that length, 
as the stored type
+   * says, so that comparisons padded to it still match them. The columns keep 
their expression IDs
+   * and metadata.
+   */
+  private def narrowViewColumns(plan: LogicalPlan): LogicalPlan = {
+    def queryAttr(e: Expression): Option[Attribute] = e match {
+      case a: Attribute => Some(a)
+      case c: Cast => queryAttr(c.child)
+      case _ => None
+    }
+    plan.resolveOperatorsUp {
+      case v @ View(_, _, p @ Project(projectList, _), _) =>
+        val newProjectList = projectList.map {
+          case a @ Alias(child, _) =>
+            (for {
+              viewType <- CharVarcharUtils.getRawType(a.metadata)

Review Comment:
   **[P1] Inspect nested field metadata when narrowing stored views**
   
   This guard reads only the view alias's top-level metadata. CreateNamedStruct 
instead copies each input attribute's metadata onto its StructField, leaving 
the enclosing alias without a raw-type entry. Such a persisted view retains 
CHAR(3) metadata inside its stored struct, but this pass skips narrowing it. 
SessionCatalog.castColToType restores that stored struct schema, and Cast 
treats structurally identical STRING fields as an identity conversion, leaving 
the newly five-character values unchanged. A later extracted alias consequently 
pads its comparison literal to three characters and loses matches.
   
   **Failure scenario:** Before upgrading, create v AS SELECT named_struct('c', 
c) AS s FROM (SELECT c FROM t3 UNION ALL SELECT c FROM t5) u, where t3.c is 
CHAR(3), t5.c is CHAR(5), and both contain 'a'. After upgrading, SELECT c FROM 
(SELECT s.c AS c FROM v) q WHERE c = 'a' returns no rows, whereas it previously 
returned the t3 row. The stored nested CHAR(3) metadata is never reconciled 
with the widened values.



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