gengliangwang commented on code in PR #60756:
URL: https://github.com/apache/spark/pull/60756#discussion_r4644746858
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ApplyCharTypePaddingHelper.scala:
##########
@@ -158,9 +180,62 @@ object ApplyCharTypePaddingHelper {
i.copy(value = newChildren.head, list = newChildren.tail)
}
+ // Like the cases above, for a scalar subquery of a CHAR column compared
with a string
+ // literal, a column, or another scalar subquery.
+ case b @ BinaryComparison(e @ CharScalarSubquery(metadata), lit) if
lit.foldable =>
+ padAttrLitCmp(e, metadata, padCharCol,
lit).map(b.withNewChildren).getOrElse(b)
+
+ case b @ BinaryComparison(lit, e @ CharScalarSubquery(metadata)) if
lit.foldable =>
+ padAttrLitCmp(e, metadata, padCharCol, lit)
+ .map(newChildren => b.withNewChildren(newChildren.reverse))
+ .getOrElse(b)
+
+ case b @ BinaryComparison(e1 @ CharOperand(m1), e2 @ CharOperand(m2))
+ if e1.isInstanceOf[ScalarSubquery] ||
e2.isInstanceOf[ScalarSubquery] =>
+ b.withNewChildren(CharVarcharUtils.addPaddingInStringComparison(
+ Seq(e1, e2), Seq(m1, m2).map(CharVarcharUtils.getRawType),
padCharCol))
+
+ case i: InSubquery if i.resolved => padInSubquery(i, padCharCol)
+
case other => other
}
+ /**
+ * Pads each CHAR value of an IN subquery and the CHAR column of the
subquery it is compared
+ * with, as a comparison of two columns pads them. The columns are padded in
a Project over the
+ * subquery, which gives them the raw type of the padded length.
+ */
+ private def padInSubquery(i: InSubquery, padCharCol: Boolean): InSubquery = {
+ val padded = i.values.zip(i.query.childOutputs).map {
+ case (value @ CharOperand(metadata), col) =>
+ val valueType = CharVarcharUtils.getRawType(metadata)
+ val colType = CharVarcharUtils.getRawType(col.metadata)
+ val Seq(newValue, newCol) =
CharVarcharUtils.addPaddingInStringComparison(
+ Seq(value, col), Seq(valueType, colType), padCharCol)
+ val target = for {
+ v <- valueType
+ c <- colType
+ wider <- CharVarcharUtils.widerCharType(c, v)
+ } yield wider
+ (newValue, Some(newCol).filterNot(_ eq col).map((_, target)))
+ case (value, _) => (value, None)
Review Comment:
**[P0] [P0] Pad literals used as IN-subquery values**
AstBuilder represents a literal against a subquery as InSubquery, but
literals do not match CharOperand and this fallback leaves them unchanged.
Meanwhile, the union now pads its shorter child's values to CHAR(5).
RewritePredicateSubquery subsequently builds ordinary EqualTo predicates
without another CHAR-padding pass, losing previously matching rows. Handle
foldable string values using the subquery column's CHAR length.
**Failure scenario:** With Parquet tables t3(c CHAR(3)) containing 'abc' and
t5(c CHAR(5)) containing 'x', SELECT 1 WHERE 'abc' IN (SELECT c FROM t3 UNION
ALL SELECT c FROM t5) previously returns 1. This PR returns no rows because
'abc' is compared with 'abc '.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/ApplyCharTypePadding.scala:
##########
@@ -88,10 +88,92 @@ 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 {
Review Comment:
**[P1] [P1] Pad the widest child when read-side padding is disabled**
padSetOperations also runs when readSideCharPadding=false, but
padCharToWiderLength returns None for the child whose declared length already
equals the target. That child can still contain an unpadded external value.
Only the shorter child is padded, and ReplaceIntersectWithSemiJoin later
compares the resulting unequal strings directly. Apply the target padding to
both children when scan padding is disabled.
**Failure scenario:** Create external Parquet tables t3(c CHAR(3)) and t5(c
CHAR(5)) over STRING storage containing 'a'. With
spark.sql.readSideCharPadding=false and standard semantics disabled, SELECT c
FROM t3 INTERSECT SELECT c FROM t5 previously returns one row. It now returns
none: the children produce 'a ' and 'a'. UNION DISTINCT similarly produces
two distinct rows.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/CharVarcharUtils.scala:
##########
@@ -409,23 +412,158 @@ 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.
+ */
+ def addPaddingInStringComparison(
+ exprs: Seq[Expression],
+ rawTypes: Seq[Option[DataType]],
+ alwaysPad: Boolean): 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).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.
+ */
+ def padCharToWiderLength(attr: Attribute, rawType: DataType):
Option[(Expression, DataType)] = {
+ getRawType(attr.metadata).flatMap { attrRawType =>
+ widerCharType(attrRawType, rawType).filter(_ != attrRawType).map { wider
=>
+ val padded = processStringForCharVarchar(
+ attr, wider, charFuncName = Some(READ_SIDE_PADDING), varcharFuncName
= None)
+ (padded, wider)
+ }
+ }
+ }
+
+ /**
+ * The raw type of a value with the given metadata and data type. The raw
type of a column is in
+ * its metadata, and the raw types of fields of a struct built from columns,
such as by
+ * `named_struct`, are in the metadata of the fields. None if neither has a
CHAR or VARCHAR type.
+ */
+ def getRawType(metadata: Metadata, dataType: DataType): Option[DataType] = {
+ def nested(dt: DataType): Option[DataType] = dt match {
+ case StructType(fields) =>
+ val rawFields = fields.map(f =>
getRawType(f.metadata).orElse(nested(f.dataType)))
+ if (rawFields.forall(_.isEmpty)) {
+ None
+ } else {
+ Some(StructType(fields.zip(rawFields).map { case (f, raw) =>
+ f.copy(dataType = raw.getOrElse(f.dataType), metadata =
cleanMetadata(f.metadata))
+ }))
+ }
+ case ArrayType(et, containsNull) => nested(et).map(ArrayType(_,
containsNull))
+ case _ => None
+ }
+ getRawType(metadata).orElse(nested(dataType))
+ }
+
+ /** The metadata of the first attribute, with the raw type of
[[widerCharRawType]] if any. */
+ def widerCharMetadata(attrs: Seq[Attribute]): Metadata = {
+ widerCharRawType(attrs).map(withRawType(attrs.head.metadata,
_)).getOrElse(attrs.head.metadata)
+ }
+
+ /**
+ * Narrows the CHAR columns and fields of the given expression, whose raw
type is `fromType`, that
+ * are longer than those at the same places of `toType`, by removing the
trailing spaces past the
+ * length of `toType`. Values with other characters past that length are
kept, as read-side
+ * padding keeps them. A view stores the CHAR type of its columns, which can
be shorter than the
+ * CHAR type of the same column of its query, such as for a view of a UNION
created before the
+ * union had the widest length of its children. Returns None if no column or
field is longer.
+ */
+ def narrowCharToLength(
+ expr: Expression,
+ fromType: DataType,
+ toType: DataType): Option[Expression] = {
+ narrowerCharType(fromType, toType).map { narrower =>
+ processStringForCharVarchar(
+ expr, narrower, charFuncName = Some(CHAR_TYPE_NARROWING),
varcharFuncName = None)
+ }.filterNot(_.fastEquals(expr))
+ }
+
+ // The CHAR types of toType where fromType is longer, and STRING elsewhere,
with the field names
+ // of toType. None if they are not both CHAR types, or structs and arrays of
them, of one shape.
+ private def narrowerCharType(fromType: DataType, toType: DataType):
Option[DataType] = {
+ (fromType, toType) match {
+ case (c1: CharType, c2: CharType) if c1.collationId == c2.collationId =>
+ Some(if (c1.length > c2.length) c2 else c2.toStringType)
+ case (StructType(fields1), StructType(fields2)) if fields1.length ==
fields2.length =>
+ val narrowerFields = fields1.zip(fields2).map { case (from, to) =>
+ narrowerCharType(from.dataType, to.dataType).map(dt =>
to.copy(dataType = dt))
+ }
+ if (narrowerFields.forall(_.isDefined)) {
Review Comment:
**[P1] [P1] Preserve unchanged non-CHAR fields during view narrowing**
The new nested-metadata lookup reconstructs mixed structs, but
narrowerCharType(INT, INT) returns None. Requiring every field to return Some
therefore discards narrowing for a sibling CHAR field.
SessionCatalog.castColToType restores the stored field metadata while Cast
treats the physical STRING fields as unchanged, leaving five-character values
advertised as CHAR(3). Preserve matching non-CHAR fields so the CHAR fields can
still be narrowed.
**Failure scenario:** Before upgrading, create v AS SELECT
named_struct('id', id, 'c', c) AS s FROM (SELECT id, c FROM t3 UNION ALL SELECT
id, c FROM t5), where t3.c is CHAR(3), t5.c is CHAR(5), and both contain 'a'.
After upgrading, SELECT c FROM (SELECT s.c AS c FROM v) q WHERE c = 'a' returns
no rows, losing the previously matching t3 row because the INT field prevents
narrowing.
--
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]