gengliangwang commented on code in PR #60756:
URL: https://github.com/apache/spark/pull/60756#discussion_r4647857685
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/ApplyCharTypePadding.scala:
##########
@@ -88,10 +90,99 @@ 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
columns of views that
+ * store a shorter length.
+ */
+ 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. One that reads a recursive reference keeps its CHAR
lengths.
+ case op @ (_: Union | _: Intersect | _: Except)
+ if op.resolved && !op.children.exists(Union.readsRecursiveReference)
=>
+ val rawTypes =
CharVarcharUtils.widerCharRawTypes(op.children.map(_.output))
+ if (rawTypes.forall(_.isEmpty)) {
+ op -> Nil
+ } else {
+ val newChildren = op.children.map { child =>
+ // A column at more than one position has one raw type, and gets
one padded column.
+ val paddedColumns = mutable.HashMap.empty[ExprId, NamedExpression]
+ val projectList = child.output.zip(rawTypes).map {
+ case (attr, Some(rawType)) =>
paddedColumns.getOrElseUpdate(attr.exprId,
+ CharVarcharUtils.padCharToWiderLength(attr, rawType,
padAllChildren).map {
+ case (padded, paddedRawType) =>
+ Alias(padded, attr.name)(
Review Comment:
**[P1] Padding the first child changes set-op output exprIds and breaks
Classic left-DataFrame column references**
Union, Intersect and Except take their output exprIds from the first child
(mergeChildOutputs uses firstAttr.exprId). When the first child has the shorter
CHAR length, padSetOperations wraps its column in Alias(readSidePadding(...),
name), which has a fresh exprId. The eagerly analyzed set operation then
outputs c#new instead of c#1. Classic Dataset.col resolves to the concrete
AttributeReference of the left DataFrame (Dataset.col -> resolve ->
addDataFrameIdToCol). Such a reference no longer matches the set operation's
output, so a later select or filter fails analysis with a missing-attribute
error. Users rely on this pattern, and python/pyspark/sql/tests/test_column.py
(test_resolve_after_union, test_resolve_after_intersect) documents it as
supported in Classic. The same code worked before the PR when the CHAR lengths
differed.
**Failure scenario:** Classic: val a = spark.table("t3") (c CHAR(3)); val b
= spark.table("t5") (c CHAR(5)); a.union(b).select(a("c")) or
a.union(b).filter(a("c") === "x"). The union's output is now c#new (the padded
alias), not c#1, so analysis fails with MISSING_ATTRIBUTES.
a.intersect(b).select(a("c")) fails the same way. Before the PR all three
resolved.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/basicLogicalOperators.scala:
##########
@@ -504,20 +535,61 @@ object Union {
Union (left :: right :: Nil)
}
- // updating nullability to make all the children consistent
- def mergeChildOutputs(childOutputs: Seq[Seq[Attribute]]): Seq[Attribute] = {
- childOutputs.transpose.map { attrs =>
+ // updating nullability to make all the children consistent, and the CHAR
lengths of the raw
+ // types if the children have CHAR columns of different lengths, see
+ // CharVarcharUtils.widerCharRawTypes. ApplyCharTypePadding pads the values
of the shorter ones.
+ def mergeChildOutputs(childOutputs: Seq[Seq[Attribute]]): Seq[Attribute] =
+ mergeChildOutputs(childOutputs, widenCharLengths = true)
+
+ def mergeChildOutputs(
+ childOutputs: Seq[Seq[Attribute]],
+ widenCharLengths: Boolean): Seq[Attribute] = {
+ val rawTypes = widerCharRawTypes(childOutputs, widenCharLengths)
+ childOutputs.transpose.zipWithIndex.map { case (attrs, i) =>
val firstAttr = attrs.head
val nullable = attrs.exists(_.nullable)
val newDt = attrs.map(_.dataType).reduce(StructType.unionLikeMerge)
- if (firstAttr.dataType == newDt) {
+ val metadata =
rawTypes(i).map(CharVarcharUtils.withRawType(firstAttr.metadata, _))
+ .getOrElse(firstAttr.metadata)
+ if (firstAttr.dataType == newDt && metadata == firstAttr.metadata) {
firstAttr.withNullability(nullable)
} else {
- AttributeReference(firstAttr.name, newDt, nullable,
firstAttr.metadata)(
+ AttributeReference(firstAttr.name, newDt, nullable, metadata)(
firstAttr.exprId, firstAttr.qualifier)
}
}
}
+
+ private[sql] def widerCharRawTypes(
+ childOutputs: Seq[Seq[Attribute]],
+ widenCharLengths: Boolean): Seq[Option[DataType]] = {
+ if (widenCharLengths) {
+ CharVarcharUtils.widerCharRawTypes(childOutputs)
+ } else {
+ Seq.fill(childOutputs.head.length)(None)
+ }
+ }
+
+ private[logical] def withWiderCharRawType(
+ attr: Attribute,
+ rawType: Option[DataType]): Attribute = {
+ rawType.map(CharVarcharUtils.withRawType(attr.metadata, _))
+ .filter(_ != attr.metadata)
+ .map(attr.withMetadata)
+ .getOrElse(attr)
+ }
+
+ /**
+ * Whether the plan reads the recursive reference of a recursive CTE that it
is not part of, as a
+ * set operation in the recursive term can. The CHAR lengths of such a set
operation are not
+ * widened, as those of the [[UnionLoop]] are not: they must stay the
lengths of the reference.
+ */
+ def readsRecursiveReference(plan: LogicalPlan): Boolean = plan match {
+ case _: UnionLoop => false
+ case r: CTERelationRef => r.recursive
Review Comment:
**[P1] readsRecursiveReference misses recursive references reached through a
nested CTE**
readsRecursiveReference returns r.recursive for a CTERelationRef and does
not look into the referenced definition. A recursive term can read the
recursive reference through a nested non-recursive CTE, which cte-recursion.sql
tests as supported. A set operation in such a term is still widened and padded
by padSetOperations, while UnionLoop keeps the anchor's length
(widenCharLengths = false). Rows produced by the recursion then carry a longer
CHAR padding than the output type of the recursive CTE claims. (Plausible: this
depends on the nested CTE still being a CTERelationRef, not inlined, when
ApplyCharTypePadding runs.)
**Failure scenario:** WITH RECURSIVE r AS (SELECT c FROM t3 UNION ALL (WITH
x AS (SELECT c FROM r WHERE ...) SELECT c FROM x UNION ALL SELECT c FROM t5))
SELECT * FROM r WHERE c = 'a', with t3.c CHAR(3) and t5.c CHAR(5). The inner
union is widened to CHAR(5), so rows from r via x are padded to 'a '. r's
output stays CHAR(3), so the literal is padded to 'a '. Recursion rows that
matched before the PR are now dropped.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/ApplyCharTypePadding.scala:
##########
@@ -88,10 +90,99 @@ 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
columns of views that
+ * store a shorter length.
+ */
+ 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. One that reads a recursive reference keeps its CHAR
lengths.
+ case op @ (_: Union | _: Intersect | _: Except)
+ if op.resolved && !op.children.exists(Union.readsRecursiveReference)
=>
+ val rawTypes =
CharVarcharUtils.widerCharRawTypes(op.children.map(_.output))
+ if (rawTypes.forall(_.isEmpty)) {
+ op -> Nil
+ } else {
+ val newChildren = op.children.map { child =>
+ // A column at more than one position has one raw type, and gets
one padded column.
+ val paddedColumns = mutable.HashMap.empty[ExprId, NamedExpression]
+ val projectList = child.output.zip(rawTypes).map {
+ case (attr, Some(rawType)) =>
paddedColumns.getOrElseUpdate(attr.exprId,
+ CharVarcharUtils.padCharToWiderLength(attr, rawType,
padAllChildren).map {
Review Comment:
**[P2] Set-op padding with padAllChildren is not idempotent when raw-type
strings differ only textually**
With spark.sql.readSideCharPadding=false, padSetOperations calls
padCharToWiderLength with alwaysPad = padAllChildren = true for every child
whenever CharVarcharUtils.widerCharRawType returns Some. widerCharRawType
decides that by comparing the raw-type metadata strings as text. Two types can
be equivalent yet render as different strings. One case is an explicit default
collation: CharType.typeName prints 'char(5) collate UTF8_BINARY' when
collation is Some, and 'char(5)' when it is None. Another is struct field
names, since widerCharType keeps the names of the attribute being padded. In
these cases every child is padded, and each padded alias keeps its own
differing string. The next application of the rule therefore sees different
strings again and pads every child a second time. Under testing, the Post-Hoc
Resolution Once batch fails its idempotence check. In production, values are
padded twice, and same-length struct values that used to be returned unpadded
now come back padded
.
**Failure scenario:** SET spark.sql.readSideCharPadding=false; t3(c CHAR(3))
UNION ALL tc(c CHAR(5) COLLATE UTF8_BINARY). The first run pads both children;
the aliases carry metadata 'char(5)' and 'char(5) collate UTF8_BINARY'. A
second run sees two distinct strings, gets Some(char(5)) and pads both again.
Under Utils.isTesting this throws onceStrategyIdempotenceIsBrokenForBatchError.
Likewise, a UNION ALL of struct<a: char(3)> and struct<b: char(3)> pads both
children on every run, and an external unpadded value 'a' now comes back as 'a
'.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/CharVarcharUtils.scala:
##########
@@ -409,20 +418,192 @@ 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) {
+ None
+ } else {
+ rawTypeStrings.map(s =>
Option(CatalystSqlParser.parseDataType(s.get))).reduce {
+ (left, right) => for (l <- left; r <- right; wider <- widerCharType(l,
r)) yield wider
+ }
+ }
+ }
+
+ /**
+ * Pads the CHAR columns and fields of the given attribute that are shorter
than those at the
+ * same places of the given raw type, see [[widerCharRawType]]. Like
read-side padding, it does
+ * not truncate longer values. Returns the padded value and its raw type,
which keeps the names
+ * of the attribute's fields, or None if the attribute is already as long,
unless `alwaysPad`,
+ * for values that the scan does not pad.
+ */
+ def padCharToWiderLength(
+ attr: Attribute,
+ rawType: DataType,
+ alwaysPad: Boolean = false): Option[(Expression, DataType)] = {
+ getRawType(attr.metadata).flatMap { attrRawType =>
+ widerCharType(attrRawType, rawType).filter(alwaysPad || _ !=
attrRawType).map { wider =>
+ val padded = processStringForCharVarchar(
Review Comment:
**[P2] Padding the shorter child nests readSidePadding and loses CHAR filter
pushdown**
With read-side padding on, the shorter child's output is already the scan's
padding alias readSidePadding(c, 3). padCharToWiderLength wraps that attribute
again, and after alias collapsing a filter sees
readSidePadding(readSidePadding(c, 3), 5).
V2ExpressionBuilder.generateCharPadColumn translates CHAR_READ_SIDE_PADDING
only when its child can be translated. The inner readSidePadding is a
StaticInvoke without a scalar function, so it cannot be, and the predicate is
not pushed. readSidePadding(c, 5) directly on the scan attribute gives the same
values and would still push down.
**Failure scenario:** A JDBC v2 catalog over Postgres, Oracle or MSSQL,
whose dialects support V2_CHAR_READ_SIDE_PADDING, with t3(c CHAR(3)) and t5(c
CHAR(5)). SELECT * FROM (SELECT c FROM t3 UNION ALL SELECT c FROM t5) WHERE c =
'a'. Before the PR, t3's scan received readSidePadding(c, 3) = 'a '. Now the
t3 side has readSidePadding(readSidePadding(c, 3), 5) = 'a ', which is
untranslatable, so all of t3 is read over JDBC and filtered in Spark.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/ApplyCharTypePadding.scala:
##########
@@ -88,10 +90,99 @@ 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
columns of views that
+ * store a shorter length.
+ */
+ 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. One that reads a recursive reference keeps its CHAR
lengths.
+ case op @ (_: Union | _: Intersect | _: Except)
+ if op.resolved && !op.children.exists(Union.readsRecursiveReference)
=>
Review Comment:
**[P2] Design: CHAR-widening check copied into five places;
ApplyCharTypePadding skips the gated helper**
This revision decides whether a set operation widens CHAR lengths with the
expression `!children.exists(Union.readsRecursiveReference)`, copied into five
places:
- basicLogicalOperators.scala:453 (Intersect.widenCharLengths)
- basicLogicalOperators.scala:507 (Except.widenCharLengths)
- basicLogicalOperators.scala:617 (UnionBase.widenCharLengths)
- SetOperationLikeResolver.scala:104, which recomputes it to pass
`widenCharLengths`
- ApplyCharTypePadding.scala:117, which repeats it as a case guard and then
calls `CharVarcharUtils.widerCharRawTypes` directly on line 118.
The PR already adds a gated helper, `Union.widerCharRawTypes(childOutputs,
widenCharLengths)` at basicLogicalOperators.scala:563. It is `private[sql]`, so
sql/core can call it, yet ApplyCharTypePadding bypasses it and rebuilds the
gate inline.
The one-argument overloads `Union.mergeChildOutputs(childOutputs)` (:541),
`Intersect.mergeChildOutputs(childOutputs)` (:465) and
`Except.mergeChildOutputs(childOutputs)` (:519) no longer have any caller in
the repository. Their hard-coded `widenCharLengths = true` skips the recursion
check. Meanwhile the two-argument versions are now public: Union's was
`private[logical]`, and Intersect and Except got new ones.
Suggested change: add one helper that takes the child plans and applies the
recursion check itself, e.g. `Union.widerCharRawTypes(children:
Seq[LogicalPlan]): Seq[Option[DataType]]`. Use it in the three computeOutput
methods, SetOperationLikeResolver and ApplyCharTypePadding.padSetOperations.
Delete the unused one-argument overloads, or route them through the same helper.
**Why it matters:** The output CHAR length set by mergeChildOutputs and the
padding of each child's values in ApplyCharTypePadding must agree position by
position, and that now depends on five separate copies of one condition. If one
copy changes, for example when a new recursive-reference node or another
exemption is added, an operator can declare CHAR(5) while one child's values
stay CHAR(3). That brings back the order-dependent missed comparisons this PR
fixes, and every fix to the condition must be made five times.
--
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]