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


##########
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:
   Fixed. The view narrowing now reads the raw type from the column's metadata, 
or from the metadata of its struct fields when it has none 
(`CharVarcharUtils.getRawType(metadata, dataType)`), on both the stored side 
and the query side. A narrowed struct is cast back to the column's data type, 
so its fields keep the metadata with their raw types. The view test now also 
has your `named_struct` view: `SELECT ... s.c AS c FROM vs ... WHERE c = 'a'` 
returns both rows, and the over-length 'abcde' is kept.



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