shivadarshan-devadiga commented on code in PR #60756:
URL: https://github.com/apache/spark/pull/60756#discussion_r4651419020
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/ApplyCharTypePadding.scala:
##########
@@ -88,10 +91,197 @@ 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
values of recursive
+ * CTEs and views that have shorter lengths.
+ */
+ 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 = Union.widerCharRawTypes(op.children)
+ if (rawTypes.forall(_.isEmpty)) {
+ op -> Nil
+ } else {
+ val newOp = op.withNewChildren(op.children.map(padChild(_, rawTypes,
padAllChildren)))
+ newOp -> op.output.zip(newOp.output)
+ .distinctBy { case (a, _) => a.exprId }
+ .filterNot { case (a, b) => a.exprId == b.exprId }
+ }
+ }, skipCond = p => p.analyzed || !p.containsAnyPattern(UNION, INTERSECT,
EXCEPT),
+ canGetOutput = _.resolved)
+ narrowViewColumns(narrowRecursiveTerms(newPlan))
+ }
+
+ /**
+ * Pads the columns of a child of a set operation to the given raw types. A
column is padded
+ * where it is produced if it can be, see [[padAtSource]], so that it keeps
its expression ID,
+ * and otherwise in a Project over the child, which gives it a new one.
+ */
+ private def padChild(
+ child: LogicalPlan,
+ rawTypes: Seq[Option[DataType]],
+ padAllChildren: Boolean): LogicalPlan = {
+ // A column at more than one position has one raw type, see
widerCharRawTypes.
+ val columns = child.output.zip(rawTypes).collect {
+ case (attr, Some(rawType)) => attr.exprId -> rawType
+ }.distinctBy(_._1)
+ val (newChild, paddedAtSource) = columns.foldLeft((child,
Set.empty[ExprId])) {
+ case ((plan, padded), (exprId, rawType)) =>
+ padAtSource(plan, exprId, rawType, padAllChildren)
+ .map(newPlan => (newPlan, padded + exprId))
+ .getOrElse((plan, padded))
+ }
+ val paddedColumns = mutable.HashMap.empty[ExprId, NamedExpression]
+ val projectList = newChild.output.zip(rawTypes).map {
+ case (attr, Some(rawType)) if !paddedAtSource.contains(attr.exprId) =>
+ paddedColumns.getOrElseUpdate(attr.exprId,
+ CharVarcharUtils.padCharToWiderLength(attr, rawType,
padAllChildren).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 == newChild.output) newChild else Project(projectList,
newChild)
+ }
+
+ /**
+ * Pads the column of the plan with the given expression ID to the CHAR
lengths of `rawType`
+ * where it is produced, in an alias of a Project under operators that pass
the column through,
+ * and gives the references to it in them the new raw type. The column keeps
its expression ID,
+ * so that a set operation keeps the output of its first child, which
references to the columns
+ * of the child's DataFrame resolve to. Returns None if the column is
produced elsewhere, or does
+ * not need padding.
+ */
+ private def padAtSource(
+ plan: LogicalPlan,
+ exprId: ExprId,
+ rawType: DataType,
+ alwaysPad: Boolean): Option[LogicalPlan] = {
+ def withNewChild(p: LogicalPlan, newChild: LogicalPlan): LogicalPlan = {
+ val metadata = newChild.output.find(_.exprId == exprId).get.metadata
+ p.withNewChildren(Seq(newChild)).transformExpressions {
+ case a: AttributeReference if a.exprId == exprId =>
a.withMetadata(metadata)
+ }
+ }
+ plan match {
+ case p @ Project(projectList, child) =>
+ projectList.find(_.exprId == exprId) match {
+ case Some(a: Alias) =>
+ CharVarcharUtils.getRawType(a.metadata).flatMap { aliasRawType =>
+ CharVarcharUtils.padCharToWiderLength(a.child, aliasRawType,
rawType, alwaysPad)
+ }.map { case (padded, paddedRawType) =>
+ val newAlias = Alias(padded, a.name)(
+ a.exprId,
+ a.qualifier,
+ Some(CharVarcharUtils.withRawType(a.metadata, paddedRawType)),
+ a.nonInheritableMetadataKeys)
+ p.copy(projectList = projectList.map {
+ case ne if ne.exprId == exprId => newAlias
+ case ne => ne
+ })
+ }
+ case Some(_: Attribute) =>
+ padAtSource(child, exprId, rawType, alwaysPad).map(withNewChild(p,
_))
+ case _ => None
+ }
+ case _: SubqueryAlias | _: Filter | _: Sort | _: LocalLimit | _:
GlobalLimit =>
+ padAtSource(plan.children.head, exprId, rawType,
alwaysPad).map(withNewChild(plan, _))
+ case _ => None
+ }
+ }
+
+ /**
+ * 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))
Review Comment:
Fixed. When the narrowing rebuilds a nullable struct, it reads the fields
only where the struct isn't null, so a field that isn't nullable is now wrapped
in `KnownNotNull` (and the NULL of the guard gets the rebuilt type). The
narrowed struct then has the nullability of the column, and the Cast back to
the column's type, which carries the raw types of its fields, is valid. The
view test has a view of `IF(id > 0, named_struct('k', 1, 'c', c), NULL)` over a
union, stored with CHAR(3), and `WHERE c = 'a'` on its field returns both rows.
--
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]