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


##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/ApplyCharTypePadding.scala:
##########
@@ -88,10 +89,95 @@ object ApplyCharTypePadding extends Rule[LogicalPlan] {
           })
       }, skipCond = p => p.analyzed || p.isInstanceOf[DeleteFromTable], 
canGetOutput = _.resolved)
       padRowLevelConditions(padDeleteConditions(
-        ApplyCharTypePaddingHelper.paddingForStringComparison(newPlan, 
padCharCol = false)))
+        ApplyCharTypePaddingHelper.paddingForStringComparison(
+          narrowCharColumns(newPlan), padCharCol = false)))
     } else {
       ApplyCharTypePaddingHelper.paddingForStringComparison(
-        plan, padCharCol = 
!conf.getConf(SQLConf.LEGACY_NO_CHAR_PADDING_IN_PREDICATE))
+        narrowCharColumns(plan),
+        padCharCol = 
!conf.getConf(SQLConf.LEGACY_NO_CHAR_PADDING_IN_PREDICATE))
+    }
+  }
+
+  /**
+   * Set operations of CHAR columns of different lengths have the widest 
length, see
+   * [[SetOperationCharPadding]]. This narrows the values of recursive CTEs 
and views, whose
+   * columns keep shorter lengths, to those lengths.
+   */
+  private def narrowCharColumns(plan: LogicalPlan): LogicalPlan =
+    narrowViewColumns(narrowRecursiveTerms(plan))
+
+  /**
+   * 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))
+      }
+    }
+  }
+
+  /**
+   * 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, a.dataType)
+              attr <- queryAttr(child)
+              queryType <- CharVarcharUtils.getRawType(attr.metadata, 
attr.dataType)
+              narrowed <- narrowToLength(child, queryType, viewType)

Review Comment:
   **[P1] Reconcile view casts before comparing raw struct types**
   
   queryAttr unwraps the view's Cast, so queryType describes the value before 
that cast, while child already has the stored view's physical type. If another 
struct field needs an allowed numeric conversion, narrowerCharType returns None 
for that field and then rejects narrowing the entire struct. The CHAR field 
therefore keeps the union's wider value beneath the view's shorter stored 
metadata. Reconcile the raw type with the cast result, or perform the narrowing 
before the cast.
   
   **Failure scenario:** Before upgrading, create t3(k BIGINT,c CHAR(3)) and 
t5(k BIGINT,c CHAR(5)), each containing (1,'a'), and create v AS SELECT 
named_struct('k',k,'c',c) AS s FROM (SELECT * FROM t3 UNION ALL SELECT * FROM 
t5). Recreate both source tables with k INT and the same rows; the view can 
safely cast k back to BIGINT. After upgrading, SELECT c FROM (SELECT s.c AS c 
FROM v) q WHERE c = 'a' returns no rows: INT versus BIGINT prevents narrowing c 
from five characters to the stored CHAR(3), and the comparison literal is 
padded to three. Previously the t3 row matched.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/CharVarcharUtils.scala:
##########
@@ -409,23 +437,214 @@ 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) {

Review Comment:
   **[P0] Preserve nested CHAR metadata across set-operation coercion**
   
   Running padding after type coercion is insufficient because 
WidenSetOperationTypes.widenTypes creates Alias(Cast(...)) without explicit 
metadata, and Alias.metadata returns empty metadata for a Cast. This guard 
consequently skips the outer set operation after an inner union has widened its 
values. ReplaceIntersectWithSemiJoin subsequently compares the structs using 
ordinary EqualNullSafe, without another padding pass. Preserve the nested CHAR 
information through these coercion casts so the outer operation can align its 
operands.
   
   **Failure scenario:** Create t3(s STRUCT<k:INT,c:CHAR(3)>), t5(s 
STRUCT<k:INT,c:CHAR(5)>), and tb(s STRUCT<k:BIGINT,c:CHAR(3)>), each containing 
(1,'a'). SELECT s FROM tb INTERSECT (SELECT s FROM t3 UNION ALL SELECT s FROM 
t5) previously returned a match. Now the inner union pads both strings to five 
characters; the outer INT-to-BIGINT struct cast drops its CHAR metadata, so 
tb's three-character string never matches and the result is empty. EXCEPT 
incorrectly retains the 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