gengliangwang commented on code in PR #60756:
URL: https://github.com/apache/spark/pull/60756#discussion_r4642446982
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/ApplyCharTypePadding.scala:
##########
@@ -88,10 +91,58 @@ object ApplyCharTypePadding extends Rule[LogicalPlan] {
})
}, skipCond = p => p.analyzed || p.isInstanceOf[DeleteFromTable],
canGetOutput = _.resolved)
padRowLevelConditions(padDeleteConditions(
- ApplyCharTypePaddingHelper.paddingForStringComparison(newPlan,
padCharCol = false)))
+ ApplyCharTypePaddingHelper.paddingForStringComparison(
+ padUnionChildren(newPlan), padCharCol = false)))
} else {
ApplyCharTypePaddingHelper.paddingForStringComparison(
- plan, padCharCol =
!conf.getConf(SQLConf.LEGACY_NO_CHAR_PADDING_IN_PREDICATE))
+ padUnionChildren(plan),
+ padCharCol =
!conf.getConf(SQLConf.LEGACY_NO_CHAR_PADDING_IN_PREDICATE))
+ }
+ }
+
+ /**
+ * The output of a Union takes the raw type of its first child. When its
children have CHAR
+ * columns or fields of different lengths at the same position, this pads
the shorter ones to the
+ * widest length and gives the output that length, as the SQL standard does
for the union of
+ * CHAR(n) and CHAR(m). Otherwise the output keeps the length of the first
child, and comparisons
+ * pad to it, so they do not match the values of a child with longer values.
+ */
+ private def padUnionChildren(plan: LogicalPlan): LogicalPlan = {
+ // The raw types of the outputs that change. transformUpWithNewOutput
gives the references to
+ // them the new expression IDs, but keeps the metadata they had.
+ val newRawTypes = mutable.HashMap.empty[ExprId, Metadata]
+ val newPlan = plan.transformUpWithNewOutput({
+ case u: Union =>
+ val columns =
u.children.map(_.output).transpose.map(CharVarcharUtils.padToWiderCharLength)
Review Comment:
**[P0] Refresh widened metadata before processing ancestor unions**
The metadata repair runs after the entire traversal, but
QueryPlan.updateAttr deliberately preserves the referring attribute's old
metadata. A Project above an inner union therefore still advertises CHAR(3)
after that union starts producing CHAR(5) values. An outer union with CHAR(4)
chooses length 4 and inserts rpad(value, 4), truncating valid five-character
values. The subsequent metadata repair cannot correct the already-generated
padding length. Propagate the widened metadata before computing each ancestor
union's target.
**Failure scenario:** With t3(c CHAR(3)) containing 'abc', t5(c CHAR(5))
containing 'abcde', and t4(c CHAR(4)) containing 'z', SELECT c FROM (SELECT c
FROM t3 UNION ALL SELECT c FROM t5) u UNION ALL SELECT c FROM t4 returns 'abcd'
for the t5 row instead of preserving 'abcde'.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/CharVarcharUtils.scala:
##########
@@ -426,6 +426,55 @@ object CharVarcharUtils extends Logging with
SparkCharVarcharUtils {
}
}
+ /**
+ * Pads the given attributes, the outputs of the children of a set operation
at one position, so
+ * that CHAR columns and fields of different lengths at the same place all
get the widest length.
+ * Returns the raw type with the widest lengths, which keeps the names of
the first attribute's
+ * fields, and an expression for each attribute: the padded value, or the
attribute if it already
+ * has the widest lengths. Returns None if the raw types are already the
same, or if they are not
+ * all CHAR types, or structs and arrays of them, at the same places.
+ */
+ def padToWiderCharLength(attrs: Seq[Attribute]): Option[(DataType,
Seq[Expression])] = {
+ val rawTypes = attrs.map(attr => getRawType(attr.metadata))
+ if (rawTypes.exists(_.isEmpty) || rawTypes.distinct.length == 1) {
+ None
+ } else {
+ rawTypes.map(_.get).map(Option(_)).reduce { (left, right) =>
+ for (l <- left; r <- right; wider <- widerCharType(l, r)) yield wider
+ }.map { target =>
+ val padded = attrs.zip(rawTypes.map(_.get)).map { case (attr, rawType)
=>
+ padCharToTargetLength(attr, rawType, target, alwaysPad =
false).getOrElse(attr)
Review Comment:
**[P0] Preserve tolerated overlength values when padding union outputs**
Under default semantics, CharVarcharCodegenUtils.readSidePadding
deliberately preserves values longer than the declared CHAR length; the
existing 'create table w/ location and over length values' test requires this
behavior. padCharToTargetLength instead generates StringRPad, whose
UTF8String.rpad implementation truncates values exceeding its target. Moving
that expression into the union's output projection newly destroys characters in
supported external-table reads. Use non-truncating padding on this path.
**Failure scenario:** An external Parquet table t3 declares c CHAR(3) over a
stored STRING value 'abcdef'; t5 declares c CHAR(5). With default settings,
SELECT c FROM t3 UNION ALL SELECT c FROM t5 changes the t3 value to 'abcde',
whereas reading t3 preserves 'abcdef'.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/ApplyCharTypePadding.scala:
##########
@@ -88,10 +91,58 @@ object ApplyCharTypePadding extends Rule[LogicalPlan] {
})
}, skipCond = p => p.analyzed || p.isInstanceOf[DeleteFromTable],
canGetOutput = _.resolved)
padRowLevelConditions(padDeleteConditions(
- ApplyCharTypePaddingHelper.paddingForStringComparison(newPlan,
padCharCol = false)))
+ ApplyCharTypePaddingHelper.paddingForStringComparison(
+ padUnionChildren(newPlan), padCharCol = false)))
} else {
ApplyCharTypePaddingHelper.paddingForStringComparison(
- plan, padCharCol =
!conf.getConf(SQLConf.LEGACY_NO_CHAR_PADDING_IN_PREDICATE))
+ padUnionChildren(plan),
+ padCharCol =
!conf.getConf(SQLConf.LEGACY_NO_CHAR_PADDING_IN_PREDICATE))
+ }
+ }
+
+ /**
+ * The output of a Union takes the raw type of its first child. When its
children have CHAR
+ * columns or fields of different lengths at the same position, this pads
the shorter ones to the
+ * widest length and gives the output that length, as the SQL standard does
for the union of
+ * CHAR(n) and CHAR(m). Otherwise the output keeps the length of the first
child, and comparisons
+ * pad to it, so they do not match the values of a child with longer values.
+ */
+ private def padUnionChildren(plan: LogicalPlan): LogicalPlan = {
+ // The raw types of the outputs that change. transformUpWithNewOutput
gives the references to
+ // them the new expression IDs, but keeps the metadata they had.
+ val newRawTypes = mutable.HashMap.empty[ExprId, Metadata]
+ val newPlan = plan.transformUpWithNewOutput({
+ case u: Union =>
+ val columns =
u.children.map(_.output).transpose.map(CharVarcharUtils.padToWiderCharLength)
+ if (columns.forall(_.isEmpty)) {
+ u -> Nil
+ } else {
+ val newChildren = u.children.zipWithIndex.map { case (child, i) =>
+ val projectList = child.output.zip(columns).map {
+ case (attr, Some((rawType, padded))) if !(padded(i) eq attr) =>
+ Alias(padded(i), attr.name)(
+ explicitMetadata =
Some(CharVarcharUtils.withRawType(attr.metadata, rawType)))
+ case (attr, _) => attr
+ }
+ if (projectList == child.output) child else Project(projectList,
child)
+ }
+ val newUnion = u.withNewChildren(newChildren)
+ val attrMapping = u.output.zip(newUnion.output).filterNot { case (a,
b) => a == b }
+ attrMapping.foreach { case (_, attr) => newRawTypes(attr.exprId) =
attr.metadata }
Review Comment:
**[P0] Refresh CTE references when their definition widens**
CTERelationDef and its CTERelationRef consumers are sibling subtrees of
WithCTE. transformUpWithNewOutput does not propagate attribute mappings between
siblings, and this map records only the new union expression IDs, which the
references do not have. The references retain CHAR(3) metadata, so comparison
padding uses length 3 although the definition now produces length 5.
ResolveWithCTE has already run; later CTE inlining does not rerun comparison
padding.
**Failure scenario:** With t3(c CHAR(3)) and t5(c CHAR(5)) each containing
'a', WITH u AS (SELECT c FROM t3 UNION ALL SELECT c FROM t5) SELECT * FROM u
WHERE c = 'a' returns no rows instead of two.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/ApplyCharTypePadding.scala:
##########
@@ -88,10 +91,58 @@ object ApplyCharTypePadding extends Rule[LogicalPlan] {
})
}, skipCond = p => p.analyzed || p.isInstanceOf[DeleteFromTable],
canGetOutput = _.resolved)
padRowLevelConditions(padDeleteConditions(
- ApplyCharTypePaddingHelper.paddingForStringComparison(newPlan,
padCharCol = false)))
+ ApplyCharTypePaddingHelper.paddingForStringComparison(
+ padUnionChildren(newPlan), padCharCol = false)))
} else {
ApplyCharTypePaddingHelper.paddingForStringComparison(
- plan, padCharCol =
!conf.getConf(SQLConf.LEGACY_NO_CHAR_PADDING_IN_PREDICATE))
+ padUnionChildren(plan),
+ padCharCol =
!conf.getConf(SQLConf.LEGACY_NO_CHAR_PADDING_IN_PREDICATE))
+ }
+ }
+
+ /**
+ * The output of a Union takes the raw type of its first child. When its
children have CHAR
+ * columns or fields of different lengths at the same position, this pads
the shorter ones to the
+ * widest length and gives the output that length, as the SQL standard does
for the union of
+ * CHAR(n) and CHAR(m). Otherwise the output keeps the length of the first
child, and comparisons
+ * pad to it, so they do not match the values of a child with longer values.
+ */
+ private def padUnionChildren(plan: LogicalPlan): LogicalPlan = {
+ // The raw types of the outputs that change. transformUpWithNewOutput
gives the references to
+ // them the new expression IDs, but keeps the metadata they had.
+ val newRawTypes = mutable.HashMap.empty[ExprId, Metadata]
+ val newPlan = plan.transformUpWithNewOutput({
+ case u: Union =>
+ val columns =
u.children.map(_.output).transpose.map(CharVarcharUtils.padToWiderCharLength)
+ if (columns.forall(_.isEmpty)) {
+ u -> Nil
+ } else {
+ val newChildren = u.children.zipWithIndex.map { case (child, i) =>
+ val projectList = child.output.zip(columns).map {
+ case (attr, Some((rawType, padded))) if !(padded(i) eq attr) =>
+ Alias(padded(i), attr.name)(
+ explicitMetadata =
Some(CharVarcharUtils.withRawType(attr.metadata, rawType)))
+ case (attr, _) => attr
+ }
+ if (projectList == child.output) child else Project(projectList,
child)
+ }
+ val newUnion = u.withNewChildren(newChildren)
+ val attrMapping = u.output.zip(newUnion.output).filterNot { case (a,
b) => a == b }
+ attrMapping.foreach { case (_, attr) => newRawTypes(attr.exprId) =
attr.metadata }
+ newUnion -> attrMapping
+ }
+ }, skipCond = p => p.analyzed || !p.containsPattern(UNION), canGetOutput =
_.resolved)
+ if (newRawTypes.isEmpty) {
+ newPlan
+ } else {
+ // Not pruned by pattern: a subquery above the Union refers to its
outputs without one.
+ newPlan.resolveOperatorsUpWithSubqueriesAndPruning(_ => true) {
+ case p =>
+ p.transformExpressions {
+ case a: AttributeReference if newRawTypes.get(a.exprId).exists(_
!= a.metadata) =>
Review Comment:
**[P0] Propagate widened metadata through renamed outputs**
newRawTypes contains only the union outputs' expression IDs. An intervening
Alias introduces another ID, and transformUpWithNewOutput stops forwarding the
union's mapping when that ID is absent from the Project output. The repair
updates the alias's child but misses references to the alias itself.
paddingForStringComparison consequently pads an outer filter's literal to
CHAR(3), while both input values are now CHAR(5), dropping both rows.
**Failure scenario:** With t3(c CHAR(3)) and t5(c CHAR(5)) each containing
'a', SELECT * FROM (SELECT c AS k FROM (SELECT c FROM t3 UNION ALL SELECT c
FROM t5) u) v WHERE k = 'a' returns no rows instead of two.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/ApplyCharTypePadding.scala:
##########
@@ -88,10 +91,58 @@ object ApplyCharTypePadding extends Rule[LogicalPlan] {
})
}, skipCond = p => p.analyzed || p.isInstanceOf[DeleteFromTable],
canGetOutput = _.resolved)
padRowLevelConditions(padDeleteConditions(
- ApplyCharTypePaddingHelper.paddingForStringComparison(newPlan,
padCharCol = false)))
+ ApplyCharTypePaddingHelper.paddingForStringComparison(
+ padUnionChildren(newPlan), padCharCol = false)))
} else {
ApplyCharTypePaddingHelper.paddingForStringComparison(
- plan, padCharCol =
!conf.getConf(SQLConf.LEGACY_NO_CHAR_PADDING_IN_PREDICATE))
+ padUnionChildren(plan),
+ padCharCol =
!conf.getConf(SQLConf.LEGACY_NO_CHAR_PADDING_IN_PREDICATE))
+ }
+ }
+
+ /**
+ * The output of a Union takes the raw type of its first child. When its
children have CHAR
+ * columns or fields of different lengths at the same position, this pads
the shorter ones to the
+ * widest length and gives the output that length, as the SQL standard does
for the union of
+ * CHAR(n) and CHAR(m). Otherwise the output keeps the length of the first
child, and comparisons
+ * pad to it, so they do not match the values of a child with longer values.
+ */
+ private def padUnionChildren(plan: LogicalPlan): LogicalPlan = {
+ // The raw types of the outputs that change. transformUpWithNewOutput
gives the references to
+ // them the new expression IDs, but keeps the metadata they had.
+ val newRawTypes = mutable.HashMap.empty[ExprId, Metadata]
+ val newPlan = plan.transformUpWithNewOutput({
+ case u: Union =>
+ val columns =
u.children.map(_.output).transpose.map(CharVarcharUtils.padToWiderCharLength)
+ if (columns.forall(_.isEmpty)) {
+ u -> Nil
+ } else {
+ val newChildren = u.children.zipWithIndex.map { case (child, i) =>
+ val projectList = child.output.zip(columns).map {
+ case (attr, Some((rawType, padded))) if !(padded(i) eq attr) =>
+ Alias(padded(i), attr.name)(
+ explicitMetadata =
Some(CharVarcharUtils.withRawType(attr.metadata, rawType)))
+ case (attr, _) => attr
+ }
+ if (projectList == child.output) child else Project(projectList,
child)
+ }
+ val newUnion = u.withNewChildren(newChildren)
+ val attrMapping = u.output.zip(newUnion.output).filterNot { case (a,
b) => a == b }
+ attrMapping.foreach { case (_, attr) => newRawTypes(attr.exprId) =
attr.metadata }
+ newUnion -> attrMapping
+ }
+ }, skipCond = p => p.analyzed || !p.containsPattern(UNION), canGetOutput =
_.resolved)
+ if (newRawTypes.isEmpty) {
+ newPlan
+ } else {
+ // Not pruned by pattern: a subquery above the Union refers to its
outputs without one.
+ newPlan.resolveOperatorsUpWithSubqueriesAndPruning(_ => true) {
+ case p =>
+ p.transformExpressions {
+ case a: AttributeReference if newRawTypes.get(a.exprId).exists(_
!= a.metadata) =>
Review Comment:
**[P0] Update attributes wrapped in OuterReference**
QueryPlan.updateOuterReferencesInSubquery changes correlated attributes'
expression IDs while preserving their metadata. This repair matches only
AttributeReference, but OuterReference is a LeafExpression, so its wrapped
attribute is never visited. ApplyCharTypePaddingHelper explicitly reads that
wrapped attribute's metadata through AttrOrOuterRef and therefore retains the
old comparison width. Handle OuterReference explicitly when repairing metadata.
**Failure scenario:** With t3(c CHAR(3)) and t5(c CHAR(5)) each containing
'a', SELECT c FROM (SELECT c FROM t3 UNION ALL SELECT c FROM t5) u WHERE EXISTS
(SELECT 1 WHERE u.c = 'a') compares five-character values against 'a ' and
returns no rows instead of two.
--
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]