This is an automated email from the ASF dual-hosted git repository.

LuciferYang 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 185af76e48ce [SPARK-60810][SQL] Keep CHAR column statistics through 
read-side padding
185af76e48ce is described below

commit 185af76e48ce42811f0e59772f290b10f2a4a922
Author: YangJie <[email protected]>
AuthorDate: Thu Nov 12 11:33:25 2026 +0800

    [SPARK-60810][SQL] Keep CHAR column statistics through read-side padding
    
    ### What changes were proposed in this pull request?
    
    CBO now sees `CHAR` column statistics through the read-side padding that 
`ApplyCharTypePadding` adds to scans, `readSidePadding(c, N)`:
    
    - `EstimationUtils.getAliasStats` passes the column's stats through 
`Alias(readSidePadding(c, N))` and raises `avgLen`/`maxLen` to at least N, 
unless the column has no non-null values.
    - `FilterEstimation` estimates a predicate on `readSidePadding(c, N)`, 
which a filter pushed below the padding `Project` compares, as one on `c`.
    - A new `CharVarcharUtils.ReadSidePadding` extractor matches the padding, 
and `V2ExpressionBuilder` now uses it.
    
    Passing the stats through exposes CHAR columns to two existing estimator 
failures, which this PR also fixes:
    
    - Histogram estimates apply only to types `EstimationUtils.toDouble` 
converts (`canEstimateWithHistogram`), and `JoinEstimation` converts its bounds 
with `toDouble`. A histogram that a DSv2 connector reports for a STRING column 
or for BOOLEAN join keys made optimization fail.
    - An equi-join whose keys have a distinct count of 0 on both sides is 
estimated at 0 rows instead of dividing by zero.
    
    ### Why are the changes needed?
    
    This is a regression from SPARK-40697 (3.4.0): read-side padding 
(`spark.sql.readSideCharPadding`, on by default) wraps every CHAR column of a 
scan. The estimators only matched bare attributes, so CHAR columns lost their 
stats at the first `Project`, and their filters got selectivity 1.0. With CBO 
on, after `ANALYZE` on a `CHAR(5)` column with 10 distinct values in 1000 rows:
    
    | query | before | after | same data as `STRING` |
    |---|---|---|---|
    | `SELECT c, count(*) FROM t GROUP BY c` | no row count | 10 | 10 |
    | `SELECT * FROM t WHERE c = '3'` | 1000 | 100 | 100 |
    
    `ANALYZE` reads through the same padding and the analyzer pads compared 
literals, so the stats and the predicates describe the same values. Standard 
CHAR/VARCHAR semantics use other read-side checks and are left to SPARK-60830.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Query results are unchanged. With CBO on, plans over analyzed CHAR columns 
can change, and so can partition pruning on CHAR columns when only 
`spark.sql.cbo.planStats.enabled` is on. The migration guide covers this. 
Queries that failed during optimization on DSv2-reported histograms or on some 
outer joins of all-null string keys now run. An equality on a STRING or BINARY 
column with a histogram but no min/max now uses the distinct count instead of 
selectivity 1.0.
    
    ### How was this patch tested?
    
    New tests, each failing without the change:
    
    - `ProjectEstimationSuite`, `FilterEstimationSuite`, `JoinEstimationSuite`, 
`DataSourceV2RelationSuite`: stats pass through the padding with the length 
floor, each predicate form on a padded column, the histogram guard for STRING, 
BINARY, CHAR and BOOLEAN keys, and all-null join keys.
    - `StatisticsCollectionSuite`, end to end after `ANALYZE` on `CHAR(5)`: 
`GROUP BY c` gives 10 rows, `c = '3'` 100, `c IN ('3', '4')` 200, a pruned CHAR 
partition 100, and an outer join of all-null CHAR columns plans.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Opus 5.5
    
    Closes #60025 from LuciferYang/SPARK-60810.
    
    Authored-by: YangJie <[email protected]>
    Signed-off-by: yangjie01 <[email protected]>
    
    
    skip-checks: true
---
 docs/sql-migration-guide.md                        |  1 +
 .../logical/statsEstimation/EstimationUtils.scala  | 33 +++++++++
 .../logical/statsEstimation/FilterEstimation.scala | 15 +++-
 .../logical/statsEstimation/JoinEstimation.scala   | 16 ++--
 .../spark/sql/catalyst/util/CharVarcharUtils.scala | 13 ++++
 .../sql/catalyst/util/V2ExpressionBuilder.scala    | 72 +++++++-----------
 .../statsEstimation/FilterEstimationSuite.scala    | 63 +++++++++++++++-
 .../statsEstimation/JoinEstimationSuite.scala      | 72 +++++++++++++++++-
 .../statsEstimation/ProjectEstimationSuite.scala   | 62 +++++++++++++++-
 .../statsEstimation/StatsEstimationTestBase.scala  |  9 ++-
 .../datasources/v2/DataSourceV2RelationSuite.scala | 33 ++++++++-
 .../spark/sql/StatisticsCollectionSuite.scala      | 85 ++++++++++++++++++++++
 12 files changed, 414 insertions(+), 60 deletions(-)

diff --git a/docs/sql-migration-guide.md b/docs/sql-migration-guide.md
index 876cf10b8276..1efd3ac15fed 100644
--- a/docs/sql-migration-guide.md
+++ b/docs/sql-migration-guide.md
@@ -24,6 +24,7 @@ license: |
 
 ## Upgrading from Spark SQL 4.4 to 5.0
 
