LuciferYang commented on code in PR #60616:
URL: https://github.com/apache/spark/pull/60616#discussion_r4625205721
##########
sql/core/src/test/scala/org/apache/spark/sql/StatisticsCollectionSuite.scala:
##########
@@ -287,6 +288,63 @@ class StatisticsCollectionSuite extends
StatisticsCollectionTestBase with Shared
}
}
+ // Both make CHAR and VARCHAR first-class types, which a comparison with a
STRING casts.
+ private val firstClassCharVarcharConfs = Seq(
+ SQLConf.CHAR_VARCHAR_STANDARD_SEMANTICS,
SQLConf.PRESERVE_CHAR_VARCHAR_TYPE_INFO)
+
+ test("SPARK-60830: CBO keeps CHAR/VARCHAR column statistics as first-class
types") {
+ for (mode <- firstClassCharVarcharConfs; colType <- Seq("CHAR(5)",
"VARCHAR(5)")) {
+ withSQLConf(SQLConf.CBO_ENABLED.key -> "true", mode.key -> "true") {
+ val tableName = "char_varchar_first_class_stats"
+ val stringTable = "char_varchar_first_class_strings"
+ withTable(tableName, stringTable) {
+ sql(s"CREATE TABLE $tableName(c $colType) USING parquet")
+ sql(s"CREATE TABLE $stringTable(s STRING) USING parquet")
+ Seq(tableName, stringTable).foreach { t =>
+ sql(s"INSERT INTO $t SELECT CAST(id % 10 AS STRING) FROM
range(1000)")
+ }
+ sql(s"ANALYZE TABLE $tableName COMPUTE STATISTICS FOR COLUMNS c")
+ sql(s"ANALYZE TABLE $stringTable COMPUTE STATISTICS FOR COLUMNS s")
+
+ val clue = s"${mode.key}, $colType"
+ assert(estimatedRows(s"SELECT c, count(*) FROM $tableName GROUP BY
c") {
+ case a: Aggregate => a
+ }.contains(BigInt(10)), clue)
+ Seq("c = '3'" -> 100, "c IN ('3', '4')" -> 200, "c IS NULL" ->
0).foreach {
Review Comment:
You read it correctly. The tests now insert `CAST(10000 + id % 10 AS
STRING)`, so the CHAR(5) values need no padding and every predicate matches the
same rows as for VARCHAR(5) and STRING. Each estimate, partition pruning
included, is now checked against `count()` of the same query. The PR
description uses the same data.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/statsEstimation/EstimationUtils.scala:
##########
@@ -123,6 +119,26 @@ object EstimationUtils {
}
}
+ /** Raises the lengths of a column with values to the length N of the CHAR
it is padded to. */
+ private def padToCharLength(stat: ColumnStat, n: Int): ColumnStat = {
+ if (stat.distinctCount.contains(BigInt(0))) {
+ stat
+ } else {
+ stat.copy(avgLen = stat.avgLen.map(_.max(n)), maxLen =
stat.maxLen.map(_.max(n)))
+ }
+ }
+
+ /**
+ * Strips a cast of a CHAR, VARCHAR or STRING value to a STRING of the same
collation, such as
+ * the one a comparison with a STRING adds when CHAR and VARCHAR are
first-class types. Such a
+ * cast returns the value unchanged.
+ */
+ def stripCastToPlainString(e: Expression): Expression = e match {
Review Comment:
Yes, `stripCastToPlainString` applies in every mode. Measured on master vs
this PR with the default confs: a filter on `CAST(v AS STRING)` over VARCHAR(5)
goes from 1000 to 100 rows, and `JOIN ... ON CAST(c AS STRING) = s` from
1000000 to 100000 for both CHAR(5) and VARCHAR(5). A new
`StatisticsCollectionSuite` test pins these default-mode estimates, and the
migration guide entry and the PR description now say so. Only a cast to a
STRING of the same collation is stripped.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/statsEstimation/JoinEstimation.scala:
##########
@@ -59,8 +59,10 @@ case class JoinEstimation(join: Join) extends Logging {
case ExtractEquiJoinKeys(joinType, leftKeys, rightKeys, _, _, left, right,
_) =>
// 1. Compute join selectivity
val joinKeyPairs = extractJoinKeysWithColStats(leftKeys, rightKeys)
- val leftSideUniqueness =
left.distinctKeys.exists(_.subsetOf(ExpressionSet(leftKeys)))
- val rightSideUniqueness =
right.distinctKeys.exists(_.subsetOf(ExpressionSet(rightKeys)))
+ val leftSideUniqueness = left.distinctKeys.exists(
+ _.subsetOf(ExpressionSet(leftKeys.map(stripCastToPlainString))))
Review Comment:
Aligned here. `DistinctKeyVisitor.joinKeySet` strips the same cast, and
`DistinctKeyVisitor.visitJoin`, `SizeInBytesOnlyStatsPlanVisitor.visitJoin` and
the outer join elimination in `joins.scala` use it, so a side unique on a
CHAR/VARCHAR column stays unique on the cast. That changes plans as well: under
either conf, `SELECT s FROM u LEFT JOIN (SELECT c FROM t GROUP BY c) g ON s =
g.c` no longer joins, nor does the same query with `ON s = CAST(g.c AS STRING)`
in the default mode. Tests cover each site, and the migration guide has an
entry for it.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/statsEstimation/FilterEstimation.scala:
##########
@@ -258,6 +255,20 @@ case class FilterEstimation(
}
}
+ /**
+ * Returns the column under the read-side padding or check that a scan wraps
a CHAR or VARCHAR
+ * column in, and under the cast to STRING that a comparison adds when CHAR
and VARCHAR are
+ * first-class types (see `EstimationUtils.stripCastToPlainString`).
+ */
+ private def unwrapCharVarcharRead(e: Expression): Expression = {
Review Comment:
Done. `CharVarcharUtils.ReadSidePaddingOrCheck` now matches the padding and
both checks and returns whether shorter values are padded to the length.
`getAliasStats` and `unwrapCharVarcharRead` each have one case.
`ReadSidePadding` stays as is for `V2ExpressionBuilder`.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/statsEstimation/JoinEstimation.scala:
##########
@@ -354,7 +356,9 @@ case class JoinEstimation(join: Join) extends Logging {
private def extractJoinKeysWithColStats(
leftKeys: Seq[Expression],
rightKeys: Seq[Expression]): Seq[(AttributeReference,
AttributeReference)] = {
- leftKeys.zip(rightKeys).collect {
+ leftKeys.zip(rightKeys).map { case (lk, rk) =>
+ (stripCastToPlainString(lk), stripCastToPlainString(rk))
Review Comment:
Done. `estimateInnerOuterJoin` strips the keys once and passes them to both
the key extraction and the uniqueness checks, and `extractJoinKeysWithColStats`
is a single `collect` again.
--
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]