gengliangwang commented on code in PR #60750:
URL: https://github.com/apache/spark/pull/60750#discussion_r4640943648


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ApplyCharTypePaddingHelper.scala:
##########
@@ -48,6 +49,22 @@ object ApplyCharTypePaddingHelper {
     }
   }
 
+  /**
+   * A column, or a field of a struct column reached through 
[[GetStructField]], with the raw type
+   * of that column or field. The raw type is the one recorded in the column's 
metadata, so a CHAR
+   * or VARCHAR field keeps its length although its data type is a string.
+   */
+  object RawTypedRef {
+    def unapply(e: Expression): Option[DataType] = e match {
+      case AttrOrOuterRef(attr) => CharVarcharUtils.getRawType(attr.metadata)
+      case GetStructField(child, ordinal, _) =>
+        unapply(child).collect {
+          case struct: StructType if ordinal < struct.length => 
struct(ordinal).dataType

Review Comment:
   **[P1] [P1] Account for reordered fields before indexing the raw struct**
   
   The current field ordinal need not match the raw metadata's ordinal. 
`Dataset.to` calls `Project.matchSchema`, which reorders nested fields while 
`createNewColumn` preserves the original column metadata. After the reordering 
below, this extractor identifies STRING field `v` as the original CHAR field 
`c`. With default read-side padding, `padAttrLitCmp` consequently pads only the 
literal to `'a  '`, making the previously correct STRING equality false. Align 
the raw schema with the current fields before selecting their types.
   
   **Failure scenario:** Create t(s STRUCT<c: CHAR(3), v: STRING>) USING 
PARQUET and insert (named_struct('c', 'x', 'v', 'a')). Evaluate 
spark.table("t").to(StructType.fromDDL("s STRUCT<v: STRING, c: 
STRING>")).selectExpr("s.v = 'a'"). The result becomes false instead of true.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ApplyCharTypePaddingHelper.scala:
##########
@@ -84,46 +101,37 @@ object ApplyCharTypePaddingHelper {
     expression match {
       // 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, padCharCol, lit)
+      case b @ BinaryComparison(e @ RawTypedRef(c: CharType), lit) if 
lit.foldable =>

Review Comment:
   **[P2] [P2] Require a resolved comparison before evaluating its constant**
   
   The surrounding traversal checks only `childrenResolved`, so an invalid 
comparison can enter this newly expanded case. For `s.c = array(1)`, both 
children resolve, but type coercion leaves their incompatible STRING and ARRAY 
types unchanged. The fixed-point analyzer runs this rule before 
`CheckAnalysis`; `padAttrLitCmp` therefore casts the array's `GenericArrayData` 
result to `UTF8String`, throwing ClassCastException instead of the normal 
datatype analysis error. Require a resolved comparison or a string-typed 
constant in both binary-comparison cases, as the IN case already does.
   
   **Failure scenario:** For t(s STRUCT<c: CHAR(3)>), run SELECT s.c = array(1) 
FROM t using the default fixed-point analyzer. This now throws 
ClassCastException instead of DATATYPE_MISMATCH.BINARY_OP_DIFF_TYPES.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ApplyCharTypePaddingHelper.scala:
##########
@@ -163,33 +171,29 @@ object ApplyCharTypePaddingHelper {
 
   private def padAttrLitCmp(
       expr: Expression,
-      metadata: Metadata,
+      c: CharType,
       padCharCol: Boolean,
       lit: Expression): Option[Seq[Expression]] = {
     if (expr.dataType.isInstanceOf[StringType]) {
-      CharVarcharUtils.getRawType(metadata).flatMap {
-        case c: CharType =>
-          val str = lit.eval().asInstanceOf[UTF8String]
-          if (str == null) {
-            None
+      val str = lit.eval().asInstanceOf[UTF8String]

Review Comment:
   **[P1] [P1] Preserve conditional evaluation when inspecting foldable 
strings**
   
   The expanded matcher now sends struct-field comparisons through this 
unconditional evaluation during analysis. A foldable string expression can 
still throw, and `paddingForStringComparison` visits comparisons inside 
unchosen conditional branches. Unlike `ConstantFolding.tryFold`, this 
evaluation does not suppress failures inside such branches, so the example now 
raises DIVIDE_BY_ZERO before the optimizer can discard the branch. The new IN 
path has the same issue. Leave failing constants for normal conditional-aware 
evaluation instead of propagating their exceptions here.
   
   **Failure scenario:** With spark.sql.ansi.enabled=true and a populated table 
t(s STRUCT<c: CHAR(3)>), run SELECT IF(false, s.c = CAST(1 / 0 AS STRING), 
true) FROM t. It should return true for every row, as before this change, but 
now fails during analysis.



-- 
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]

Reply via email to