gengliangwang commented on code in PR #60756:
URL: https://github.com/apache/spark/pull/60756#discussion_r4652817732
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/CharVarcharUtils.scala:
##########
@@ -409,23 +437,251 @@ 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 {
+ val rawTypes = rawTypeStrings.map(s =>
CatalystSqlParser.parseDataType(s.get))
+ // Raw types can differ only in how they print, such as with the default
collation given
+ // explicitly or with other names of struct fields. They have the same
lengths already.
+ if (rawTypes.map(normalizeCharType).distinct.length == 1) {
+ None
+ } else {
+ rawTypes.map(Option(_)).reduce {
+ (left, right) => for (l <- left; r <- right; wider <-
widerCharType(l, r)) yield wider
+ }
+ }
+ }
+ }
+
+ // The type with the collation of each CHAR type given explicitly, and
without field names.
+ private def normalizeCharType(dt: DataType): DataType = dt match {
+ case c: CharType => CharType(c.length, Some(c.collationId))
+ case StructType(fields) =>
+ StructType(fields.map(f => StructField("",
normalizeCharType(f.dataType))))
+ case ArrayType(et, _) => ArrayType(normalizeCharType(et))
+ case other => other
+ }
+
+ /**
+ * 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(attr, wider,
+ charFuncName = Some(READ_SIDE_PADDING), varcharFuncName = None,
+ keepFieldNullability = true)
+ (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))
+ }
+
+ /**
+ * [[widerCharRawType]] for each position of the outputs of the children of
a set operation. A
+ * child can output a column at more than one position, and a reference to
the column can't tell
+ * them apart, so the positions that share a column in any child get one raw
type: the widest of
+ * all of them. Returns None for every position if the outputs have
different lengths.
+ */
+ def widerCharRawTypes(childOutputs: Seq[Seq[Attribute]]):
Seq[Option[DataType]] = {
+ val width = childOutputs.head.length
+ if (childOutputs.exists(_.length != width)) {
+ Seq.fill(width)(None)
+ } else {
+ val columns = childOutputs.transpose
+ // The first position of each group of positions that share a column.
+ val group = Array.tabulate(width)(identity)
+ def find(i: Int): Int = if (group(i) == i) i else find(group(i))
+ childOutputs.foreach { output =>
+ output.indices.groupBy(i => output(i).exprId).values.foreach {
positions =>
+ positions.tail.foreach(i => group(find(i)) = find(positions.head))
+ }
+ }
+ val rawTypes = columns.indices.groupBy(find).map { case (first,
positions) =>
+ first -> widerCharRawType(positions.flatMap(columns))
+ }
+ columns.indices.map(i => rawTypes(find(i)))
+ }
+ }
+
+ /**
+ * 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,
+ keepFieldNullability = true)
+ }.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.
+ // Fields of other types must be the same.
+ 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)) {
+ Some(StructType(narrowerFields.map(_.get)))
+ } else {
+ None
+ }
+ case (ArrayType(et1, _), ArrayType(et2, containsNull)) =>
+ narrowerCharType(et1, et2).map(ArrayType(_, containsNull))
+ // other fields of a struct, such as an INT next to a CHAR
+ case _ if fromType == toType && !hasChar(toType) => Some(toType)
+ case _ => None
+ }
+ }
+
+ /**
+ * The raw type of a value of the given raw type cast to `dataType`: the
CHAR and VARCHAR types
+ * of the raw type where the cast keeps a string of the same collation, and
the types of
+ * `dataType` elsewhere, with its field names. None if the types don't have
the same shape.
+ */
+ def rawTypeOfCast(rawType: DataType, dataType: DataType): Option[DataType] =
{
+ (rawType, dataType) match {
+ case (c: CharType, s: StringType) if c.collationId == s.collationId =>
Some(c)
+ case (v: VarcharType, s: StringType) if v.collationId == s.collationId
=> Some(v)
Review Comment:
**[P1] [P1] Keep widened VARCHAR constraints in cast metadata**
VarcharType extends StringType, so this branch returns VARCHAR(3) for a cast
whose target is VARCHAR(5). The new metadataOfCast calls in
WidenSetOperationTypes and SetOperationLikeResolver attach that shorter type to
the cast alias, and Union.mergeChildOutputs propagates it.
ViewHelper.prepareTable then calls getRawSchema, which trusts the metadata over
the actual VARCHAR(5) data type and stores VARCHAR(3). Reading the view inserts
a narrowing cast through SessionCatalog.castColToType; a valid five-character
value consequently raises EXCEED_LIMIT_LENGTH. Preserve metadata consistent
with the target when coercing first-class string types.
**Failure scenario:** Set
spark.sql.charVarchar.standardSemantics.enabled=true. Create Parquet tables
v3(c VARCHAR(3)) and v5(c VARCHAR(5)), inserting 'a' and 'abcde' respectively.
Execute CREATE VIEW v AS SELECT c FROM v3 UNION ALL SELECT c FROM v5. SELECT c
FROM v now fails on 'abcde'; before this commit the view stored VARCHAR(5) and
returned both values.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ApplyCharTypePaddingHelper.scala:
##########
@@ -158,33 +180,93 @@ 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.
+ // Unlike the cases above, these don't truncate values longer than their
CHAR length.
+ case b @ BinaryComparison(e @ CharScalarSubquery(metadata), lit) if
lit.foldable =>
Review Comment:
**[P1] [P1] Preserve conditional evaluation in scalar comparisons**
The new scalar-subquery case accepts any foldable operand and passes it to
padAttrLitCmp, which unconditionally calls lit.eval() at line 258. That
evaluates expressions inside unreachable conditional branches during analysis.
ConstantFolding.tryFold explicitly suppresses such failures in conditional
branches, allowing SimplifyConditionals to remove them. Scalar comparisons
previously skipped this helper, so this introduces a new failure path. Leave
the comparison unchanged when evaluating its foldable operand fails.
**Failure scenario:** With ANSI enabled and t(c CHAR(3)) containing 'a',
SELECT CASE WHEN false THEN (SELECT c FROM t) = CAST(1 / 0 AS STRING) ELSE true
END should return true. It now raises DIVIDE_BY_ZERO during analysis despite
the branch being unreachable.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/CharVarcharUtils.scala:
##########
@@ -409,23 +437,251 @@ 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 {
+ val rawTypes = rawTypeStrings.map(s =>
CatalystSqlParser.parseDataType(s.get))
+ // Raw types can differ only in how they print, such as with the default
collation given
+ // explicitly or with other names of struct fields. They have the same
lengths already.
+ if (rawTypes.map(normalizeCharType).distinct.length == 1) {
+ None
+ } else {
+ rawTypes.map(Option(_)).reduce {
+ (left, right) => for (l <- left; r <- right; wider <-
widerCharType(l, r)) yield wider
+ }
+ }
+ }
+ }
+
+ // The type with the collation of each CHAR type given explicitly, and
without field names.
+ private def normalizeCharType(dt: DataType): DataType = dt match {
+ case c: CharType => CharType(c.length, Some(c.collationId))
+ case StructType(fields) =>
+ StructType(fields.map(f => StructField("",
normalizeCharType(f.dataType))))
+ case ArrayType(et, _) => ArrayType(normalizeCharType(et))
+ case other => other
+ }
+
+ /**
+ * 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(attr, wider,
+ charFuncName = Some(READ_SIDE_PADDING), varcharFuncName = None,
+ keepFieldNullability = true)
+ (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))
+ }
+
+ /**
+ * [[widerCharRawType]] for each position of the outputs of the children of
a set operation. A
+ * child can output a column at more than one position, and a reference to
the column can't tell
+ * them apart, so the positions that share a column in any child get one raw
type: the widest of
+ * all of them. Returns None for every position if the outputs have
different lengths.
+ */
+ def widerCharRawTypes(childOutputs: Seq[Seq[Attribute]]):
Seq[Option[DataType]] = {
+ val width = childOutputs.head.length
+ if (childOutputs.exists(_.length != width)) {
+ Seq.fill(width)(None)
+ } else {
+ val columns = childOutputs.transpose
+ // The first position of each group of positions that share a column.
+ val group = Array.tabulate(width)(identity)
+ def find(i: Int): Int = if (group(i) == i) i else find(group(i))
+ childOutputs.foreach { output =>
+ output.indices.groupBy(i => output(i).exprId).values.foreach {
positions =>
+ positions.tail.foreach(i => group(find(i)) = find(positions.head))
+ }
+ }
+ val rawTypes = columns.indices.groupBy(find).map { case (first,
positions) =>
+ first -> widerCharRawType(positions.flatMap(columns))
+ }
+ columns.indices.map(i => rawTypes(find(i)))
+ }
+ }
+
+ /**
+ * 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,
+ keepFieldNullability = true)
+ }.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.
+ // Fields of other types must be the same.
+ 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)) {
+ Some(StructType(narrowerFields.map(_.get)))
+ } else {
+ None
+ }
+ case (ArrayType(et1, _), ArrayType(et2, containsNull)) =>
Review Comment:
**[P1] [P1] Preserve source array nullability while narrowing CHAR fields**
This takes containsNull from the narrowing target, which is the anchor type
for recursive CTEs. The recursive term can legitimately have nullable array
elements even when the anchor does not: UnionLoop accepts this and merges
output nullability. processStringForCharVarcharInArray uses the supplied flag
to bind its lambda, so an anchor's false flag makes the recursive lambda
non-nullable. nullSafeRebuiltStruct consequently omits its NULL guard. Under
interpreted evaluation, a NULL element is rebuilt as a non-null struct
containing NULL. Keep the source array's element nullability when selecting
narrower CHAR lengths.
**Failure scenario:** With one 'a' row in each Parquet table t3(c CHAR(3))
and t5(c CHAR(5)), set spark.sql.codegen.wholeStage=false and
spark.sql.codegen.factoryMode=NO_CODEGEN. Run: WITH RECURSIVE r(a,n) AS (SELECT
array(named_struct('c',c)),0 FROM t3 UNION ALL SELECT
array(IF(r.n=0,NULL,named_struct('c',t5.c))),r.n+1 FROM r CROSS JOIN t5 WHERE
r.n<1) SELECT n,a FROM r. The n=1 row contains [{c:NULL}] instead of [NULL].
--
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]