spark-test commented on code in PR #60756:
URL: https://github.com/apache/spark/pull/60756#discussion_r4659524997
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/Analyzer.scala:
##########
@@ -804,6 +805,9 @@ class Analyzer(
BindParameters ::
typeCoercionRules() ++
Seq(
+ // After WidenSetOperationTypes, and not part of the type coercion
rules, which also run on
+ // optimized plans.
+ PadSetOperationCharLengths,
Review Comment:
**Blocking (P1):** Placing the padding here, after the rules that rewrite a
set operation only once its children are resolved, makes a chain advance one
level per Resolution iteration: the parent waits for the child's padding, and
the padding waits for the parent's own rewrite. Reading the code, `SELECT c, b
FROM a5` followed by 100 branches of `UNION ALL SELECT c, i FROM a3` (CHAR(5)
and BIGINT against CHAR(3) and INT) needs about 100 iterations and fails with
'Max iterations (100) reached for batch Resolution', where the base branch
widened every level in the first iteration. A Spark Connect `reduce(_
unionByName _)` over DataFrames whose CHAR lengths differ hits the same limit
without any widening, and shorter chains still pay one iteration over the whole
plan per level.
**Recommended change:** Pad a set operation in the same step that rewrites
it into one that is resolved except for its CHAR lengths, as
SetOperationLikeResolver already does: when, during analysis
(AnalysisHelper.isInAnalyzer), WidenSetOperationTypes widens a Union, Intersect
or Except, ResolveUnion turns a by-name Union into a positional one,
ResolveReferences deduplicates a Union's repeated child outputs, or
DeduplicateRelations deduplicates a set operation's children, apply
SetOperationCharPadding.padChildren to the new node before the traversal moves
to its parent, and return the combined attribute mapping. Keep
PadSetOperationCharLengths for set operations that need padding and none of
these rewrites.
**Why this works:** Each set operation is then rewritten, padded and
resolved before its parent is visited in the same bottom-up traversal, so a
chain of any depth resolves in one iteration as on the base branch, while the
gate still keeps operators above an unpadded set operation unresolved.
**Risks:** The padding moves into rules that V2 writes also run on optimized
plans; the analysis-phase check keeps it off there, and a mistake in that check
would pad optimized write plans. Set operations are padded earlier within each
iteration, which changes the order in which later rules of the batch see them
but not the analyzed plan. A rule that an extension adds to the Resolution
batch and that rewrites a set operation only once its children are resolved
would still make such a chain take one iteration per level.
**Constraints:** Padding must happen only in the analysis phase. The
widening and padding mappings must be applied as one remap of the references
above.
**Verification:**
- **Regression:** A UNION ALL chain of 150 branches, the first SELECT c, b
FROM a CHAR(5) and BIGINT table and the rest SELECT c, i FROM a CHAR(3) and INT
table, analyzes and returns its rows with the default
spark.sql.analyzer.maxIterations.
- **Regression:** A chain of 150 nested by-name Unions over inputs whose
CHAR lengths differ, built as Spark Connect builds reduce of unionByName,
analyzes with the default iteration limit.
- **Regression:** A UNION ALL chain of 150 branches, the first SELECT a, b
FROM a table with two CHAR(5) columns and the rest SELECT c, c FROM a CHAR(3)
table, analyzes and returns its rows with the default
spark.sql.analyzer.maxIterations.
- **Compatibility:** The fixed-point and single-pass analyzers give the same
plans for chains of set operations that need widening and CHAR padding.
- **Compatibility:** A V2 write that needs a distribution or ordering, of a
union whose children an optimizer rule gave different CHAR metadata, writes the
values the same query returns when read.
##########
docs/sql-migration-guide.md:
##########
@@ -26,6 +26,8 @@ license: |
- Since Spark 5.0, the Spark Thrift Server refuses to start when
`hive.server2.enable.doAs` is `true` and `hive.server2.authentication` verifies
user identities (any recognized type other than `NONE`/`NOSASL`). It
impersonates the connecting user for Hive metastore calls and driver-side file
system access, but executor-side data access still runs as the server's own
service identity, so storage-level permissions are checked against the service
principal rather than the connecting user (SPARK-5159). Spark 4.4 logs a
warning for the same configuration. To restore the previous behavior, set
`spark.sql.hive.thriftServer.allowIneffectiveDoAs` to `true`. Setting
`hive.server2.enable.doAs` to `false` also starts the server, but note that it
stops impersonating metastore calls as well, so it is not a no-op.
- Since Spark 5.0, Spark requires Java 21 or later. Users who ran Spark 4.x on
Java 17 can see two differences that come from Java. The datetime pattern
letter `F` is the aligned week of month instead of the aligned day of week in
month (JDK-8282081). For example, `date_format(date '2019-12-31', 'F')` returns
`5` instead of `3`. Converting a `FLOAT` or `DOUBLE` value to a string gives
the shortest decimal that represents the value (JDK-4511638). For example,
`CAST(CAST(4567890123456789 AS FLOAT) AS STRING)` returns `4.56789E15` instead
of `4.5678899E15`. A cast from `FLOAT` or `DOUBLE` to `DECIMAL` goes through
this string, so its result can change as well. For example,
`CAST(1.0751133388005187E17D AS DECIMAL(38, 0))` returns `107511333880051870`
instead of `107511333880051872`.
+- Since Spark 5.0, a `UNION`, `INTERSECT` or `EXCEPT` of `CHAR` columns or
fields of different lengths has the widest `CHAR` length, as the SQL standard
requires, and the values of its shorter children are padded to it. Previously,
it had the `CHAR` length of its first child while the values of the other
children kept their own lengths, so a comparison with its output missed the
rows of those children, and which rows it returned depended on the order of the
children. For example, for a `CHAR(3)` column `c` of a table `t3` and a
`CHAR(5)` column `c` of a table `t5` that both contain `'a'`, `SELECT c FROM t3
UNION SELECT c FROM t5` returns one row instead of two, the `INTERSECT` of them
returns `'a '` instead of no row, and a table created from their `UNION ALL`
has a `CHAR(5)` column instead of `CHAR(3)`. A view of such a set operation
created before Spark 5.0 stores the `CHAR` length of the first child. A view
`WITH SCHEMA EVOLUTION` gets the widest length, a view `WITH SCHEMA TY
PE EVOLUTION` gets it after it is read once, when the view is updated in the
catalog, and other views keep the length they store, with the trailing spaces
past it removed from their values. A Classic DataFrame reference to a column of
the shorter first child, such as `a.union(b).select(a("c"))`, no longer
resolves, as when the type of the first child is widened; refer to the column
by name instead. To restore the previous behavior, set
`spark.sql.legacy.noCharWideningInSetOperations` to `true`.
Review Comment:
**Nit (P3):** Users upgrading aren't told that these change too, or that the
legacy flag restores them: views whose stored CHAR length is shorter than their
query's for any reason, such as a table recreated with a longer CHAR column,
are narrowed and, WITH SCHEMA TYPE EVOLUTION, updated in the catalog; recursive
CTEs return recursive-term values at the anchor's CHAR length (the PR's a3/a5
test asserts 'y '); widening casts keep CHAR and VARCHAR types, so `CREATE
TABLE x AS SELECT m FROM w3 UNION ALL SELECT m FROM w5` stores `MAP<BIGINT,
CHAR(3)>` instead of `MAP<BIGINT, STRING>`; and with
`spark.sql.readSideCharPadding=false` the reference break also hits a first
child that is already the widest. The phrase "with the trailing spaces past it
removed" is also inaccurate for values that do not fit: `charTypeNarrowing`
returns a CHAR(5) 'abcd ' read through a CHAR(3) view unchanged.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60756#discussion_r4643265460).
**Verification:**
- **Inspection:** The 5.0 migration entry describes the narrowing of views
with a shorter stored CHAR length for any reason, the recursive CTE narrowing,
the CHAR and VARCHAR types kept through widening casts, the reference break
with read-side padding off, and how narrowed values that don't fit are
returned, and names the legacy flag for them.
- **Inspection:** The narrowViewColumns comment describes every view whose
stored CHAR length is shorter than its query's.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/CharVarcharUtils.scala:
##########
@@ -409,23 +442,310 @@ 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. If they can't, a position gets its own if it doesn't pad the
shared column.
+ * 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 groupRawTypes = columns.indices.groupBy(find).map { case (first,
positions) =>
+ first -> widerCharRawType(positions.flatMap(columns))
+ }
+ // The columns that a child outputs at more than one position.
+ val sharedColumns = childOutputs.map { output =>
+ output.groupBy(_.exprId).collect { case (exprId, attrs) if
attrs.length > 1 => exprId }
+ .toSet
+ }
+ val alwaysPad = !SQLConf.get.readSideCharPadding
+ // Whether the raw type at a position pads a column that other positions
share.
+ def padsSharedColumn(position: Int, rawType: DataType): Boolean = {
+ columns(position).zip(sharedColumns).exists { case (attr, shared) =>
+ shared.contains(attr.exprId) && getRawType(attr.metadata).exists {
attrRawType =>
+ alwaysPad || !widerCharType(attrRawType,
rawType).contains(attrRawType)
+ }
+ }
+ }
+ columns.indices.map { i =>
+ // Without one raw type for the positions that share a column, such as
when another of
+ // them has a child without a raw type, a position still gets its own
if that doesn't pad
+ // the column that they share.
+ groupRawTypes(find(i)).orElse {
+ widerCharRawType(columns(i)).filterNot(padsSharedColumn(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))
+ }
+
+ /** Whether the expression narrows a value with [[narrowCharToLength]]. */
+ def isNarrowing(e: Expression): Boolean = e.exists {
+ case s: StaticInvoke =>
+ s.functionName == CHAR_TYPE_NARROWING && s.staticObject ==
classOf[CharVarcharCodegenUtils]
+ case _ => false
+ }
+
+ // 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
+ }
+ // The value narrowed is of fromType, so its elements are as nullable as
there.
+ case (ArrayType(et1, containsNull), ArrayType(et2, _)) =>
+ 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 {
+ // A CHAR or VARCHAR type of its own, under first-class CHAR and VARCHAR
types, is the type.
+ case (_, t: CharType) => Some(t)
+ case (_, t: VarcharType) => Some(t)
+ case (c: CharType, s: StringType) if c.collationId == s.collationId =>
Some(c)
+ case (v: VarcharType, s: StringType) if v.collationId == s.collationId
=> Some(v)
+ case (StructType(rawFields), StructType(fields)) if rawFields.length ==
fields.length =>
+ val castFields = rawFields.zip(fields).map { case (rawField, field) =>
+ rawTypeOfCast(rawField.dataType, field.dataType).map(dt =>
field.copy(dataType = dt))
+ }
+ if (castFields.forall(_.isDefined))
Some(StructType(castFields.map(_.get))) else None
+ case (ArrayType(rawElementType, _), ArrayType(elementType,
containsNull)) =>
+ rawTypeOfCast(rawElementType, elementType).map(ArrayType(_,
containsNull))
+ case (MapType(rawKeyType, rawValueType, _), MapType(keyType, valueType,
valueContainsNull)) =>
+ for {
+ k <- rawTypeOfCast(rawKeyType, keyType)
+ v <- rawTypeOfCast(rawValueType, valueType)
+ } yield MapType(k, v, valueContainsNull)
+ case (_: StructType | _: ArrayType | _: MapType, _) => None
+ case (_, other) => Some(other)
+ }
+ }
+
+ /**
+ * The metadata of the alias of a value with the given metadata cast to
`dataType`, such as a
+ * widening cast of a child of a set operation, which an alias of a cast
would otherwise lose: the
+ * raw type of the cast value, see [[rawTypeOfCast]]. None if the cast keeps
no CHAR or VARCHAR
+ * type.
+ */
+ def metadataOfCast(metadata: Metadata, dataType: DataType): Option[Metadata]
= {
+ getRawType(metadata).flatMap(rawTypeOfCast(_,
dataType)).filter(hasCharVarchar)
+ .map(withRawType(Metadata.empty, _))
+ }
+
+ /**
+ * For each position of the outputs of the children of a set operation cast
to the given types
+ * (None for no cast), whether a cast keeps the CHAR and VARCHAR types of
the value, see
+ * [[metadataOfCast]]. Only where each child has a raw type, and the raw
types after the casts are
+ * the same or can be widened to one, so that the set operation pads the
children to the same
+ * lengths; and only if `enabled`, as the set operation pads them, see
SetOperationCharPadding.
+ * Elsewhere, the output would keep the raw type of the first child for
values that don't have it.
+ */
+ def keepsCharTypesInCast(
+ childOutputs: Seq[Seq[Attribute]],
+ targetTypes: Seq[Option[DataType]],
+ enabled: Boolean): Seq[Boolean] = {
+ childOutputs.transpose.zip(targetTypes).map { case (attrs, targetType) =>
+ val castTypes = attrs.map { attr =>
Review Comment:
**Nit (P3):** `castTypes` parses every raw-typed attribute with
`CatalystSqlParser` before `enabled` is checked, and also at positions with no
target type, whose results the callers never read; `narrowViewColumns` in
ApplyCharTypePadding.scala does the same for every CHAR or VARCHAR column of
every view in every query. A query over a view of a table with 200 VARCHAR
columns parses 400 raw-type strings per analysis although no VARCHAR column can
be narrowed, also with `spark.sql.legacy.noCharWideningInSetOperations=true`.
Checking `enabled`, the target type and whether the raw-type strings differ
before parsing gives the same results.
**Verification:**
- **Behavior:** A view over a table with unchanged CHAR and VARCHAR columns
returns the same values, and a view whose stored CHAR length is shorter than
its query's is still narrowed.
- **Behavior:** A widened set operation keeps or drops CHAR and VARCHAR
types in its casts as before, with
spark.sql.legacy.noCharWideningInSetOperations set to true and to false.
- **Inspection:** keepsCharTypesInCast checks `enabled` and the target type
before parsing, and narrowViewColumns compares the raw-type strings before
parsing.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/SetOperationCharPadding.scala:
##########
@@ -0,0 +1,178 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.catalyst.analysis
+
+import scala.collection.mutable
+
+import org.apache.spark.sql.catalyst.expressions.{Alias, Attribute,
Expression, ExprId, NamedExpression}
+import org.apache.spark.sql.catalyst.plans.logical.{AnalysisHelper,
CTERelationRef, Except, Intersect, LogicalPlan, Project, SetOperation, Union,
UnionLoop, UnionLoopRef}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.util.CharVarcharUtils
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.DataType
+
+/**
+ * The SQL standard gives a set operation of CHAR(n) and CHAR(m) the length
max(n, m). When the
+ * children of a Union, Intersect or Except have CHAR columns or fields of
different lengths at
+ * the same position, this pads the values of the shorter children to the
widest length, in a
+ * Project over each child that needs it, as
[[TypeCoercionBase.WidenSetOperationTypes]] casts
+ * them to the widest type. The output of the set operation, which comes from
its first child,
+ * then has the widest length. Like read-side padding, the padding does not
truncate longer values.
+ *
+ * During analysis, such a set operation is not resolved until its children
are padded, see
+ * [[isAligned]], so that nothing above it is resolved with the shorter length
of its first child.
+ * The children are padded once the set operation is resolved otherwise, after
the widening of
+ * their types and the deduplication of their output: in
[[PadSetOperationCharLengths]] by the
+ * fixed-point analyzer, and in `SetOperationLikeResolver` by the single-pass
resolver, both with
+ * [[padChildren]].
+ */
+object SetOperationCharPadding {
+
+ /**
+ * Whether the CHAR lengths of the children of a set operation are the same
at each position, so
+ * that it needs no padding. Only analysis pads the children, so outside of
it, see
+ * [[AnalysisHelper.isInAnalyzer]], this is true: an optimizer rule can make
the metadata of the
+ * children differ, such as one that simplifies an expression into a column,
whose alias then
+ * has the column's raw type. True if the children are not resolved yet.
+ */
+ def isAligned(children: Seq[LogicalPlan]): Boolean =
+ !AnalysisHelper.isInAnalyzer || !needsPadding(children)
+
+ /** Whether the resolved children of a set operation have CHAR lengths to
pad. */
+ def needsPadding(children: Seq[LogicalPlan]): Boolean = {
+ children.forall(_.resolved) &&
+ widerCharRawTypes(children, children.map(_.output)).exists(_.isDefined)
+ }
+
+ /**
+ * Pads the columns of the children of a set operation that have CHAR
lengths shorter than the
+ * widest at their position, see [[CharVarcharUtils.widerCharRawTypes]].
Without read-side
+ * padding, the values of the widest children can be shorter too, so they
are padded as well.
+ * `newAlias` builds the alias of a padded column from the padded value, the
column, and the
+ * raw type of the padded value. Returns the children and their outputs,
which are the given
+ * ones if no column needs padding.
+ */
+ def padChildren(
+ children: Seq[LogicalPlan],
+ childOutputs: Seq[Seq[Attribute]],
+ newAlias: (Expression, Attribute, DataType) => Alias)
+ : (Seq[LogicalPlan], Seq[Seq[Attribute]]) = {
+ val rawTypes = widerCharRawTypes(children, childOutputs)
+ if (rawTypes.forall(_.isEmpty)) {
+ (children, childOutputs)
+ } else {
+ val alwaysPad = !SQLConf.get.readSideCharPadding
+ children.zip(childOutputs).map { case (child, output) =>
+ // 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 = output.zip(rawTypes).map {
+ case (attr, Some(rawType)) =>
+ paddedColumns.getOrElseUpdate(attr.exprId,
+ CharVarcharUtils.padCharToWiderLength(attr, rawType,
alwaysPad).map {
+ case (padded, paddedRawType) => newAlias(padded, attr,
paddedRawType)
+ }.getOrElse(attr))
+ case (attr, None) => attr
+ }
+ if (projectList == output) {
+ (child, output)
+ } else {
+ (Project(projectList, child), projectList.map(_.toAttribute))
+ }
+ }.unzip
+ }
+ }
+
+ /** The alias of a padded column for the fixed-point analyzer. */
+ def newAlias(padded: Expression, attr: Attribute, rawType: DataType): Alias
= {
+ Alias(padded, attr.name)(
+ qualifier = attr.qualifier,
+ explicitMetadata = Some(CharVarcharUtils.withRawType(attr.metadata,
rawType)))
+ }
+
+ // The raw types with the widest CHAR lengths at each position, or None for
every position of a
+ // set operation that reads a recursive reference.
+ private def widerCharRawTypes(
+ children: Seq[LogicalPlan],
+ childOutputs: Seq[Seq[Attribute]]): Seq[Option[DataType]] = {
+ def none = Seq.fill(childOutputs.head.length)(None)
+ if (!isEnabled) {
+ none
+ } else {
+ val rawTypes = CharVarcharUtils.widerCharRawTypes(childOutputs)
+ // Most set operations need no padding, so the plan is only walked when
one does.
+ if (rawTypes.exists(_.isDefined) &&
children.exists(readsRecursiveReference)) {
Review Comment:
**Blocking (P1):** This exemption is decided from the plan's shape, and the
shape changes at execution: `UnionLoopExec` substitutes each iteration's rows
for the `UnionLoopRef` in the optimized recursive term and runs it with
`Dataset.ofRows`, the rebuilt nodes aren't marked analyzed, and the analysis
pads the union because no recursive reference is left to exempt it. Reading the
code, `WITH RECURSIVE r(c, n) AS (SELECT c, 0 FROM t3 UNION ALL SELECT c, n + 1
FROM (SELECT c, n FROM r UNION ALL SELECT c, id FROM t5) WHERE n < 2) SELECT n
FROM r WHERE c = 'a'`, with t3 holding ('a', 1) and t5 holding ('a', 10),
returns {0}, or no row once the final union of the iteration results is padded
too, instead of the base branch's {0, 1, 2}, because the outer literal was
padded to 'a ' while the recursive rows become 'a '. The PR's test of this
shape filters the t5 branch with a constant that the optimizer prunes, so it
observes neither effect.
This extends existing discussions
[1](https://github.com/apache/spark/pull/60756#discussion_r4646391549),
[2](https://github.com/apache/spark/pull/60756#discussion_r4652060901).
See **Shared repair plan 1** in the review body.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/SetOperationCharPadding.scala:
##########
@@ -0,0 +1,178 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.catalyst.analysis
+
+import scala.collection.mutable
+
+import org.apache.spark.sql.catalyst.expressions.{Alias, Attribute,
Expression, ExprId, NamedExpression}
+import org.apache.spark.sql.catalyst.plans.logical.{AnalysisHelper,
CTERelationRef, Except, Intersect, LogicalPlan, Project, SetOperation, Union,
UnionLoop, UnionLoopRef}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.util.CharVarcharUtils
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.DataType
+
+/**
+ * The SQL standard gives a set operation of CHAR(n) and CHAR(m) the length
max(n, m). When the
+ * children of a Union, Intersect or Except have CHAR columns or fields of
different lengths at
+ * the same position, this pads the values of the shorter children to the
widest length, in a
+ * Project over each child that needs it, as
[[TypeCoercionBase.WidenSetOperationTypes]] casts
+ * them to the widest type. The output of the set operation, which comes from
its first child,
+ * then has the widest length. Like read-side padding, the padding does not
truncate longer values.
+ *
+ * During analysis, such a set operation is not resolved until its children
are padded, see
+ * [[isAligned]], so that nothing above it is resolved with the shorter length
of its first child.
+ * The children are padded once the set operation is resolved otherwise, after
the widening of
+ * their types and the deduplication of their output: in
[[PadSetOperationCharLengths]] by the
+ * fixed-point analyzer, and in `SetOperationLikeResolver` by the single-pass
resolver, both with
+ * [[padChildren]].
+ */
+object SetOperationCharPadding {
+
+ /**
+ * Whether the CHAR lengths of the children of a set operation are the same
at each position, so
+ * that it needs no padding. Only analysis pads the children, so outside of
it, see
+ * [[AnalysisHelper.isInAnalyzer]], this is true: an optimizer rule can make
the metadata of the
+ * children differ, such as one that simplifies an expression into a column,
whose alias then
+ * has the column's raw type. True if the children are not resolved yet.
+ */
+ def isAligned(children: Seq[LogicalPlan]): Boolean =
+ !AnalysisHelper.isInAnalyzer || !needsPadding(children)
+
+ /** Whether the resolved children of a set operation have CHAR lengths to
pad. */
+ def needsPadding(children: Seq[LogicalPlan]): Boolean = {
+ children.forall(_.resolved) &&
+ widerCharRawTypes(children, children.map(_.output)).exists(_.isDefined)
+ }
+
+ /**
+ * Pads the columns of the children of a set operation that have CHAR
lengths shorter than the
+ * widest at their position, see [[CharVarcharUtils.widerCharRawTypes]].
Without read-side
+ * padding, the values of the widest children can be shorter too, so they
are padded as well.
+ * `newAlias` builds the alias of a padded column from the padded value, the
column, and the
+ * raw type of the padded value. Returns the children and their outputs,
which are the given
+ * ones if no column needs padding.
+ */
+ def padChildren(
+ children: Seq[LogicalPlan],
+ childOutputs: Seq[Seq[Attribute]],
+ newAlias: (Expression, Attribute, DataType) => Alias)
+ : (Seq[LogicalPlan], Seq[Seq[Attribute]]) = {
+ val rawTypes = widerCharRawTypes(children, childOutputs)
+ if (rawTypes.forall(_.isEmpty)) {
+ (children, childOutputs)
+ } else {
+ val alwaysPad = !SQLConf.get.readSideCharPadding
+ children.zip(childOutputs).map { case (child, output) =>
+ // 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 = output.zip(rawTypes).map {
+ case (attr, Some(rawType)) =>
+ paddedColumns.getOrElseUpdate(attr.exprId,
+ CharVarcharUtils.padCharToWiderLength(attr, rawType,
alwaysPad).map {
+ case (padded, paddedRawType) => newAlias(padded, attr,
paddedRawType)
+ }.getOrElse(attr))
+ case (attr, None) => attr
+ }
+ if (projectList == output) {
+ (child, output)
+ } else {
+ (Project(projectList, child), projectList.map(_.toAttribute))
+ }
+ }.unzip
+ }
+ }
+
+ /** The alias of a padded column for the fixed-point analyzer. */
+ def newAlias(padded: Expression, attr: Attribute, rawType: DataType): Alias
= {
+ Alias(padded, attr.name)(
+ qualifier = attr.qualifier,
+ explicitMetadata = Some(CharVarcharUtils.withRawType(attr.metadata,
rawType)))
+ }
+
+ // The raw types with the widest CHAR lengths at each position, or None for
every position of a
+ // set operation that reads a recursive reference.
+ private def widerCharRawTypes(
+ children: Seq[LogicalPlan],
+ childOutputs: Seq[Seq[Attribute]]): Seq[Option[DataType]] = {
+ def none = Seq.fill(childOutputs.head.length)(None)
+ if (!isEnabled) {
+ none
+ } else {
+ val rawTypes = CharVarcharUtils.widerCharRawTypes(childOutputs)
+ // Most set operations need no padding, so the plan is only walked when
one does.
+ if (rawTypes.exists(_.isDefined) &&
children.exists(readsRecursiveReference)) {
+ none
+ } else {
+ rawTypes
+ }
+ }
+ }
+
+ /**
+ * Whether set operations of CHAR columns of different lengths have the
widest length. Not in the
+ * legacy mode where CHAR is a STRING, in which ApplyCharTypePadding pads
nothing either, or
+ * with [[SQLConf.LEGACY_NO_CHAR_WIDENING_IN_SET_OPERATIONS]].
+ */
+ def isEnabled: Boolean = {
+ val conf = SQLConf.get
+ !(conf.charVarcharAsString && !conf.charVarcharStandardSemantics) &&
+ !conf.getConf(SQLConf.LEGACY_NO_CHAR_WIDENING_IN_SET_OPERATIONS)
+ }
+
+ /**
+ * Whether the plan reads the recursive reference of a recursive CTE that it
is not part of,
Review Comment:
**Nit (P3):** This says 'a recursive CTE that it is not part of', but the
method below returns `false` at a `UnionLoop` and `true` for a recursive
reference whose `UnionLoop` the plan does not contain, that is for a plan that
is part of the CTE's definition, like the example on the next line. A reader of
this guard gets its condition backwards.
See **Shared repair plan 1** in the review body.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/CharVarcharUtils.scala:
##########
@@ -409,23 +442,310 @@ 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. If they can't, a position gets its own if it doesn't pad the
shared column.
+ * 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 groupRawTypes = columns.indices.groupBy(find).map { case (first,
positions) =>
+ first -> widerCharRawType(positions.flatMap(columns))
+ }
+ // The columns that a child outputs at more than one position.
+ val sharedColumns = childOutputs.map { output =>
+ output.groupBy(_.exprId).collect { case (exprId, attrs) if
attrs.length > 1 => exprId }
+ .toSet
+ }
+ val alwaysPad = !SQLConf.get.readSideCharPadding
+ // Whether the raw type at a position pads a column that other positions
share.
+ def padsSharedColumn(position: Int, rawType: DataType): Boolean = {
+ columns(position).zip(sharedColumns).exists { case (attr, shared) =>
+ shared.contains(attr.exprId) && getRawType(attr.metadata).exists {
attrRawType =>
+ alwaysPad || !widerCharType(attrRawType,
rawType).contains(attrRawType)
+ }
+ }
+ }
+ columns.indices.map { i =>
+ // Without one raw type for the positions that share a column, such as
when another of
+ // them has a child without a raw type, a position still gets its own
if that doesn't pad
+ // the column that they share.
+ groupRawTypes(find(i)).orElse {
+ widerCharRawType(columns(i)).filterNot(padsSharedColumn(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))
+ }
+
+ /** Whether the expression narrows a value with [[narrowCharToLength]]. */
+ def isNarrowing(e: Expression): Boolean = e.exists {
+ case s: StaticInvoke =>
+ s.functionName == CHAR_TYPE_NARROWING && s.staticObject ==
classOf[CharVarcharCodegenUtils]
+ case _ => false
+ }
+
+ // 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)
Review Comment:
**Blocking (P1):** For a recursive-term CHAR type shorter than the anchor's,
this returns the anchor's STRING type, so `narrowCharToLength` returns None and
`narrowRecursiveTerms` leaves the shorter values as they are. Now that the
anchor's set operation is padded to its widest length, that case is common.
Reading the code, with t3(id INT, c CHAR(3)) holding (1, 'a') and t5(id INT, c
CHAR(5)) holding (2, 'a'), `WITH RECURSIVE r(id, c, n) AS (SELECT id, c, 0 FROM
(SELECT id, c FROM t3 UNION ALL SELECT id, c FROM t5) UNION ALL SELECT t3.id,
t3.c, r.n + 1 FROM r JOIN t3 ON r.id = t3.id WHERE r.c = 'a' AND r.n < 3)
SELECT id, n FROM r` produces (1, 'a ', 1) in iteration 1, and iteration 2
compares 'a ' with the literal padded to 'a ', so (1, 2) and (1, 3), which
the base branch returned, are lost.
**Recommended change:** Let ApplyCharTypePadding.narrowRecursiveTerms bring
every CHAR value of the recursive term to the anchor's CHAR length in both
directions: where the recursive term's CHAR type at a position is shorter than
the anchor's, wrap the value in charTypeNarrowing as well, whose first branch
pads a value that fits to the limit. Do it through a mode that only
narrowRecursiveTerms uses, such as a parameter of narrowerCharType that keeps
the target CHAR type whenever the lengths differ, so the view narrowing keeps
its current behavior. Add recursive CTE tests with a filter and a join on the
recursive reference's CHAR column.
**Why this works:** Every value that leaves the recursive term then has the
anchor's CHAR length, in either direction, so comparisons and joins padded to
the CTE's lengths match the rows of every iteration, and the iteration results
that UnionLoopExec unions have the anchor's raw types.
**Risks:** Recursive CTEs whose anchor reads a longer CHAR column directly
and whose recursive term reads a shorter one, which already compared those
values wrongly on the base branch, now get padded recursive values too, so
their results change; spark.sql.legacy.noCharWideningInSetOperations turns the
narrowing, and with it this padding, off. The recursion of such CTEs gains a
padding projection, a per-row cost only on those queries.
**Constraints:** The view narrowing must keep its current behavior for views
whose query has a shorter CHAR length than they store.
**Exclusions:**
- Views whose query has a shorter CHAR length than they store keep their
current values; padding them is a separate change.
**Verification:**
- **Regression:** A recursive CTE whose anchor is a UNION ALL of a CHAR(3)
and a CHAR(5) column, and whose recursive term joins the recursive reference
with the CHAR(3) table and filters it with c = 'a', returns the rows of every
iteration, not only of the first.
- **Regression:** The same recursive term joining the recursive reference's
CHAR column with a CHAR(5) column returns the joined rows of every iteration.
- **Compatibility:** A recursive term whose CHAR values are longer than the
anchor's is still narrowed to the anchor's length, and a view whose stored CHAR
length differs from its query's returns the same values as before.
- **Behavior:** A recursive CTE whose anchor reads a CHAR(5) column and
whose recursive term reads a CHAR(3) column returns its recursive rows padded
to 5 characters, which a filter on the CTE's column matches.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/CharVarcharUtils.scala:
##########
@@ -409,23 +442,310 @@ 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. If they can't, a position gets its own if it doesn't pad the
shared column.
+ * 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 groupRawTypes = columns.indices.groupBy(find).map { case (first,
positions) =>
Review Comment:
**Non-blocking (P2):** Grouping positions by shared column gives them one
CHAR length even when their own children differ. Reading the code, `SELECT *
FROM (SELECT c, c FROM t3 INTERSECT SELECT c3, c5 FROM t35) s(p, q)` types p as
CHAR(5) with 'a ', while the same query with UNION ALL types p as CHAR(3)
with 'a ', although both children of p are CHAR(3); the PR's test asserts
exactly this split. A CTAS or view then stores the wider type and `length()`
sees the extra spaces, though which rows match is unchanged. Because the set
operation stays unresolved until it is padded, nothing above it refers to the
repeated column yet, so the first child could output `[c, readSidePadding(c, 5)
AS c#new]` and keep each position's own length.
This extends existing discussions
[1](https://github.com/apache/spark/pull/60756#issuecomment-7048669373),
[2](https://github.com/apache/spark/pull/60756#discussion_r4646391535),
[3](https://github.com/apache/spark/pull/60756#discussion_r4653538072).
See **Shared repair plan 2** in the review body.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/CharVarcharUtils.scala:
##########
@@ -409,23 +442,310 @@ 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. If they can't, a position gets its own if it doesn't pad the
shared column.
+ * 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 =>
Review Comment:
**Non-blocking (P2):** `output(i)` here, `columns(i)` and
`positions.flatMap(columns)` index Lists by position inside loops, since a
parser-built binary `Union` has List children and `transpose` then yields List
columns, which makes the check quadratic in the width; it runs for every set
operation, CHAR columns or not, in every Resolution iteration and in each new
instance's `resolved`. There is also no exit when no attribute has a raw type,
differing VARCHAR strings are parsed per child and again in the single-position
fallback, and `needsPadding` materializes every position. The review's
standalone model of this loop, not a Spark run, estimates about 173 ms per
evaluation for a UNION ALL of two 10000-column SELECTs against about 4.5 ms for
the base branch's checks; narrow set operations are not measurably affected.
Indexed access, an early exit and one parse per distinct string give the same
results.
**Verification:**
- **Behavior:** For set operations with no raw types, with mixed CHAR and
VARCHAR raw types, with VARCHAR lengths that differ, with structs and arrays of
CHAR fields and with repeated columns, the check returns the same per-position
raw types as before.
- **Inspection:** The check reads child outputs and columns by position in
constant time, returns before any parsing when the first child has no raw-typed
attribute, and parses each distinct raw-type string at most once.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala:
##########
@@ -8466,6 +8466,19 @@ object SQLConf {
.booleanConf
.createWithDefault(false)
+ val LEGACY_NO_CHAR_WIDENING_IN_SET_OPERATIONS =
Review Comment:
**Non-blocking (P2):** This flag is a session conf that isn't in
`OffsetSeqMetadata.relevantSQLConfs` and that
`StreamingQueryManager.createQuery` does not apply when it analyzes a restored
query, as it does for `ALLOW_EXCEPT_ON_STREAMING_DATAFRAME`. Reading the code,
a `dropDuplicates("c")` over
`spark.readStream.table("t3").select("c").union(spark.readStream.table("t5").select("c"))`
started on the base branch stores the key 'b ' for a 'b' from t3; restarted
on this PR from the same checkpoint, the union pads t3's values to 'b ', so
the next 'b' from t3 matches no stored key and is emitted again, and a running
count by c starts a new group at zero. This assumes, as file-source tables do,
that the streaming relation carries the table's CHAR raw types; the migration
guide says nothing about streaming.
**Recommended change:** Add spark.sql.legacy.noCharWideningInSetOperations
to OffsetSeqMetadata.relevantSQLConfs, with true as its value for checkpoints
that predate it, so new checkpoints record the session's value. Mark each set
operation whose children the CHAR padding pads, for example with a tree-node
tag set wherever the padding is applied. When createQuery restores a query
whose recorded value differs from the session's (a checkpoint that predates the
flag counts as recording true), and its analyzed plan has a streaming set
operation that the padding changed (marked) or that the recorded value would
pad (its children's CHAR lengths still differ): if the DataFrame's unanalyzed
plan, df.queryExecution.logical, still holds that set operation unanalyzed, as
for a query written as one SQL statement or sent as a Spark Connect plan,
analyze it in a session clone with the recorded value, as createQuery already
does for ALLOW_EXCEPT_ON_STREAMING_DATAFRAME, and run that plan; otherwi
se, as for a Classic DataFrame whose set operation was analyzed when union()
or a sibling was called, fail the start with an error that names the flag and
the recorded value and says to set the flag to that value before building the
DataFrame, or to start the query from a new checkpoint. Add a sentence on
restarted streaming queries to the set-operation migration entry.
**Why this works:** A restored query's set operations then either get the
padding its checkpoint recorded, through a fresh analysis under the recorded
value, or the query fails at start with an error that names the flag, so its
stateful operators never key on values padded differently from their stored
state; a query started after the change records the session's value and keeps
that behavior across restarts.
**Risks:** Restored Classic DataFrame queries whose set operations the
padding changed fail at start after the upgrade until users set the flag to the
recorded value before building the DataFrame or start from a new checkpoint;
the error names both. The fresh analysis at start can give a different plan
than the DataFrame's if the tables or views it reads changed between defining
and starting the query, as for any re-analysis. Queries restored from old
checkpoints keep the base branch's set-operation behavior, including its missed
comparisons, until they start from a new checkpoint. The mark has to survive
the analyzer rules that run after the padding and the copies they make; a lost
mark lets such a restart run with keys padded differently from its state, as it
does now.
**Constraints:** The recorded value must apply wherever the restored query's
set operations are analyzed, not only to execution-time confs. The mark must be
set wherever the padding is applied, including any rule that pads a set
operation in the same step as widening or deduplication.
**Exclusions:**
- The subquery padding is not pinned, because IN-subquery and
scalar-subquery comparisons do not key streaming state.
**Verification:**
- **Regression:** A streaming dropDuplicates over such a union, written as
one SQL statement and restarted from a checkpoint whose offset log lacks the
flag, emits no duplicate for a key that the shorter child produced before the
restart.
- **Regression:** The same query built with Classic union() and restarted
from that checkpoint fails at start with an error that names the flag, and with
the flag set to true before the DataFrame is built it emits no duplicate.
- **Behavior:** A query started after the change records the flag's value in
its offset log, and restarting it keeps the widest CHAR length of its set
operations.
- **Compatibility:** Restarting a streaming query without set operations, or
one whose set operations the padding did not change, from an old checkpoint
gives the same plan and results as before.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/rules.scala:
##########
@@ -630,7 +630,22 @@ object ViewSyncSchemaToMetaStore extends (LogicalPlan =>
Unit) {
viewSchemaMode == SchemaEvolution && viewFields.length !=
viewQueryFields.length
val fieldNames = viewQuery.schema.fieldNames
- val redo = redoSignature || viewFields.zipWithIndex.exists { case
(field, index) =>
+ // A column that ApplyCharTypePadding narrowed to the CHAR type the
view stores, as the
+ // CHAR type of its query is now wider, evolves to the CHAR type of
the query.
+ val evolvedRawTypes: Map[Int, DataType] = (viewSchemaMode, viewQuery)
match {
+ case (SchemaTypeEvolution, Project(projectList, _)) =>
Review Comment:
**Nit (P3):** `evolvedRawTypes` is computed only for `SchemaTypeEvolution`,
and `schemaChanged` compares data types, nullability, names and comments but
not the CHAR raw type, so a `WITH SCHEMA EVOLUTION` view of `SELECT c FROM t3
UNION ALL SELECT c FROM t5` stored before 5.0 returns c as CHAR(5) while
`DESCRIBE TABLE` and the catalog keep CHAR(3) until some other schema change
rewrites it. The migration note says such a view 'gets the widest length'.
See **Shared repair plan 3** in the review body.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/SetOperationCharPadding.scala:
##########
@@ -0,0 +1,178 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.catalyst.analysis
+
+import scala.collection.mutable
+
+import org.apache.spark.sql.catalyst.expressions.{Alias, Attribute,
Expression, ExprId, NamedExpression}
+import org.apache.spark.sql.catalyst.plans.logical.{AnalysisHelper,
CTERelationRef, Except, Intersect, LogicalPlan, Project, SetOperation, Union,
UnionLoop, UnionLoopRef}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.util.CharVarcharUtils
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.DataType
+
+/**
+ * The SQL standard gives a set operation of CHAR(n) and CHAR(m) the length
max(n, m). When the
+ * children of a Union, Intersect or Except have CHAR columns or fields of
different lengths at
+ * the same position, this pads the values of the shorter children to the
widest length, in a
+ * Project over each child that needs it, as
[[TypeCoercionBase.WidenSetOperationTypes]] casts
+ * them to the widest type. The output of the set operation, which comes from
its first child,
+ * then has the widest length. Like read-side padding, the padding does not
truncate longer values.
+ *
+ * During analysis, such a set operation is not resolved until its children
are padded, see
+ * [[isAligned]], so that nothing above it is resolved with the shorter length
of its first child.
+ * The children are padded once the set operation is resolved otherwise, after
the widening of
+ * their types and the deduplication of their output: in
[[PadSetOperationCharLengths]] by the
+ * fixed-point analyzer, and in `SetOperationLikeResolver` by the single-pass
resolver, both with
+ * [[padChildren]].
+ */
+object SetOperationCharPadding {
+
+ /**
+ * Whether the CHAR lengths of the children of a set operation are the same
at each position, so
+ * that it needs no padding. Only analysis pads the children, so outside of
it, see
+ * [[AnalysisHelper.isInAnalyzer]], this is true: an optimizer rule can make
the metadata of the
+ * children differ, such as one that simplifies an expression into a column,
whose alias then
+ * has the column's raw type. True if the children are not resolved yet.
+ */
+ def isAligned(children: Seq[LogicalPlan]): Boolean =
+ !AnalysisHelper.isInAnalyzer || !needsPadding(children)
Review Comment:
**Non-blocking (P2):** The gate here reads `isEnabled`, through
`needsPadding`, from whatever conf is current when a set operation's lazy
`resolved` is first computed. A view created while
`spark.sql.legacy.charVarcharAsString` or
`spark.sql.legacy.noCharWideningInSetOperations` was true keeps that value for
its body when the caller doesn't set the key, so `CREATE VIEW v AS WITH u AS
(SELECT c FROM t3 UNION ALL SELECT c FROM t5) SELECT a.c FROM u a JOIN u b ON
a.c = b.c` over CHAR(3) and CHAR(5) columns analyzes its union unpadded.
Reading the code, a session without the flag then fails to read the view with
INTERNAL_ERROR 'Found the unresolved operator', because CheckAnalysis inlines
`u` twice under the caller's conf and the copy of the union computes `resolved`
as needing padding. The base branch reads the view.
This extends existing discussions
[1](https://github.com/apache/spark/pull/60756#discussion_r4652060894),
[2](https://github.com/apache/spark/pull/60756#discussion_r4652060910).
**Recommended change:** Run the body of CheckAnalysis.checkAnalysis, its CTE
inlining and its checks, inside AnalysisHelper.markOutsideAnalyzer, so that the
CHAR gate on resolved, which only keeps analyzer rules from resolving the
operators above a set operation before it is padded, does not apply while a
plan is checked. This covers the eager check that ViewResolution.resolve runs
on a view body and the SimpleAnalyzer.checkAnalysis calls after a SQL function
body is resolved, which run under the caller's conf after the body was analyzed
under its captured configs, and the query's final check, which inlines the same
CTEs again. Add view and SQL function tests.
**Why this works:** A copy that a check's CTE inlining makes of a set
operation that its body's configs left unpadded then computes resolved outside
the analysis phase, where the gate is off, so it is resolved as on the base
branch, while operators whose resolved was computed during analysis keep that
value.
**Risks:** A set operation whose resolved is first computed by a check, such
as the root of a query, is no longer reported by the final check when it still
needs CHAR padding; PadSetOperationCharLengths pads every such set operation
during analysis, so this only hides a padding bug, and operators above an
unpadded set operation still fail the check. Checks no longer run inside the
analysis phase, so the test-only assertNotAnalysisRule no longer applies to
code that a check runs.
**Constraints:** The gate must still apply to every analyzer rule, so that
no operator above an unpadded set operation is resolved during analysis.
**Verification:**
- **Regression:** Reading such a view from a session without the flag
returns its rows instead of failing with 'Found the unresolved operator', both
when the view is the whole query and when another query selects from it.
- **Regression:** Calling such a SQL function from a session without the
flag returns its rows.
- **Compatibility:** A view whose body has an unresolvable operator still
fails eagerly with the same error.
##########
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/rules.scala:
##########
@@ -656,6 +673,9 @@ object ViewSyncSchemaToMetaStore extends (LogicalPlan =>
Unit) {
try {
session.sessionState.catalog.alterTable(updatedViewMeta)
} catch {
+ // The narrowing keeps the values of the query as the stored CHAR
types say, so a view
+ // whose only change is the CHAR types it evolves to is still read
correctly.
+ case NonFatal(_) if !schemaChanged =>
Review Comment:
**Nit (P3):** This drops the failure with no log, so when `alterTable` keeps
failing, for a reader without ALTER privilege or on a read-only catalog, every
SELECT or EXPLAIN on such a view repeats the write, the view keeps its old CHAR
type, and neither the user nor an operator gets a message explaining it. The
read itself stays correct, since the narrowing returns the stored lengths, and
the `ve` view test only exercises a successful update.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60756#issuecomment-7064885909).
See **Shared repair plan 3** in the review body.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ApplyCharTypePaddingHelper.scala:
##########
@@ -158,33 +167,142 @@ 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.
+ // A comparison of types that don't match is left to CheckAnalysis.
+ // As in ConstantFolding, a constant that fails to evaluate, such as one
in a branch that is
+ // never evaluated, is left to the evaluation of the query.
+ case b @ BinaryComparison(e @ CharScalarSubquery(metadata), lit)
Review Comment:
**Non-blocking (P2):** This case and the IN-list and `InSubquery` cases
after it read no flag, while `spark.sql.legacy.noCharWideningInSetOperations`
is read only by `SetOperationCharPadding.isEnabled`. Reading the code, with
t3(id INT, c CHAR(3)) and t5(id INT, c CHAR(5)) each holding 'a' and the legacy
flag set, `SELECT id FROM t3 WHERE c IN (SELECT c FROM t5)` still returns 1 and
`SELECT id FROM t5 WHERE c = (SELECT c FROM t3)` still returns 2, where the
base branch returns no rows; only the CHAR-as-STRING mode, which drops all CHAR
semantics, turns the rewrite off.
This extends an [existing
discussion](https://github.com/apache/spark/pull/60756#issuecomment-7064885909).
**Verification:**
- **Behavior:** With the flag set to true, SELECT id FROM t3 WHERE c IN
(SELECT c FROM t5), its NOT IN and multi-column forms, 'a' IN (SELECT c FROM
t5), SELECT id FROM t5 WHERE c = (SELECT c FROM t3) and (SELECT c FROM t5) IN
('a') return the base branch's results for t3(c CHAR(3)) and t5(c CHAR(5))
holding 'a'.
- **Inspection:** The migration-guide entry for subquery comparisons names
the flag that restores the previous behavior.
--
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]