You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@spark.apache.org by we...@apache.org on 2022/10/12 06:16:36 UTC
[spark] branch master updated: [SPARK-40697][SQL] Add read-side char padding to cover external data files
This is an automated email from the ASF dual-hosted git repository.
wenchen pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/spark.git
The following commit(s) were added to refs/heads/master by this push:
new b9998cf1bf3 [SPARK-40697][SQL] Add read-side char padding to cover external data files
b9998cf1bf3 is described below
commit b9998cf1bf3501936bdf7c0d2a8cc3ddf0115a06
Author: Wenchen Fan <we...@databricks.com>
AuthorDate: Wed Oct 12 14:16:16 2022 +0800
[SPARK-40697][SQL] Add read-side char padding to cover external data files
### What changes were proposed in this pull request?
The current char/varchar feature relies on the data source to take care of all the write paths and ensure the char/varchar semantic (length check, string padding). This is good for the read performance, but has problems if some write paths did not follow the char/varchar semantic. e.g. a parquet table can be written by old Spark versions that do not have char/varchar type, or by other systems that do not recognize Spark char/varchar type.
This PR adds read-side string padding for the char type, so that we can still guarantee the char type semantic if the underlying data is valid (not over length). Char type is rarely used for legacy reasons and the perf doesn't matter that much, correctness is more important here. People can still disable read-side padding via a config if they are sure the data was written properly, such as benchmarks.
Note, we don't add read-side length check as varchar type is widely used and we don't want to introduce perf regression for the common case. Another reason is it's better to avoid invalid data at the write side, and read-side check won't help much.
### Why are the changes needed?
to better enforce char type semantic
### Does this PR introduce _any_ user-facing change?
Yes. Now Spark can still return padding char type values correctly even if the data source writer wrote the char type value without padding.
### How was this patch tested?
updated tests
Closes #38151 from cloud-fan/char.
Authored-by: Wenchen Fan <we...@databricks.com>
Signed-off-by: Wenchen Fan <we...@databricks.com>
---
core/src/main/resources/error/error-classes.json | 5 -
.../sql/catalyst/util/CharVarcharCodegenUtils.java | 11 ++
.../spark/sql/catalyst/analysis/Analyzer.scala | 124 +------------
.../spark/sql/catalyst/optimizer/InlineCTE.scala | 6 +-
.../spark/sql/catalyst/util/CharVarcharUtils.scala | 52 ++++--
.../spark/sql/errors/QueryCompilationErrors.scala | 8 -
.../org/apache/spark/sql/internal/SQLConf.scala | 10 ++
.../datasources/ApplyCharTypePadding.scala | 192 +++++++++++++++++++++
.../sql/internal/BaseSessionStateBuilder.scala | 1 +
.../apache/spark/sql/internal/CatalogImpl.scala | 27 ++-
.../apache/spark/sql/CharVarcharTestSuite.scala | 26 ++-
.../org/apache/spark/sql/PlanStabilitySuite.scala | 23 +--
.../org/apache/spark/sql/TPCDSQuerySuite.scala | 4 +
.../apache/spark/sql/sources/TableScanSuite.scala | 2 +-
.../spark/sql/hive/HiveSessionStateBuilder.scala | 1 +
15 files changed, 301 insertions(+), 191 deletions(-)
diff --git a/core/src/main/resources/error/error-classes.json b/core/src/main/resources/error/error-classes.json
index 71e7d7250d0..312f42fd955 100644
--- a/core/src/main/resources/error/error-classes.json
+++ b/core/src/main/resources/error/error-classes.json
@@ -2833,11 +2833,6 @@
"Table or view '<ident>' not found."
]
},
- "_LEGACY_ERROR_TEMP_1304" : {
- "message" : [
- "Unexpected type <className> of the relation <tableName>."
- ]
- },
"_LEGACY_ERROR_TEMP_1305" : {
"message" : [
"Unsupported TableChange <change> in JDBC catalog."
diff --git a/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/util/CharVarcharCodegenUtils.java b/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/util/CharVarcharCodegenUtils.java
index 581f4bb6d25..582b697c92a 100644
--- a/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/util/CharVarcharCodegenUtils.java
+++ b/sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/util/CharVarcharCodegenUtils.java
@@ -52,4 +52,15 @@ public class CharVarcharCodegenUtils {
return trimTrailingSpaces(inputStr, numChars, limit);
}
}
+
+ public static UTF8String readSidePadding(UTF8String inputStr, int limit) {
+ int numChars = inputStr.numChars();
+ if (numChars == limit) {
+ return inputStr;
+ } else if (numChars < limit) {
+ return inputStr.rpad(limit, SPACE);
+ } else {
+ return inputStr;
+ }
+ }
}
diff --git a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/Analyzer.scala b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/Analyzer.scala
index a577bc005be..62d930dcd20 100644
--- a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/Analyzer.scala
+++ b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/Analyzer.scala
@@ -56,7 +56,7 @@ import org.apache.spark.sql.internal.connector.V1Function
import org.apache.spark.sql.types._
import org.apache.spark.sql.types.DayTimeIntervalType.DAY
import org.apache.spark.sql.util.{CaseInsensitiveStringMap, SchemaUtils}
-import org.apache.spark.unsafe.types.{CalendarInterval, UTF8String}
+import org.apache.spark.unsafe.types.CalendarInterval
import org.apache.spark.util.Utils
import org.apache.spark.util.collection.{Utils => CUtils}
@@ -322,8 +322,6 @@ class Analyzer(override val catalogManager: CatalogManager)
Seq(ResolveWithCTE) ++
extendedResolutionRules : _*),
Batch("Remove TempResolvedColumn", Once, RemoveTempResolvedColumn),
- Batch("Apply Char Padding", Once,
- ApplyCharTypePadding),
Batch("Post-Hoc Resolution", Once,
Seq(ResolveCommandsWithIfExists) ++
postHocResolutionRules: _*),
@@ -4290,126 +4288,6 @@ object UpdateOuterReferences extends Rule[LogicalPlan] {
}
}
-/**
- * This rule performs string padding for char type comparison.
- *
- * When comparing char type column/field with string literal or char type column/field,
- * right-pad the shorter one to the longer length.
- */
-object ApplyCharTypePadding extends Rule[LogicalPlan] {
-
- object AttrOrOuterRef {
- def unapply(e: Expression): Option[Attribute] = e match {
- case a: Attribute => Some(a)
- case OuterReference(a: Attribute) => Some(a)
- case _ => None
- }
- }
-
- override def apply(plan: LogicalPlan): LogicalPlan = {
- if (SQLConf.get.charVarcharAsString) {
- return plan
- }
- plan.resolveOperatorsUpWithPruning(_.containsAnyPattern(BINARY_COMPARISON, IN)) {
- case operator => operator.transformExpressionsUpWithPruning(
- _.containsAnyPattern(BINARY_COMPARISON, IN)) {
- case e if !e.childrenResolved => e
-
- // String literal is treated as char type when it's compared to a char type column.
- // We should pad the shorter one to the longer length.
- case b @ BinaryComparison(e @ AttrOrOuterRef(attr), lit) if lit.foldable =>
- padAttrLitCmp(e, attr.metadata, lit).map { newChildren =>
- b.withNewChildren(newChildren)
- }.getOrElse(b)
-
- case b @ BinaryComparison(lit, e @ AttrOrOuterRef(attr)) if lit.foldable =>
- padAttrLitCmp(e, attr.metadata, lit).map { newChildren =>
- b.withNewChildren(newChildren.reverse)
- }.getOrElse(b)
-
- case i @ In(e @ AttrOrOuterRef(attr), list)
- if attr.dataType == StringType && list.forall(_.foldable) =>
- CharVarcharUtils.getRawType(attr.metadata).flatMap {
- case CharType(length) =>
- val (nulls, literalChars) =
- list.map(_.eval().asInstanceOf[UTF8String]).partition(_ == null)
- val literalCharLengths = literalChars.map(_.numChars())
- val targetLen = (length +: literalCharLengths).max
- Some(i.copy(
- value = addPadding(e, length, targetLen),
- list = list.zip(literalCharLengths).map {
- case (lit, charLength) => addPadding(lit, charLength, targetLen)
- } ++ nulls.map(Literal.create(_, StringType))))
- case _ => None
- }.getOrElse(i)
-
- // For char type column or inner field comparison, pad the shorter one to the longer length.
- case b @ BinaryComparison(e1 @ AttrOrOuterRef(left), e2 @ AttrOrOuterRef(right))
- // For the same attribute, they must be the same length and no padding is needed.
- if !left.semanticEquals(right) =>
- val outerRefs = (e1, e2) match {
- case (_: OuterReference, _: OuterReference) => Seq(left, right)
- case (_: OuterReference, _) => Seq(left)
- case (_, _: OuterReference) => Seq(right)
- case _ => Nil
- }
- val newChildren = CharVarcharUtils.addPaddingInStringComparison(Seq(left, right))
- if (outerRefs.nonEmpty) {
- b.withNewChildren(newChildren.map(_.transform {
- case a: Attribute if outerRefs.exists(_.semanticEquals(a)) => OuterReference(a)
- }))
- } else {
- b.withNewChildren(newChildren)
- }
-
- case i @ In(e @ AttrOrOuterRef(attr), list) if list.forall(_.isInstanceOf[Attribute]) =>
- val newChildren = CharVarcharUtils.addPaddingInStringComparison(
- attr +: list.map(_.asInstanceOf[Attribute]))
- if (e.isInstanceOf[OuterReference]) {
- i.copy(
- value = newChildren.head.transform {
- case a: Attribute if a.semanticEquals(attr) => OuterReference(a)
- },
- list = newChildren.tail)
- } else {
- i.copy(value = newChildren.head, list = newChildren.tail)
- }
- }
- }
- }
-
- private def padAttrLitCmp(
- expr: Expression,
- metadata: Metadata,
- lit: Expression): Option[Seq[Expression]] = {
- if (expr.dataType == StringType) {
- CharVarcharUtils.getRawType(metadata).flatMap {
- case CharType(length) =>
- val str = lit.eval().asInstanceOf[UTF8String]
- if (str == null) {
- None
- } else {
- val stringLitLen = str.numChars()
- if (length < stringLitLen) {
- Some(Seq(StringRPad(expr, Literal(stringLitLen)), lit))
- } else if (length > stringLitLen) {
- Some(Seq(expr, StringRPad(lit, Literal(length))))
- } else {
- None
- }
- }
- case _ => None
- }
- } else {
- None
- }
- }
-
- private def addPadding(expr: Expression, charLength: Int, targetLength: Int): Expression = {
- if (targetLength > charLength) StringRPad(expr, Literal(targetLength)) else expr
- }
-}
-
/**
* The rule `ResolveAggregationFunctions` in the main resolution batch creates
* [[TempResolvedColumn]] in filter conditions and sort expressions to hold the temporarily resolved
diff --git a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/InlineCTE.scala b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/InlineCTE.scala
index 3380b52832b..1e4364b3f4a 100644
--- a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/InlineCTE.scala
+++ b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/InlineCTE.scala
@@ -128,7 +128,11 @@ case class InlineCTE(alwaysInline: Boolean = false) extends Rule[LogicalPlan] {
val ctePlan = DeduplicateRelations(
Join(cteDef.child, cteDef.child, Inner, None, JoinHint(None, None))).children(1)
val projectList = ref.output.zip(ctePlan.output).map { case (tgtAttr, srcAttr) =>
- Alias(srcAttr, tgtAttr.name)(exprId = tgtAttr.exprId)
+ if (srcAttr.semanticEquals(tgtAttr)) {
+ tgtAttr
+ } else {
+ Alias(srcAttr, tgtAttr.name)(exprId = tgtAttr.exprId)
+ }
}
Project(projectList, ctePlan)
}
diff --git a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/CharVarcharUtils.scala b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/CharVarcharUtils.scala
index 2b3566d4b15..75af56bdee8 100644
--- a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/CharVarcharUtils.scala
+++ b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/CharVarcharUtils.scala
@@ -181,27 +181,39 @@ object CharVarcharUtils extends Logging {
}
def stringLengthCheck(expr: Expression, dt: DataType): Expression = {
+ processStringForCharVarchar(
+ expr,
+ dt,
+ charFuncName = Some("charTypeWriteSideCheck"),
+ varcharFuncName = Some("varcharTypeWriteSideCheck"))
+ }
+
+ private def processStringForCharVarchar(
+ expr: Expression,
+ dt: DataType,
+ charFuncName: Option[String],
+ varcharFuncName: Option[String]): Expression = {
dt match {
- case CharType(length) =>
+ case CharType(length) if charFuncName.isDefined =>
StaticInvoke(
classOf[CharVarcharCodegenUtils],
StringType,
- "charTypeWriteSideCheck",
+ charFuncName.get,
expr :: Literal(length) :: Nil,
returnNullable = false)
- case VarcharType(length) =>
+ case VarcharType(length) if varcharFuncName.isDefined =>
StaticInvoke(
classOf[CharVarcharCodegenUtils],
StringType,
- "varcharTypeWriteSideCheck",
+ varcharFuncName.get,
expr :: Literal(length) :: Nil,
returnNullable = false)
case StructType(fields) =>
val struct = CreateNamedStruct(fields.zipWithIndex.flatMap { case (f, i) =>
- Seq(Literal(f.name),
- stringLengthCheck(GetStructField(expr, i, Some(f.name)), f.dataType))
+ Seq(Literal(f.name), processStringForCharVarchar(
+ GetStructField(expr, i, Some(f.name)), f.dataType, charFuncName, varcharFuncName))
})
if (expr.nullable) {
If(IsNull(expr), Literal(null, struct.dataType), struct)
@@ -209,24 +221,40 @@ object CharVarcharUtils extends Logging {
struct
}
- case ArrayType(et, containsNull) => stringLengthCheckInArray(expr, et, containsNull)
+ case ArrayType(et, containsNull) =>
+ processStringForCharVarcharInArray(expr, et, containsNull, charFuncName, varcharFuncName)
case MapType(kt, vt, valueContainsNull) =>
- val newKeys = stringLengthCheckInArray(MapKeys(expr), kt, containsNull = false)
- val newValues = stringLengthCheckInArray(MapValues(expr), vt, valueContainsNull)
+ val newKeys = processStringForCharVarcharInArray(
+ MapKeys(expr), kt, containsNull = false, charFuncName, varcharFuncName)
+ val newValues = processStringForCharVarcharInArray(
+ MapValues(expr), vt, valueContainsNull, charFuncName, varcharFuncName)
MapFromArrays(newKeys, newValues)
case _ => expr
}
}
- private def stringLengthCheckInArray(
- arr: Expression, et: DataType, containsNull: Boolean): Expression = {
+ private def processStringForCharVarcharInArray(
+ arr: Expression,
+ et: DataType,
+ containsNull: Boolean,
+ charFuncName: Option[String],
+ varcharFuncName: Option[String]): Expression = {
val param = NamedLambdaVariable("x", replaceCharVarcharWithString(et), containsNull)
- val func = LambdaFunction(stringLengthCheck(param, et), Seq(param))
+ val func = LambdaFunction(
+ processStringForCharVarchar(param, et, charFuncName, varcharFuncName),
+ Seq(param))
ArrayTransform(arr, func)
}
+ def addPaddingForScan(attr: Attribute): Expression = {
+ getRawType(attr.metadata).map { rawType =>
+ processStringForCharVarchar(
+ attr, rawType, charFuncName = Some("readSidePadding"), varcharFuncName = None)
+ }.getOrElse(attr)
+ }
+
/**
* Return expressions to apply char type padding for the string comparison between the given
* attributes. When comparing two char type columns/fields, we need to pad the shorter one to
diff --git a/sql/catalyst/src/main/scala/org/apache/spark/sql/errors/QueryCompilationErrors.scala b/sql/catalyst/src/main/scala/org/apache/spark/sql/errors/QueryCompilationErrors.scala
index 9eb7bb13a87..0c6aeedfc4a 100644
--- a/sql/catalyst/src/main/scala/org/apache/spark/sql/errors/QueryCompilationErrors.scala
+++ b/sql/catalyst/src/main/scala/org/apache/spark/sql/errors/QueryCompilationErrors.scala
@@ -2850,14 +2850,6 @@ private[sql] object QueryCompilationErrors extends QueryErrorsBase {
messageParameters = Map("ident" -> ident.quoted))
}
- def unexpectedTypeOfRelationError(relation: LogicalPlan, tableName: String): Throwable = {
- new AnalysisException(
- errorClass = "_LEGACY_ERROR_TEMP_1304",
- messageParameters = Map(
- "className" -> relation.getClass.getCanonicalName,
- "tableName" -> tableName))
- }
-
def unsupportedTableChangeInJDBCCatalogError(change: TableChange): Throwable = {
new AnalysisException(
errorClass = "_LEGACY_ERROR_TEMP_1305",
diff --git a/sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala b/sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala
index 1c981aa3950..161c4092f60 100644
--- a/sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala
+++ b/sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala
@@ -3820,6 +3820,14 @@ object SQLConf {
.booleanConf
.createWithDefault(false)
+ val READ_SIDE_CHAR_PADDING = buildConf("spark.sql.readSideCharPadding")
+ .doc("When true, Spark applies string padding when reading CHAR type columns/fields, " +
+ "in addition to the write-side padding. This config is true by default to better enforce " +
+ "CHAR type semantic in cases such as external tables.")
+ .version("3.4.0")
+ .booleanConf
+ .createWithDefault(true)
+
val CLI_PRINT_HEADER =
buildConf("spark.sql.cli.print.header")
.doc("When set to true, spark-sql CLI prints the names of the columns in query output.")
@@ -4713,6 +4721,8 @@ class SQLConf extends Serializable with Logging {
def charVarcharAsString: Boolean = getConf(SQLConf.LEGACY_CHAR_VARCHAR_AS_STRING)
+ def readSideCharPadding: Boolean = getConf(SQLConf.READ_SIDE_CHAR_PADDING)
+
def cliPrintHeader: Boolean = getConf(SQLConf.CLI_PRINT_HEADER)
def legacyIntervalEnabled: Boolean = getConf(LEGACY_INTERVAL_ENABLED)
diff --git a/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/ApplyCharTypePadding.scala b/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/ApplyCharTypePadding.scala
new file mode 100644
index 00000000000..b5bf337a5a2
--- /dev/null
+++ b/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/ApplyCharTypePadding.scala
@@ -0,0 +1,192 @@
+/*
+ * 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.execution.datasources
+
+import org.apache.spark.sql.catalyst.catalog.HiveTableRelation
+import org.apache.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.plans.logical.{LogicalPlan, Project}
+import org.apache.spark.sql.catalyst.rules.Rule
+import org.apache.spark.sql.catalyst.trees.TreePattern.{BINARY_COMPARISON, IN}
+import org.apache.spark.sql.catalyst.util.CharVarcharUtils
+import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Relation
+import org.apache.spark.sql.types.{CharType, Metadata, StringType}
+import org.apache.spark.unsafe.types.UTF8String
+
+/**
+ * This rule performs string padding for char type.
+ *
+ * When reading values from column/field of type CHAR(N), right-pad the values to length N, if the
+ * read-side padding config is turned on.
+ *
+ * When comparing char type column/field with string literal or char type column/field,
+ * right-pad the shorter one to the longer length.
+ */
+object ApplyCharTypePadding extends Rule[LogicalPlan] {
+
+ object AttrOrOuterRef {
+ def unapply(e: Expression): Option[Attribute] = e match {
+ case a: Attribute => Some(a)
+ case OuterReference(a: Attribute) => Some(a)
+ case _ => None
+ }
+ }
+
+ override def apply(plan: LogicalPlan): LogicalPlan = {
+ if (conf.charVarcharAsString) {
+ return plan
+ }
+
+ if (conf.readSideCharPadding) {
+ val newPlan = plan.resolveOperatorsUpWithNewOutput {
+ case r: LogicalRelation =>
+ readSidePadding(r, () =>
+ r.copy(output = r.output.map(CharVarcharUtils.cleanAttrMetadata)))
+ case r: DataSourceV2Relation =>
+ readSidePadding(r, () =>
+ r.copy(output = r.output.map(CharVarcharUtils.cleanAttrMetadata)))
+ case r: HiveTableRelation =>
+ readSidePadding(r, () => {
+ val cleanedDataCols = r.dataCols.map(CharVarcharUtils.cleanAttrMetadata)
+ val cleanedPartCols = r.partitionCols.map(CharVarcharUtils.cleanAttrMetadata)
+ r.copy(dataCols = cleanedDataCols, partitionCols = cleanedPartCols)
+ })
+ }
+ paddingForStringComparison(newPlan)
+ } else {
+ paddingForStringComparison(plan)
+ }
+ }
+
+ private def readSidePadding(
+ relation: LogicalPlan,
+ cleanedRelation: () => LogicalPlan)
+ : (LogicalPlan, Seq[(Attribute, Attribute)]) = {
+ val projectList = relation.output.map { attr =>
+ CharVarcharUtils.addPaddingForScan(attr) match {
+ case ne: NamedExpression => ne
+ case other => Alias(other, attr.name)(explicitMetadata = Some(attr.metadata))
+ }
+ }
+ if (projectList == relation.output) {
+ relation -> Nil
+ } else {
+ val newPlan = Project(projectList, cleanedRelation())
+ newPlan -> relation.output.zip(newPlan.output)
+ }
+ }
+
+ private def paddingForStringComparison(plan: LogicalPlan): LogicalPlan = {
+ plan.resolveOperatorsUpWithPruning(_.containsAnyPattern(BINARY_COMPARISON, IN)) {
+ case operator => operator.transformExpressionsUpWithPruning(
+ _.containsAnyPattern(BINARY_COMPARISON, IN)) {
+ case e if !e.childrenResolved => e
+
+ // String literal is treated as char type when it's compared to a char type column.
+ // We should pad the shorter one to the longer length.
+ case b @ BinaryComparison(e @ AttrOrOuterRef(attr), lit) if lit.foldable =>
+ padAttrLitCmp(e, attr.metadata, lit).map { newChildren =>
+ b.withNewChildren(newChildren)
+ }.getOrElse(b)
+
+ case b @ BinaryComparison(lit, e @ AttrOrOuterRef(attr)) if lit.foldable =>
+ padAttrLitCmp(e, attr.metadata, lit).map { newChildren =>
+ b.withNewChildren(newChildren.reverse)
+ }.getOrElse(b)
+
+ case i @ In(e @ AttrOrOuterRef(attr), list)
+ if attr.dataType == StringType && list.forall(_.foldable) =>
+ CharVarcharUtils.getRawType(attr.metadata).flatMap {
+ case CharType(length) =>
+ val (nulls, literalChars) =
+ list.map(_.eval().asInstanceOf[UTF8String]).partition(_ == null)
+ val literalCharLengths = literalChars.map(_.numChars())
+ val targetLen = (length +: literalCharLengths).max
+ Some(i.copy(
+ value = addPadding(e, length, targetLen),
+ list = list.zip(literalCharLengths).map {
+ case (lit, charLength) => addPadding(lit, charLength, targetLen)
+ } ++ nulls.map(Literal.create(_, StringType))))
+ case _ => None
+ }.getOrElse(i)
+
+ // For char type column or inner field comparison, pad the shorter one to the longer length.
+ case b @ BinaryComparison(e1 @ AttrOrOuterRef(left), e2 @ AttrOrOuterRef(right))
+ // For the same attribute, they must be the same length and no padding is needed.
+ if !left.semanticEquals(right) =>
+ val outerRefs = (e1, e2) match {
+ case (_: OuterReference, _: OuterReference) => Seq(left, right)
+ case (_: OuterReference, _) => Seq(left)
+ case (_, _: OuterReference) => Seq(right)
+ case _ => Nil
+ }
+ val newChildren = CharVarcharUtils.addPaddingInStringComparison(Seq(left, right))
+ if (outerRefs.nonEmpty) {
+ b.withNewChildren(newChildren.map(_.transform {
+ case a: Attribute if outerRefs.exists(_.semanticEquals(a)) => OuterReference(a)
+ }))
+ } else {
+ b.withNewChildren(newChildren)
+ }
+
+ case i @ In(e @ AttrOrOuterRef(attr), list) if list.forall(_.isInstanceOf[Attribute]) =>
+ val newChildren = CharVarcharUtils.addPaddingInStringComparison(
+ attr +: list.map(_.asInstanceOf[Attribute]))
+ if (e.isInstanceOf[OuterReference]) {
+ i.copy(
+ value = newChildren.head.transform {
+ case a: Attribute if a.semanticEquals(attr) => OuterReference(a)
+ },
+ list = newChildren.tail)
+ } else {
+ i.copy(value = newChildren.head, list = newChildren.tail)
+ }
+ }
+ }
+ }
+
+ private def padAttrLitCmp(
+ expr: Expression,
+ metadata: Metadata,
+ lit: Expression): Option[Seq[Expression]] = {
+ if (expr.dataType == StringType) {
+ CharVarcharUtils.getRawType(metadata).flatMap {
+ case CharType(length) =>
+ val str = lit.eval().asInstanceOf[UTF8String]
+ if (str == null) {
+ None
+ } else {
+ val stringLitLen = str.numChars()
+ if (length < stringLitLen) {
+ Some(Seq(StringRPad(expr, Literal(stringLitLen)), lit))
+ } else if (length > stringLitLen) {
+ Some(Seq(expr, StringRPad(lit, Literal(length))))
+ } else {
+ None
+ }
+ }
+ case _ => None
+ }
+ } else {
+ None
+ }
+ }
+
+ private def addPadding(expr: Expression, charLength: Int, targetLength: Int): Expression = {
+ if (targetLength > charLength) StringRPad(expr, Literal(targetLength)) else expr
+ }
+}
diff --git a/sql/core/src/main/scala/org/apache/spark/sql/internal/BaseSessionStateBuilder.scala b/sql/core/src/main/scala/org/apache/spark/sql/internal/BaseSessionStateBuilder.scala
index 2271990741d..b12a86c08d1 100644
--- a/sql/core/src/main/scala/org/apache/spark/sql/internal/BaseSessionStateBuilder.scala
+++ b/sql/core/src/main/scala/org/apache/spark/sql/internal/BaseSessionStateBuilder.scala
@@ -196,6 +196,7 @@ abstract class BaseSessionStateBuilder(
PreprocessTableCreation(session) +:
PreprocessTableInsertion +:
DataSourceAnalysis(this) +:
+ ApplyCharTypePadding +:
ReplaceCharWithVarchar +:
customPostHocResolutionRules
diff --git a/sql/core/src/main/scala/org/apache/spark/sql/internal/CatalogImpl.scala b/sql/core/src/main/scala/org/apache/spark/sql/internal/CatalogImpl.scala
index e3a303d4c0a..335e52fee18 100644
--- a/sql/core/src/main/scala/org/apache/spark/sql/internal/CatalogImpl.scala
+++ b/sql/core/src/main/scala/org/apache/spark/sql/internal/CatalogImpl.scala
@@ -26,7 +26,7 @@ import org.apache.spark.sql.catalyst.{DefinedByConstructorParams, FunctionIdenti
import org.apache.spark.sql.catalyst.analysis._
import org.apache.spark.sql.catalyst.catalog._
import org.apache.spark.sql.catalyst.encoders.ExpressionEncoder
-import org.apache.spark.sql.catalyst.plans.logical.{CreateTable, LocalRelation, RecoverPartitions, ShowFunctions, ShowNamespaces, ShowTables, SubqueryAlias, TableSpec, View}
+import org.apache.spark.sql.catalyst.plans.logical.{CreateTable, LocalRelation, LogicalPlan, RecoverPartitions, ShowFunctions, ShowNamespaces, ShowTables, TableSpec, View}
import org.apache.spark.sql.connector.catalog.{CatalogManager, CatalogPlugin, CatalogV2Util, FunctionCatalog, Identifier, SupportsNamespaces, Table => V2Table, TableCatalog, V1Table}
import org.apache.spark.sql.connector.catalog.CatalogV2Implicits.{CatalogHelper, MultipartIdentifierHelper, TransformHelper}
import org.apache.spark.sql.errors.QueryCompilationErrors
@@ -801,29 +801,24 @@ class CatalogImpl(sparkSession: SparkSession) extends Catalog {
// Temporary and global temporary views are not supposed to be put into the relation cache
// since they are tracked separately. V1 and V2 plans are cache invalidated accordingly.
- relation match {
- case SubqueryAlias(_, v: View) if !v.isTempView =>
- sessionCatalog.invalidateCachedTable(v.desc.identifier)
- case SubqueryAlias(_, r: LogicalRelation) =>
+ def invalidateCache(plan: LogicalPlan): Unit = plan match {
+ case v: View =>
+ if (!v.isTempView) sessionCatalog.invalidateCachedTable(v.desc.identifier)
+ case r: LogicalRelation =>
sessionCatalog.invalidateCachedTable(r.catalogTable.get.identifier)
- case SubqueryAlias(_, h: HiveTableRelation) =>
+ case h: HiveTableRelation =>
sessionCatalog.invalidateCachedTable(h.tableMeta.identifier)
- case SubqueryAlias(_, r: DataSourceV2Relation) =>
+ case r: DataSourceV2Relation =>
r.catalog.get.asTableCatalog.invalidateTable(r.identifier.get)
- case SubqueryAlias(_, v: View) if v.isTempView =>
- case _ =>
- throw QueryCompilationErrors.unexpectedTypeOfRelationError(relation, tableName)
+ case _ => plan.children.foreach(invalidateCache)
}
+ invalidateCache(relation)
+
// Re-caches the logical plan of the relation.
// Note this is a no-op for the relation itself if it's not cached, but will clear all
// caches referencing this relation. If this relation is cached as an InMemoryRelation,
// this will clear the relation cache and caches of all its dependents.
- relation match {
- case SubqueryAlias(_, relationPlan) =>
- sparkSession.sharedState.cacheManager.recacheByPlan(sparkSession, relationPlan)
- case _ =>
- throw QueryCompilationErrors.unexpectedTypeOfRelationError(relation, tableName)
- }
+ sparkSession.sharedState.cacheManager.recacheByPlan(sparkSession, relation)
}
/**
diff --git a/sql/core/src/test/scala/org/apache/spark/sql/CharVarcharTestSuite.scala b/sql/core/src/test/scala/org/apache/spark/sql/CharVarcharTestSuite.scala
index 35a62d687de..27a630c169b 100644
--- a/sql/core/src/test/scala/org/apache/spark/sql/CharVarcharTestSuite.scala
+++ b/sql/core/src/test/scala/org/apache/spark/sql/CharVarcharTestSuite.scala
@@ -806,13 +806,11 @@ class FileSourceCharVarcharTestSuite extends CharVarcharTestSuite with SharedSpa
}
test("create table w/ location and fit length values") {
- Seq("char", "varchar").foreach { typ =>
- withTempPath { dir =>
- withTable("t") {
- sql("SELECT '12' as col").write.format(format).save(dir.toString)
- sql(s"CREATE TABLE t (col $typ(2)) using $format LOCATION '$dir'")
- checkAnswer(sql("select * from t"), Row("12"))
- }
+ withTempPath { dir =>
+ withTable("t") {
+ sql("SELECT '12' as col1, '12' as col2").write.format(format).save(dir.toString)
+ sql(s"CREATE TABLE t (col1 char(3), col2 varchar(3)) using $format LOCATION '$dir'")
+ checkAnswer(sql("select * from t"), Row("12 ", "12"))
}
}
}
@@ -830,14 +828,12 @@ class FileSourceCharVarcharTestSuite extends CharVarcharTestSuite with SharedSpa
}
test("alter table set location w/ fit length values") {
- Seq("char", "varchar").foreach { typ =>
- withTempPath { dir =>
- withTable("t") {
- sql("SELECT '12' as col").write.format(format).save(dir.toString)
- sql(s"CREATE TABLE t (col $typ(2)) using $format")
- sql(s"ALTER TABLE t SET LOCATION '$dir'")
- checkAnswer(spark.table("t"), Row("12"))
- }
+ withTempPath { dir =>
+ withTable("t") {
+ sql("SELECT '12' as col1, '12' as col2").write.format(format).save(dir.toString)
+ sql(s"CREATE TABLE t (col1 char(3), col2 varchar(3)) using $format")
+ sql(s"ALTER TABLE t SET LOCATION '$dir'")
+ checkAnswer(spark.table("t"), Row("12 ", "12"))
}
}
}
diff --git a/sql/core/src/test/scala/org/apache/spark/sql/PlanStabilitySuite.scala b/sql/core/src/test/scala/org/apache/spark/sql/PlanStabilitySuite.scala
index ace1756a14d..643dcc20c65 100644
--- a/sql/core/src/test/scala/org/apache/spark/sql/PlanStabilitySuite.scala
+++ b/sql/core/src/test/scala/org/apache/spark/sql/PlanStabilitySuite.scala
@@ -256,16 +256,19 @@ trait PlanStabilitySuite extends DisableAdaptiveExecutionSuite {
protected def testQuery(tpcdsGroup: String, query: String, suffix: String = ""): Unit = {
val queryString = resourceToString(s"$tpcdsGroup/$query.sql",
classLoader = Thread.currentThread().getContextClassLoader)
- val qe = sql(queryString).queryExecution
- val plan = qe.executedPlan
- val explain = normalizeLocation(normalizeIds(qe.explainString(FormattedMode)))
-
- assert(ValidateRequirements.validate(plan))
-
- if (regenerateGoldenFiles) {
- generateGoldenFile(plan, query + suffix, explain)
- } else {
- checkWithApproved(plan, query + suffix, explain)
+ // Disable char/varchar read-side handling for better performance.
+ withSQLConf(SQLConf.READ_SIDE_CHAR_PADDING.key -> "false") {
+ val qe = sql(queryString).queryExecution
+ val plan = qe.executedPlan
+ val explain = normalizeLocation(normalizeIds(qe.explainString(FormattedMode)))
+
+ assert(ValidateRequirements.validate(plan))
+
+ if (regenerateGoldenFiles) {
+ generateGoldenFile(plan, query + suffix, explain)
+ } else {
+ checkWithApproved(plan, query + suffix, explain)
+ }
}
}
}
diff --git a/sql/core/src/test/scala/org/apache/spark/sql/TPCDSQuerySuite.scala b/sql/core/src/test/scala/org/apache/spark/sql/TPCDSQuerySuite.scala
index 8c4d25a7eb9..ffd15eb46a4 100644
--- a/sql/core/src/test/scala/org/apache/spark/sql/TPCDSQuerySuite.scala
+++ b/sql/core/src/test/scala/org/apache/spark/sql/TPCDSQuerySuite.scala
@@ -29,6 +29,10 @@ import org.apache.spark.tags.ExtendedSQLTest
@ExtendedSQLTest
class TPCDSQuerySuite extends BenchmarkQueryTest with TPCDSBase {
+ override protected def sparkConf: SparkConf =
+ // Disable read-side char padding so that the generated code is less than 8000.
+ super.sparkConf.set(SQLConf.READ_SIDE_CHAR_PADDING, false)
+
// q72 is skipped due to GitHub Actions' memory limit.
tpcdsQueries.filterNot(sys.env.contains("GITHUB_ACTIONS") && _ == "q72").foreach { name =>
val queryString = resourceToString(s"tpcds/$name.sql",
diff --git a/sql/core/src/test/scala/org/apache/spark/sql/sources/TableScanSuite.scala b/sql/core/src/test/scala/org/apache/spark/sql/sources/TableScanSuite.scala
index 8f263f042cf..eac77c29382 100644
--- a/sql/core/src/test/scala/org/apache/spark/sql/sources/TableScanSuite.scala
+++ b/sql/core/src/test/scala/org/apache/spark/sql/sources/TableScanSuite.scala
@@ -141,7 +141,7 @@ class TableScanSuite extends DataSourceTest with SharedSparkSession {
Date.valueOf("1970-01-01"),
new Timestamp(20000 + i),
s"varchar_$i",
- s"char_$i",
+ s"char_$i".padTo(18, ' '),
Seq(i, i + 1),
Seq(Map(s"str_$i" -> Row(i.toLong))),
Map(i -> i.toString),
diff --git a/sql/hive/src/main/scala/org/apache/spark/sql/hive/HiveSessionStateBuilder.scala b/sql/hive/src/main/scala/org/apache/spark/sql/hive/HiveSessionStateBuilder.scala
index b554958572a..c4e0057ae95 100644
--- a/sql/hive/src/main/scala/org/apache/spark/sql/hive/HiveSessionStateBuilder.scala
+++ b/sql/hive/src/main/scala/org/apache/spark/sql/hive/HiveSessionStateBuilder.scala
@@ -101,6 +101,7 @@ class HiveSessionStateBuilder(
PreprocessTableCreation(session) +:
PreprocessTableInsertion +:
DataSourceAnalysis(this) +:
+ ApplyCharTypePadding +:
HiveAnalysis +:
ReplaceCharWithVarchar +:
customPostHocResolutionRules
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@spark.apache.org
For additional commands, e-mail: commits-help@spark.apache.org