+- Since Spark 5.0, when `spark.sql.cbo.enabled` is `true`, the optimizer 
estimates plans over analyzed `CHAR` columns from their column statistics, as 
it does for `STRING` columns. Since Spark 3.4, read-side `CHAR` padding 
(`spark.sql.readSideCharPadding`, `true` by default) hid these statistics, so, 
for example, a filter on a `CHAR` partition column was estimated to keep every 
row. The estimate assumes evenly distributed values, so for a skewed partition 
it can now be smaller than the d [...]
 - 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 (S [...]
 - 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 A [...]
 
diff --git 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/statsEstimation/EstimationUtils.scala
 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/statsEstimation/EstimationUtils.scala
index c107e5428852..59ec6a8d2aea 100644
--- 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/statsEstimation/EstimationUtils.scala
+++ 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/statsEstimation/EstimationUtils.scala
@@ -22,6 +22,7 @@ import scala.math.BigDecimal.RoundingMode
 
 import org.apache.spark.sql.catalyst.expressions.{Alias, Attribute, 
AttributeMap, EmptyRow, Expression}
 import org.apache.spark.sql.catalyst.plans.logical._
+import org.apache.spark.sql.catalyst.util.CharVarcharUtils
 import org.apache.spark.sql.types.{DecimalType, _}
 
 object EstimationUtils {
@@ -87,6 +88,29 @@ object EstimationUtils {
     expressions.collect {
       case alias @ Alias(attr: Attribute, _) if attributeStats.contains(attr) 
=>
         alias.toAttribute -> attributeStats(attr)
+      // Read-side CHAR padding wraps each CHAR column of a scan. With padding 
on, ANALYZE TABLE
+      // reads the table through it as well, so the statistics already 
describe padded values.
+      // Statistics collected otherwise (with padding off, or reported by a 
connector) can
+      // describe shorter values, and every non-null padded value has at least 
N characters.
+      // A distinct count of 0 means no non-null values, so there is nothing 
to pad (ANALYZE
+      // then stores the type's default size as the lengths). The distinct 
count is left as is.
+      // It is too high only when stored values differ just in trailing 
spaces, which the
+      // padding makes equal.
+      // TODO(SPARK-60830): under 
spark.sql.charVarchar.standardSemantics.enabled the scan wraps
+      // CHAR and VARCHAR columns in charTypeReadSideCheck and 
varcharTypeReadSideCheck instead,
+      // so they still lose their statistics here and in 
FilterEstimation.calculateSingleCondition.
+      // They need an extractor of their own, because V2ExpressionBuilder 
relies on
+      // ReadSidePadding never matching the checks. Under first-class CHAR 
types the filter unwrap
+      // also has to see through the cast to STRING.
+      case alias @ Alias(CharVarcharUtils.ReadSidePadding(attr: Attribute, n), 
_)
+          if attributeStats.contains(attr) =>
+        val stat = attributeStats(attr)
+        val padded = if (stat.distinctCount.contains(BigInt(0))) {
+          stat
+        } else {
+          stat.copy(avgLen = stat.avgLen.map(_.max(n)), maxLen = 
stat.maxLen.map(_.max(n)))
+        }
+        alias.toAttribute -> padded
       case alias @ Alias(expr: Expression, _) if expr.foldable && 
expr.deterministic =>
         val value = expr.eval(EmptyRow)
         val size = expr.dataType.defaultSize
@@ -128,6 +152,15 @@ object EstimationUtils {
     if (outputRowCount > 0) outputRowCount * getSizePerRow(attributes, 
attrStats) else 1
   }
 
+  /**
+   * Whether a column of this type can be estimated with an equi-height 
histogram: the types
+   * whose values [[toDouble]] converts. A DSv2 connector can report a 
histogram for any type.
+   */
+  def canEstimateWithHistogram(dataType: DataType): Boolean = dataType match {
+    case _: NumericType | DateType | TimestampType | BooleanType => true
+    case _ => false
+  }
+
   /**
    * For simplicity we use Double to unify operations for data types whose 
min/max values can be
    * represented as numbers, e.g. Boolean can be represented as 0 (false) or 1 
(true).
diff --git 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/statsEstimation/FilterEstimation.scala
 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/statsEstimation/FilterEstimation.scala
index da2277b521db..3dc0694b6799 100755
--- 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/statsEstimation/FilterEstimation.scala
+++ 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/statsEstimation/FilterEstimation.scala
@@ -25,6 +25,7 @@ import org.apache.spark.sql.catalyst.expressions._
 import org.apache.spark.sql.catalyst.expressions.Literal.{FalseLiteral, 
TrueLiteral}
 import org.apache.spark.sql.catalyst.plans.logical._
 import 
org.apache.spark.sql.catalyst.plans.logical.statsEstimation.EstimationUtils._
+import org.apache.spark.sql.catalyst.util.CharVarcharUtils
 import org.apache.spark.sql.types._
 
 object FilterEstimation {
@@ -161,7 +162,10 @@ case class FilterEstimation(
   /**
    * Returns a percentage of rows meeting a single condition in Filter node.
    * Currently we only support binary predicates where one side is a column,
-   * and the other is a literal.
+   * and the other is a literal. A side may also be the read-side CHAR padding 
of a column, which
+   * is what a predicate pushed below the padding Project compares. It is 
estimated as the column
+   * itself, as `EstimationUtils.getAliasStats` does above the padding 
Project. The read-side
+   * checks of standard CHAR/VARCHAR semantics are not handled yet, see the 
SPARK-60830 TODO there.
    *
    * @param condition a single logical expression
    * @param update a boolean flag to specify if we need to update ColumnStat 
of a column
@@ -170,7 +174,11 @@ case class FilterEstimation(
    *         It returns None if the condition is not supported.
    */
   def calculateSingleCondition(condition: Expression, update: Boolean): 
Option[Double] = {
-    condition match {
+    val unpadded = condition.mapChildren {
+      case CharVarcharUtils.ReadSidePadding(attr: Attribute, _) => attr
+      case other => other
+    }
+    unpadded match {
       case l: Literal =>
         evaluateLiteral(l)
 
@@ -366,7 +374,8 @@ case class FilterEstimation(
 
     if (!valueInRange) return Some(0.0)
 
-    val percent = if (colStat.histogram.isDefined) {
+    val useHistogram = colStat.histogram.isDefined && 
canEstimateWithHistogram(attr.dataType)
+    val percent = if (useHistogram) {
       if (colStat.hasMinMaxStats) {
         Some(computeEqualityPossibilityByHistogram(literal, colStat))
       } else {
diff --git 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/statsEstimation/JoinEstimation.scala
 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/statsEstimation/JoinEstimation.scala
index a4672f9cd9f6..dd55a66b31ac 100644
--- 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/statsEstimation/JoinEstimation.scala
+++ 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/statsEstimation/JoinEstimation.scala
@@ -198,10 +198,14 @@ case class JoinEstimation(join: Join) extends Logging {
       val rightKeyStat = rightStats.attributeStats(rightKey)
       val lInterval = ValueInterval(leftKeyStat.min, leftKeyStat.max, 
leftKey.dataType)
       val rInterval = ValueInterval(rightKeyStat.min, rightKeyStat.max, 
rightKey.dataType)
-      if (ValueInterval.isIntersected(lInterval, rInterval)) {
+      // A distinct count of 0 on both sides means neither has a non-null key 
value.
+      val noValues = leftKeyStat.distinctCount.contains(BigInt(0)) &&
+        rightKeyStat.distinctCount.contains(BigInt(0))
+      if (!noValues && ValueInterval.isIntersected(lInterval, rInterval)) {
         val (newMin, newMax) = ValueInterval.intersect(lInterval, rInterval, 
leftKey.dataType)
         val (card, joinStat) = (leftKeyStat.histogram, rightKeyStat.histogram) 
match {
-          case (Some(l: Histogram), Some(r: Histogram)) =>
+          case (Some(l: Histogram), Some(r: Histogram))
+              if canEstimateWithHistogram(leftKey.dataType) =>
             computeByHistogram(leftKey, rightKey, l, r, newMin, newMax)
           case _ =>
             computeByNdv(leftKey, rightKey, newMin, newMax)
@@ -215,7 +219,8 @@ case class JoinEstimation(join: Join) extends Logging {
         // Return cardinality estimated from the most selective join keys.
         if (card < joinCard) joinCard = card
       } else {
-        // One of the join key pairs is disjoint, thus the two sides of join 
is disjoint.
+        // One of the join key pairs is disjoint or has no non-null values, 
thus the two sides
+        // of join is disjoint.
         joinCard = 0
       }
       i += 1
@@ -263,9 +268,8 @@ case class JoinEstimation(join: Join) extends Logging {
     val overlappedRanges = getOverlappedRanges(
       leftHistogram = leftHistogram,
       rightHistogram = rightHistogram,
-      // Only numeric values have equi-height histograms.
-      lowerBound = newMin.get.toString.toDouble,
-      upperBound = newMax.get.toString.toDouble)
+      lowerBound = toDouble(newMin.get, leftKey.dataType),
+      upperBound = toDouble(newMax.get, leftKey.dataType))
 
     var card: BigDecimal = 0
     var totalNdv: Double = 0
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 0871f0a0b8a2..654ead129379 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
@@ -391,6 +391,19 @@ object CharVarcharUtils extends Logging with 
SparkCharVarcharUtils {
     }.getOrElse(attr)
   }
 
+  /**
+   * Matches the read-side CHAR padding that [[addPaddingForScan]] wraps a 
column in (when
+   * standard semantics are off) and extracts the padded expression and the 
CHAR length.
+   */
+  private[sql] object ReadSidePadding {
+    def unapply(e: Expression): Option[(Expression, Int)] = e match {
+      case s @ StaticInvoke(_, _, READ_SIDE_PADDING, Seq(child, Literal(n: 
Int, _)), _, _, _, _,
+          None) if s.staticObject == classOf[CharVarcharCodegenUtils] =>
+        Some((child, n))
+      case _ => None
+    }
+  }
+
   /**
    * 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/catalyst/util/V2ExpressionBuilder.scala
 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/V2ExpressionBuilder.scala
index ecc75ec3ae3a..a493eb89b400 100644
--- 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/V2ExpressionBuilder.scala
+++ 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/V2ExpressionBuilder.scala
@@ -149,11 +149,11 @@ class V2ExpressionBuilder(e: Expression, isPredicate: 
Boolean = false) extends L
           None
         }
       }
-    case IsNull(invoke: StaticInvoke) if isCharReadSidePaddingInvoke(invoke) =>
-      generateExpression(invoke.arguments.head)
+    case IsNull(CharVarcharUtils.ReadSidePadding(child, _)) =>
+      generateExpression(child)
         .map(c => new V2Predicate("IS_NULL", Array[V2Expression](c)))
-    case IsNotNull(invoke: StaticInvoke) if 
isCharReadSidePaddingInvoke(invoke) =>
-      generateExpression(invoke.arguments.head)
+    case IsNotNull(CharVarcharUtils.ReadSidePadding(child, _)) =>
+      generateExpression(child)
         .map(c => new V2Predicate("IS_NOT_NULL", Array[V2Expression](c)))
     case IsNull(col) => generateExpression(col)
       .map(c => new V2Predicate("IS_NULL", Array[V2Expression](c)))
@@ -484,41 +484,28 @@ class V2ExpressionBuilder(e: Expression, isPredicate: 
Boolean = false) extends L
     }
   }
 
-  private def isCharReadSidePaddingInvoke(invoke: StaticInvoke): Boolean = {
-    invoke.scalarFunction.isEmpty &&
-      invoke.staticObject == classOf[CharVarcharCodegenUtils] &&
-      invoke.functionName == CharVarcharUtils.READ_SIDE_PADDING &&
-      invoke.arguments.length == 2
-  }
-
   // Identity compile is only valid vs a literal Spark already padded to the 
CHAR length.
-  private def charPadLength(invoke: StaticInvoke): Option[Int] = 
invoke.arguments(1) match {
-    case Literal(n: Int, _) => Some(n)
-    case _ => None
-  }
-
   private def isFoldableStringOfLen(expr: Expression, n: Int): Boolean = expr 
match {
     case Literal(s: UTF8String, _) => s.numChars() == n
     case _ => false
   }
 
-  private def generateCharPadColumn(invoke: StaticInvoke): 
Option[V2Expression] = {
+  private def generateCharPadColumn(
+      child: Expression, length: Int, dataType: DataType): 
Option[V2Expression] = {
     generateExpressionWithNameByChildren(
       CharVarcharUtils.V2_CHAR_READ_SIDE_PADDING,
-      Seq(invoke.arguments.head, invoke.arguments(1), Literal.create(" ", 
StringType)),
-      invoke.dataType,
+      Seq(child, Literal(length), Literal.create(" ", StringType)),
+      dataType,
       isPredicate = false)
   }
 
   private def generateCharPadLiteralCmp(
       name: String, left: Expression, right: Expression): Option[V2Expression] 
= {
     def paddedVsLit(pad: Expression, lit: Expression): Option[V2Expression] = 
pad match {
-      case invoke: StaticInvoke if isCharReadSidePaddingInvoke(invoke) =>
-        charPadLength(invoke).filter(isFoldableStringOfLen(lit, _)).flatMap { 
_ =>
-          generateCharPadColumn(invoke).flatMap { col =>
-            generateExpression(lit).map { l =>
-              new V2Predicate(name, Array[V2Expression](col, l))
-            }
+      case CharVarcharUtils.ReadSidePadding(child, n) if 
isFoldableStringOfLen(lit, n) =>
+        generateCharPadColumn(child, n, pad.dataType).flatMap { col =>
+          generateExpression(lit).map { l =>
+            new V2Predicate(name, Array[V2Expression](col, l))
           }
         }
       case _ => None
@@ -528,34 +515,29 @@ class V2ExpressionBuilder(e: Expression, isPredicate: 
Boolean = false) extends L
 
   private def generateCharPadIn(
       value: Expression, list: Seq[Expression]): Option[V2Expression] = value 
match {
-    case invoke: StaticInvoke if isCharReadSidePaddingInvoke(invoke) =>
-      charPadLength(invoke).filter(n => list.nonEmpty && 
list.forall(isFoldableStringOfLen(_, n)))
-        .flatMap { _ =>
-          generateCharPadColumn(invoke).flatMap { col =>
-            val lits = list.flatMap(generateExpression(_))
-            if (lits.length == list.length) {
-              Some(new V2Predicate("IN", (col +: lits).toArray[V2Expression]))
-            } else {
-              None
-            }
-          }
+    case CharVarcharUtils.ReadSidePadding(child, n)
+        if list.nonEmpty && list.forall(isFoldableStringOfLen(_, n)) =>
+      generateCharPadColumn(child, n, value.dataType).flatMap { col =>
+        val lits = list.flatMap(generateExpression(_))
+        if (lits.length == list.length) {
+          Some(new V2Predicate("IN", (col +: lits).toArray[V2Expression]))
+        } else {
+          None
         }
+      }
     case _ => None
   }
 
   private def generateCharPadInSet(
       child: Expression, hset: Set[Any]): Option[V2Expression] = child match {
-    case invoke: StaticInvoke if isCharReadSidePaddingInvoke(invoke) =>
-      charPadLength(invoke).filter { n =>
-        hset.nonEmpty && hset.forall {
+    case CharVarcharUtils.ReadSidePadding(grandChild, n)
+        if hset.nonEmpty && hset.forall {
           case s: UTF8String => s.numChars() == n
           case _ => false
-        }
-      }.flatMap { _ =>
-        generateCharPadColumn(invoke).map { col =>
-          val lits = hset.toSeq.map(elem => LiteralValue(elem, child.dataType))
-          new V2Predicate("IN", (col +: lits).toArray[V2Expression])
-        }
+        } =>
+      generateCharPadColumn(grandChild, n, child.dataType).map { col =>
+        val lits = hset.toSeq.map(elem => LiteralValue(elem, child.dataType))
+        new V2Predicate("IN", (col +: lits).toArray[V2Expression])
       }
     case _ => None
   }
diff --git 
a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/statsEstimation/FilterEstimationSuite.scala
 
b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/statsEstimation/FilterEstimationSuite.scala
index 64e91b8cacdd..d36d0989fcb1 100755
--- 
a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/statsEstimation/FilterEstimationSuite.scala
+++ 
b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/statsEstimation/FilterEstimationSuite.scala
@@ -25,8 +25,9 @@ import org.apache.spark.sql.catalyst.plans.LeftOuter
 import org.apache.spark.sql.catalyst.plans.logical._
 import 
org.apache.spark.sql.catalyst.plans.logical.statsEstimation.ColumnStatsMap
 import 
org.apache.spark.sql.catalyst.plans.logical.statsEstimation.EstimationUtils._
-import org.apache.spark.sql.catalyst.util.DateTimeUtils
+import org.apache.spark.sql.catalyst.util.{CharVarcharUtils, DateTimeUtils}
 import org.apache.spark.sql.types._
+import org.apache.spark.unsafe.types.UTF8String
 
 /**
  * In this test suite, we test predicates containing the following operators:
@@ -963,6 +964,66 @@ class FilterEstimationSuite extends 
StatsEstimationTestBase {
       expectedRowCount = 10)
   }
 
+  test("SPARK-60810: predicates on a read-side padded CHAR column use the 
column's stats") {
+    val padded = CharVarcharUtils.addPaddingForScan(
+      charAttr("cstring", 2).withExprId(attrString.exprId))
+    assert(padded match {
+      case CharVarcharUtils.ReadSidePadding(a: Attribute, _) => a.exprId == 
attrString.exprId
+      case _ => false
+    }, s"expected read-side padding over cstring, got $padded")
+    val child = childStatsTestPlan(Seq(attrString), tableRowCount = 10L)
+    // colStatString has 10 distinct values and no nulls over 10 rows.
+    Seq(
+      EqualTo(padded, Literal("A0")) -> 1,
+      EqualTo(Literal("A0"), padded) -> 1,
+      In(padded, Seq(Literal("A0"), Literal("A1"))) -> 2,
+      InSet(padded, Set(UTF8String.fromString("A0"), 
UTF8String.fromString("A1"))) -> 2,
+      IsNull(padded) -> 0).foreach { case (condition, expectedRows) =>
+      val filter = Filter(condition, child)
+      assert(filter.stats.rowCount.contains(BigInt(expectedRows)), condition)
+    }
+    // With no nulls IS NOT NULL keeps every row, which an unsupported 
predicate does too, so
+    // use a child with nulls. The update lands on the column's own stat (in a 
plan, the padding
+    // Project above passes it on): nullCount becomes 0, where scaling alone 
would give 3.
+    val childWithNulls = childStatsTestPlan(Seq(attrString), tableRowCount = 
10L,
+      attributeMap = AttributeMap(Seq(attrString -> 
colStatString.copy(nullCount = Some(4)))))
+    validateEstimatedStats(
+      Filter(IsNotNull(padded), childWithNulls),
+      Seq(attrString -> colStatString.copy(distinctCount = Some(6), nullCount 
= Some(0))),
+      expectedRowCount = 6)
+    // Under Not the predicate is estimated without update; the output stat is 
only scaled to
+    // the 9 remaining rows.
+    validateEstimatedStats(
+      Filter(Not(EqualTo(padded, Literal("A0"))), child),
+      Seq(attrString -> colStatString.copy(distinctCount = Some(9))),
+      expectedRowCount = 9)
+  }
+
+  test("SPARK-60810: equality on a string or binary column with a reported 
histogram") {
+    // DSv2 connectors can report a histogram for any type. Only numeric-like 
types have
+    // equi-height histograms, so string and binary columns fall back to their 
distinct count.
+    val histogram = Histogram(height = 1, Array(HistogramBin(lo = 0, hi = 10, 
ndv = 10)))
+    val stat = colStatString.copy(min = Some(UTF8String.fromString("A0")),
+      max = Some(UTF8String.fromString("A9")), histogram = Some(histogram))
+    val child = childStatsTestPlan(Seq(attrString), tableRowCount = 10L,
+      attributeMap = AttributeMap(Seq(attrString -> stat)))
+    validateEstimatedStats(
+      Filter(EqualTo(attrString, Literal("A0")), child),
+      Seq(attrString -> stat.copy(distinctCount = Some(1))),
+      expectedRowCount = 1)
+
+    val attrBinary = AttributeReference("cbinary", BinaryType)()
+    val binaryStat = ColumnStat(distinctCount = Some(10), min = 
Some(Array[Byte](0)),
+      max = Some(Array[Byte](9)), nullCount = Some(0), avgLen = Some(1), 
maxLen = Some(1),
+      histogram = Some(histogram))
+    val binaryChild = StatsTestPlan(
+      outputList = Seq(attrBinary),
+      rowCount = 10,
+      attributeStats = AttributeMap(Seq(attrBinary -> binaryStat)))
+    assert(Filter(EqualTo(attrBinary, Literal(Array[Byte](1))), 
binaryChild).stats.rowCount
+      .contains(BigInt(1)))
+  }
+
   test("ColumnStatsMap tests") {
     val attrNoDistinct = AttributeReference("att_without_distinct", 
IntegerType)()
     val attrNoCount = AttributeReference("att_without_count", BooleanType)()
diff --git 
a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/statsEstimation/JoinEstimationSuite.scala
 
b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/statsEstimation/JoinEstimationSuite.scala
index 68567541e197..6eb469677ddf 100644
--- 
a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/statsEstimation/JoinEstimationSuite.scala
+++ 
b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/statsEstimation/JoinEstimationSuite.scala
@@ -21,11 +21,11 @@ import java.sql.{Date, Timestamp}
 
 import scala.collection.mutable
 
-import org.apache.spark.sql.catalyst.expressions.{And, Attribute, 
AttributeMap, AttributeReference, EqualTo}
+import org.apache.spark.sql.catalyst.expressions.{Alias, And, Attribute, 
AttributeMap, AttributeReference, EqualTo}
 import org.apache.spark.sql.catalyst.plans._
 import org.apache.spark.sql.catalyst.plans.logical._
 import 
org.apache.spark.sql.catalyst.plans.logical.statsEstimation.EstimationUtils._
-import org.apache.spark.sql.catalyst.util.DateTimeUtils
+import org.apache.spark.sql.catalyst.util.{CharVarcharUtils, DateTimeUtils}
 import org.apache.spark.sql.types.{DateType, TimestampType, _}
 
 
@@ -560,6 +560,74 @@ class JoinEstimationSuite extends StatsEstimationTestBase {
     assert(join.stats == expectedStats)
   }
 
+  test("SPARK-60810: string and binary join keys with histograms use the 
distinct count") {
+    // DSv2 connectors can report a histogram for any type, but only 
numeric-like keys can be
+    // estimated with one. 10 x 10 rows with 10 distinct values on each side 
give 10 rows.
+    val histogram = Histogram(height = 1, Array(HistogramBin(lo = 0, hi = 10, 
ndv = 10)))
+    val stat = ColumnStat(distinctCount = Some(10), nullCount = Some(0), 
avgLen = Some(1),
+      maxLen = Some(1), histogram = Some(histogram))
+    def side(key: Attribute): LogicalPlan =
+      StatsTestPlan(Seq(key), 10, AttributeMap(Seq(key -> stat)))
+    def joinRows(left: LogicalPlan, right: LogicalPlan): Option[BigInt] = 
Join(left, right, Inner,
+      Some(EqualTo(left.output.head, right.output.head)), 
JoinHint.NONE).stats.rowCount
+
+    Seq(StringType, BinaryType).foreach { dt =>
+      val rows = joinRows(side(AttributeReference("l", dt)()), 
side(AttributeReference("r", dt)()))
+      assert(rows.contains(BigInt(10)), dt)
+    }
+
+    // CHAR keys reach the join through the read-side padding Project, which 
passes the
+    // column's statistics, histogram included, to its alias.
+    def paddedSide(name: String): LogicalPlan = {
+      val c = charAttr(name, 5)
+      Project(Seq(Alias(CharVarcharUtils.addPaddingForScan(c), name)()), 
side(c))
+    }
+    assert(joinRows(paddedSide("l"), paddedSide("r")).contains(BigInt(10)))
+  }
+
+  test("SPARK-60810: boolean join keys with histograms use the histogram 
estimate") {
+    // A DSv2 connector can report a histogram for a boolean column. The 
intersected bounds come
+    // back as Booleans and must be converted like the filter's histogram 
estimate does.
+    // 8 false and 4 true values on each side.
+    val histogram = Histogram(height = 4, Array(HistogramBin(lo = 0, hi = 0, 
ndv = 1),
+      HistogramBin(lo = 0, hi = 0, ndv = 1), HistogramBin(lo = 1, hi = 1, ndv 
= 1)))
+    val stat = ColumnStat(distinctCount = Some(2), min = Some(false), max = 
Some(true),
+      nullCount = Some(0), avgLen = Some(1), maxLen = Some(1), histogram = 
Some(histogram))
+    def side(name: String): LogicalPlan = {
+      val key = AttributeReference(name, BooleanType)()
+      StatsTestPlan(Seq(key), 12, AttributeMap(Seq(key -> stat)))
+    }
+    val (left, right) = (side("l"), side("r"))
+    val join = Join(left, right, Inner, Some(EqualTo(left.output.head, 
right.output.head)),
+      JoinHint.NONE)
+    // 8 x 8 + 4 x 4 from the histograms. The distinct count alone would give 
12 x 12 / 2 = 72.
+    assert(join.stats.rowCount.contains(BigInt(80)))
+  }
+
+  test("SPARK-60810: join keys without non-null values match no rows") {
+    // ANALYZE stores a distinct count of 0 for a column of nulls, and an IS 
NULL filter sets
+    // it. Padded CHAR keys get the column's statistics through the padding 
Project.
+    val nullStat = ColumnStat(distinctCount = Some(0), nullCount = Some(10), 
avgLen = Some(5),
+      maxLen = Some(5))
+    def nullSide(key: Attribute): LogicalPlan =
+      StatsTestPlan(Seq(key), 10, AttributeMap(Seq(key -> nullStat)))
+    def paddedSide(name: String): LogicalPlan = {
+      val c = charAttr(name, 5)
+      Project(Seq(Alias(CharVarcharUtils.addPaddingForScan(c), name)()), 
nullSide(c))
+    }
+    def stringSide(name: String): LogicalPlan = 
nullSide(AttributeReference(name, StringType)())
+    Seq(
+      paddedSide("l") -> paddedSide("r"),
+      paddedSide("l") -> stringSide("r"),
+      stringSide("l") -> stringSide("r")).foreach { case (left, right) =>
+      val condition = Some(EqualTo(left.output.head, right.output.head))
+      assert(Join(left, right, Inner, condition, JoinHint.NONE).stats.rowCount
+        .contains(BigInt(0)))
+      assert(Join(left, right, FullOuter, condition, 
JoinHint.NONE).stats.rowCount
+        .contains(BigInt(20)))
+    }
+  }
+
   test("SPARK-33018 Fix estimate statistics issue if child has 0 bytes") {
     case class MyStatsTestPlan(
         outputList: Seq[Attribute],
diff --git 
a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/statsEstimation/ProjectEstimationSuite.scala
 
b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/statsEstimation/ProjectEstimationSuite.scala
index 8efb41d8b3c2..b6e6d2e662d3 100644
--- 
a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/statsEstimation/ProjectEstimationSuite.scala
+++ 
b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/statsEstimation/ProjectEstimationSuite.scala
@@ -21,7 +21,7 @@ import java.sql.{Date, Timestamp}
 
 import org.apache.spark.sql.catalyst.expressions.{Alias, Attribute, 
AttributeMap, AttributeReference, Literal}
 import org.apache.spark.sql.catalyst.plans.logical._
-import org.apache.spark.sql.catalyst.util.DateTimeUtils
+import org.apache.spark.sql.catalyst.util.{CharVarcharUtils, DateTimeUtils}
 import org.apache.spark.sql.types._
 
 
@@ -163,6 +163,66 @@ class ProjectEstimationSuite extends 
StatsEstimationTestBase {
     assert(proj2.stats == expectedStats2)
   }
 
+  test("SPARK-60810: column stats of a CHAR column survive read-side padding") 
{
+    val c = charAttr("c", 5)
+    val colStat = ColumnStat(distinctCount = Some(10), nullCount = Some(0),
+      avgLen = Some(5), maxLen = Some(5))
+    val child = StatsTestPlan(
+      outputList = Seq(c),
+      rowCount = 1000,
+      attributeStats = AttributeMap(Seq(c -> colStat)))
+
+    val padded = CharVarcharUtils.addPaddingForScan(c)
+    assert(padded != c, "expected a read-side padding expression for a CHAR 
column")
+    val proj = Project(Seq(Alias(padded, "c")()), child)
+    assert(proj.stats.attributeStats.get(proj.output.head).contains(colStat))
+
+    // Statistics of values shorter than N, e.g. collected with read-side 
padding off: every
+    // non-null padded value has at least N characters.
+    val shortStat = colStat.copy(avgLen = Some(3), maxLen = Some(4))
+    val shortChild = child.copy(attributeStats = AttributeMap(Seq(c -> 
shortStat)))
+    val shortProj = Project(Seq(Alias(padded, "c")()), shortChild)
+    
assert(shortProj.stats.attributeStats.get(shortProj.output.head).contains(colStat))
+    // The same without a distinct count, e.g. from a connector that reports 
only lengths.
+    val noNdvChild = child.copy(
+      attributeStats = AttributeMap(Seq(c -> shortStat.copy(distinctCount = 
None))))
+    val noNdvProj = Project(Seq(Alias(padded, "c")()), noNdvChild)
+    assert(noNdvProj.stats.attributeStats.get(noNdvProj.output.head)
+      .contains(colStat.copy(distinctCount = None)))
+    // Padding leaves longer values as they are, so lengths above N are kept.
+    val longStat = colStat.copy(avgLen = Some(7), maxLen = Some(9))
+    val longProj = Project(Seq(Alias(padded, "c")()),
+      child.copy(attributeStats = AttributeMap(Seq(c -> longStat))))
+    
assert(longProj.stats.attributeStats.get(longProj.output.head).contains(longStat))
+
+    // An all-null column has no values to pad; ANALYZE stores the default 
size of the string
+    // type, 20, as its lengths, which a CHAR(30) floor must not raise.
+    val wide = charAttr("w", 30)
+    val nullStat = ColumnStat(distinctCount = Some(0), nullCount = Some(1000),
+      avgLen = Some(20), maxLen = Some(20))
+    val nullChild = StatsTestPlan(
+      outputList = Seq(wide),
+      rowCount = 1000,
+      attributeStats = AttributeMap(Seq(wide -> nullStat)))
+    val nullProj = Project(Seq(Alias(CharVarcharUtils.addPaddingForScan(wide), 
"w")()), nullChild)
+    
assert(nullProj.stats.attributeStats.get(nullProj.output.head).contains(nullStat))
+    // An IS NULL filter below the padding Project sets the distinct count to 
0 and scales the
+    // null count down, so it no longer covers every row the filter returns.
+    val isNullStat = ColumnStat(distinctCount = Some(0), nullCount = Some(200),
+      avgLen = Some(3), maxLen = Some(4))
+    val isNullProj = Project(Seq(Alias(padded, "c")()),
+      child.copy(attributeStats = AttributeMap(Seq(c -> isNullStat))))
+    
assert(isNullProj.stats.attributeStats.get(isNullProj.output.head).contains(isNullStat))
+    // A null count covering every row is not a sign of no values: a filter 
that leaves 1 of
+    // 1000 rows scales 999 nulls up to 1, while the column still has a value.
+    val scaledStat = ColumnStat(distinctCount = Some(1), nullCount = Some(1),
+      avgLen = Some(2), maxLen = Some(2))
+    val scaledProj = Project(Seq(Alias(padded, "c")()), child.copy(rowCount = 
1,
+      attributeStats = AttributeMap(Seq(c -> scaledStat))))
+    assert(scaledProj.stats.attributeStats.get(scaledProj.output.head)
+      .contains(scaledStat.copy(avgLen = Some(5), maxLen = Some(5))))
+  }
+
   private def checkProjectStats(
       child: LogicalPlan,
       projectAttrMap: AttributeMap[ColumnStat],
diff --git 
a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/statsEstimation/StatsEstimationTestBase.scala
 
b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/statsEstimation/StatsEstimationTestBase.scala
index 2564effbf25a..856a76b073c3 100644
--- 
a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/statsEstimation/StatsEstimationTestBase.scala
+++ 
b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/statsEstimation/StatsEstimationTestBase.scala
@@ -21,8 +21,10 @@ import org.apache.spark.SparkFunSuite
 import org.apache.spark.sql.catalyst.analysis.MultiInstanceRelation
 import org.apache.spark.sql.catalyst.expressions.{Attribute, AttributeMap, 
AttributeReference}
 import org.apache.spark.sql.catalyst.plans.logical.{ColumnStat, LeafNode, 
LogicalPlan, Statistics}
+import org.apache.spark.sql.catalyst.types.DataTypeUtils
+import org.apache.spark.sql.catalyst.util.CharVarcharUtils
 import org.apache.spark.sql.internal.SQLConf
-import org.apache.spark.sql.types.{IntegerType, StringType}
+import org.apache.spark.sql.types.{CharType, IntegerType, StringType, 
StructField, StructType}
 
 
 trait StatsEstimationTestBase extends SparkFunSuite {
@@ -52,6 +54,11 @@ trait StatsEstimationTestBase extends SparkFunSuite {
 
   def attr(colName: String): AttributeReference = AttributeReference(colName, 
IntegerType)()
 
+  /** A CHAR(n) column as a table scan outputs it, before read-side padding. */
+  def charAttr(colName: String, n: Int): AttributeReference =
+    
DataTypeUtils.toAttribute(CharVarcharUtils.replaceCharVarcharWithStringInSchema(
+      StructType(Seq(StructField(colName, CharType(n))))).head)
+
   /** Convert (column name, column stat) pairs to an AttributeMap based on 
plan output. */
   def toAttributeMap(colStats: Seq[(String, ColumnStat)], plan: LogicalPlan)
     : AttributeMap[ColumnStat] = {
diff --git 
a/sql/catalyst/src/test/scala/org/apache/spark/sql/execution/datasources/v2/DataSourceV2RelationSuite.scala
 
b/sql/catalyst/src/test/scala/org/apache/spark/sql/execution/datasources/v2/DataSourceV2RelationSuite.scala
index 8f4d300be61d..a89edf0e714c 100644
--- 
a/sql/catalyst/src/test/scala/org/apache/spark/sql/execution/datasources/v2/DataSourceV2RelationSuite.scala
+++ 
b/sql/catalyst/src/test/scala/org/apache/spark/sql/execution/datasources/v2/DataSourceV2RelationSuite.scala
@@ -27,6 +27,8 @@ import org.apache.spark.sql.catalyst.plans.SQLHelper
 import org.apache.spark.sql.catalyst.plans.logical.{Filter, Histogram, 
HistogramBin, Project}
 import 
org.apache.spark.sql.catalyst.plans.logical.statsEstimation.EstimationUtils
 import org.apache.spark.sql.catalyst.trees.{TreeNodeTag, TreePattern}
+import org.apache.spark.sql.catalyst.types.DataTypeUtils
+import org.apache.spark.sql.catalyst.util.CharVarcharUtils
 import 
org.apache.spark.sql.catalyst.util.FieldMetadataUtils.FIELD_ID_METADATA_KEY
 import org.apache.spark.sql.catalyst.util.INTERNAL_METADATA_KEYS
 import org.apache.spark.sql.connector.catalog.{Column, MetadataColumn, 
SupportsMetadataColumns, Table, TableCapability}
@@ -34,7 +36,7 @@ import 
org.apache.spark.sql.connector.expressions.{FieldReference, NamedReferenc
 import org.apache.spark.sql.connector.read.{Scan, Statistics => V2Statistics, 
SupportsReportStatistics}
 import org.apache.spark.sql.connector.read.colstats.ColumnStatistics
 import org.apache.spark.sql.internal.SQLConf
-import org.apache.spark.sql.types.{DataType, IntegerType, MetadataBuilder, 
StringType, StructField, StructType}
+import org.apache.spark.sql.types.{CharType, DataType, IntegerType, 
MetadataBuilder, StringType, StructField, StructType}
 import org.apache.spark.sql.util.CaseInsensitiveStringMap
 
 class DataSourceV2RelationSuite extends SparkFunSuite with SQLHelper {
@@ -219,6 +221,35 @@ class DataSourceV2RelationSuite extends SparkFunSuite with 
SQLHelper {
     }
   }
 
+  test("SPARK-60810: pushed and inferred filters on a read-side padded CHAR 
column") {
+    withSQLConf(SQLConf.CBO_ENABLED.key -> "true") {
+      val c = 
DataTypeUtils.toAttribute(CharVarcharUtils.replaceCharVarcharWithStringInSchema(
+        StructType(Seq(StructField("c", CharType(5))))).head)
+      val schema = StructType(Seq(StructField("c", StringType)))
+      val scan = new Scan with SupportsReportStatistics {
+        override def readSchema(): StructType = schema
+        override def estimateStatistics(): V2Statistics = 
DataSourceV2Relation.v1StatsToV2Stats(
+          CatalogStatistics(sizeInBytes = 16000, rowCount = 
Some(BigInt(1000)), colStats = Map(
+            "c" -> CatalogColumnStat(distinctCount = Some(10), nullCount = 
Some(200),
+              avgLen = Some(5), maxLen = Some(5)))),
+          schema)
+        override def reflectsFullyPushedDownFilters(): Boolean = false
+        override def useInferredFilterEstimation(): Boolean = true
+      }
+      // Filters pushed into a scan compare the padding expression, like a 
Filter pushed below
+      // the padding Project. Of 1000 rows the equality keeps 100 and IS NOT 
NULL keeps 800, and
+      // the smaller estimate of the two groups wins; STARTSWITH cannot be 
estimated.
+      val padded = CharVarcharUtils.addPaddingForScan(c)
+      Seq(
+        EqualTo(padded, Literal("3    ")) -> 100,
+        StartsWith(padded, Literal("3")) -> 800).foreach { case (pushed, 
expectedRows) =>
+        val withFilters = scanRel(Seq(c), scan).copy(
+          pushedFilters = Seq(pushed), inferredFilters = 
Seq(IsNotNull(padded)))
+        assert(withFilters.stats.rowCount.contains(BigInt(expectedRows)), 
pushed)
+      }
+    }
+  }
+
   test("inferred filters improve estimates for opaque original predicates") {
     withSQLConf(SQLConf.CBO_ENABLED.key -> "true") {
       val base = scanWithCorrelatedColumns()
diff --git 
a/sql/core/src/test/scala/org/apache/spark/sql/StatisticsCollectionSuite.scala 
b/sql/core/src/test/scala/org/apache/spark/sql/StatisticsCollectionSuite.scala
index 42bff6f6c606..cd3cc638ccfd 100644
--- 
a/sql/core/src/test/scala/org/apache/spark/sql/StatisticsCollectionSuite.scala
+++ 
b/sql/core/src/test/scala/org/apache/spark/sql/StatisticsCollectionSuite.scala
@@ -33,6 +33,7 @@ import org.apache.spark.sql.catalyst.util.{DateTimeTestUtils, 
DateTimeUtils}
 import 
org.apache.spark.sql.catalyst.util.DateTimeTestUtils.{withDefaultTimeZone, PST, 
UTC}
 import org.apache.spark.sql.catalyst.util.DateTimeUtils.{getZoneId, 
TimeZoneUTC}
 import org.apache.spark.sql.execution.LogicalRDD
+import org.apache.spark.sql.execution.datasources.LogicalRelation
 import org.apache.spark.sql.functions.timestamp_seconds
 import org.apache.spark.sql.internal.SQLConf
 import org.apache.spark.sql.test.SharedSparkSession
@@ -202,6 +203,90 @@ class StatisticsCollectionSuite extends 
StatisticsCollectionTestBase with Shared
     }
   }
 
+  test("SPARK-60810: CBO keeps CHAR column statistics through read-side 
padding") {
+    withSQLConf(
+        SQLConf.CBO_ENABLED.key -> "true",
+        SQLConf.READ_SIDE_CHAR_PADDING.key -> "true") {
+      val tableName = "char_read_side_padding_stats"
+      withTable(tableName) {
+        sql(s"CREATE TABLE $tableName(c CHAR(5)) USING parquet")
+        sql(s"INSERT INTO $tableName SELECT CAST(id % 10 AS STRING) FROM 
range(1000)")
+        sql(s"ANALYZE TABLE $tableName COMPUTE STATISTICS FOR COLUMNS c")
+
+        def estimatedRows(query: String)(
+            pick: PartialFunction[LogicalPlan, LogicalPlan]): Option[BigInt] = 
{
+          val plan = sql(query).queryExecution.optimizedPlan
+          plan.collectFirst(pick).getOrElse(fail(s"no matching node 
in\n${plan.treeString}"))
+            .stats.rowCount
+        }
+        // Above the padding Project, which carries the column's statistics.
+        assert(estimatedRows(s"SELECT c, count(*) FROM $tableName GROUP BY c") 
{
+          case a: Aggregate => a
+        }.contains(BigInt(10)))
+        // Pushed below it, where the predicate compares the padding 
expression itself.
+        assert(estimatedRows(s"SELECT * FROM $tableName WHERE c = '3'") {
+          case f: Filter => f
+        }.contains(BigInt(100)))
+        assert(estimatedRows(s"SELECT * FROM $tableName WHERE c IN ('3', 
'4')") {
+          case f: Filter => f
+        }.contains(BigInt(200)))
+      }
+    }
+  }
+
+  test("SPARK-60810: CBO plans an outer join on CHAR columns that hold only 
nulls") {
+    withSQLConf(
+        SQLConf.CBO_ENABLED.key -> "true",
+        SQLConf.READ_SIDE_CHAR_PADDING.key -> "true") {
+      withTable("char_nulls_a", "char_nulls_b", "char_nulls_c") {
+        Seq("char_nulls_a", "char_nulls_b").foreach { t =>
+          sql(s"CREATE TABLE $t(id INT, c CHAR(5)) USING parquet")
+          sql(s"INSERT INTO $t SELECT CAST(id AS INT), CAST(NULL AS STRING) 
FROM range(10)")
+          sql(s"ANALYZE TABLE $t COMPUTE STATISTICS FOR COLUMNS id, c")
+        }
+        sql("CREATE TABLE char_nulls_c(x INT) USING parquet")
+        sql("INSERT INTO char_nulls_c VALUES (1)")
+        sql("ANALYZE TABLE char_nulls_c COMPUTE STATISTICS FOR COLUMNS x")
+
+        // The padded keys carry a distinct count of 0 on both sides, so they 
match no rows and
+        // the full outer join keeps the rows of both sides.
+        val df = sql(
+          """SELECT * FROM (
+            |  SELECT a.id AS aid, b.id AS bid
+            |  FROM char_nulls_a a FULL OUTER JOIN char_nulls_b b ON a.c = 
b.c) j
+            |CROSS JOIN char_nulls_c""".stripMargin)
+        val plan = df.queryExecution.optimizedPlan
+        val fullOuter = plan.collectFirst {
+          case j: Join if j.joinType == 
org.apache.spark.sql.catalyst.plans.FullOuter => j
+        }.getOrElse(fail(s"no full outer join in\n${plan.treeString}"))
+        assert(fullOuter.stats.rowCount.contains(BigInt(20)), plan.treeString)
+        checkAnswer(df.selectExpr("count(*)"), Row(20))
+      }
+    }
+  }
+
+  test("SPARK-60810: partition pruning estimates a filter on a CHAR partition 
column") {
+    withSQLConf(
+        SQLConf.CBO_ENABLED.key -> "true",
+        SQLConf.READ_SIDE_CHAR_PADDING.key -> "true") {
+      val tableName = "char_partition_pruning_stats"
+      withTable(tableName) {
+        sql(s"CREATE TABLE $tableName(v INT, p CHAR(5)) USING parquet 
PARTITIONED BY (p)")
+        sql(s"INSERT INTO $tableName SELECT CAST(id AS INT), CAST(id % 10 AS 
STRING) " +
+          "FROM range(1000)")
+        sql(s"ANALYZE TABLE $tableName COMPUTE STATISTICS FOR COLUMNS v, p")
+
+        // PruneFileSourcePartitions estimates the pushed-down partition 
filter, which compares
+        // the padding expression, and saves the result as the pruned 
relation's statistics.
+        val plan = sql(s"SELECT * FROM $tableName WHERE p = 
'3'").queryExecution.optimizedPlan
+        val prunedStats = plan.collectFirst {
+          case l: LogicalRelation => l.catalogTable.flatMap(_.stats)
+        }.flatten.getOrElse(fail(s"no catalog statistics 
in\n${plan.treeString}"))
+        assert(prunedStats.rowCount.contains(BigInt(100)), plan.treeString)
+      }
+    }
+  }
+
   test("test table-level statistics for data source table") {
     val tableName = "tbl"
     withTable(tableName) {


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to