dongjoon-hyun commented on code in PR #60750:
URL: https://github.com/apache/spark/pull/60750#discussion_r4647438098


##########
sql/core/src/test/scala/org/apache/spark/sql/CharVarcharTestSuite.scala:
##########
@@ -660,6 +660,59 @@ trait CharVarcharTestSuite extends QueryTest {
     }
   }
 
+  test("SPARK-61970: char type comparison: struct field and string literal") {

Review Comment:
   **[2] The tests cover struct fields in a projection only.**
   
   All three tests compare struct fields under the default read-side padding, 
and `testConditions` evaluates the comparisons in a projection. These paths of 
the change are not covered:
   
   - Top-level columns. The type check from [1] and `tryEvalString` change 
their behavior too, as [the 
reply](https://github.com/apache/spark/pull/60750#discussion_r4642170943) on 
the earlier thread says. For example, `IF(false, c = CAST(1 / 0 AS STRING), 
true)` on a top-level CHAR column now passes analysis under ANSI, and the 
`Dataset.to` case in [1] no longer matches.
   - `spark.sql.readSideCharPadding=false`, where `padCharCol` is true and the 
field side gets an `rpad` as well.
   - An outer reference to a struct field, e.g. `EXISTS (SELECT 1 FROM range(1) 
WHERE t.s.c = 'a')`.
   - A `WHERE` filter, which is the example in the PR description. A filter 
goes through filter pushdown, and a projection does not.
   - DELETE, UPDATE and MERGE conditions on a struct CHAR field of a DSv2 
table. `padDeleteConditions`, `padRowLevelConditions` and 
`ResolveRowLevelCommandAssignments` all go through this matcher, so their 
struct-field conditions are now padded too.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ApplyCharTypePaddingHelper.scala:
##########
@@ -48,6 +53,37 @@ 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 {
+    // A value whose type no longer matches its raw type, e.g. after a cast, 
has none.
+    def unapply(e: Expression): Option[DataType] = rawType(e).filter { rawType 
=>
+      DataTypeUtils.equalsIgnoreNullability(
+        CharVarcharUtils.replaceCharVarcharWithString(rawType), e.dataType)
+    }
+
+    private def rawType(e: Expression): Option[DataType] = e match {
+      case AttrOrOuterRef(attr) => CharVarcharUtils.getRawType(attr.metadata)
+      case GetStructField(child, ordinal, _) =>
+        child.dataType match {
+          case current: StructType if ordinal < current.length =>
+            // Look the field up by name, as Dataset.to matches fields: it can 
reorder and
+            // rename the fields of a struct at any level, and keeps the 
column's metadata.
+            val name = current(ordinal).name
+            rawType(child).flatMap {
+              case raw: StructType => raw.fields.find(f => 
SQLConf.get.resolver(f.name, name))

Review Comment:
   **[3] The field lookup ignores the ordinal.**
   
   `find` returns the first field whose name matches under the resolver, 
wherever it is, even when the raw struct is aligned with the current one, which 
is the usual case. A struct can have names that differ only in case when it was 
created under `spark.sql.caseSensitive=true`, e.g. `s STRUCT<a: CHAR(3), A: 
STRING>`. If a reference to `A` is then padded under a case-insensitive 
resolver, `find` returns `a`, the type check passes because both are strings, 
and the literal compared with the STRING field `A` is padded to 3 characters. 
This is a corner case, and I haven't found a common path into it. But checking 
the field at `ordinal` first, and using the resolver only when its name 
differs, as after `Dataset.to`, keeps the usual case exact and skips the scan. 
It combines the two options from [the earlier 
thread](https://github.com/apache/spark/pull/60750#discussion_r4642353996):
   
   ```scala
   rawType(child).flatMap {
     case raw: StructType =>
       raw.lift(ordinal).filter(_.name == name)
         .orElse(raw.fields.find(f => SQLConf.get.resolver(f.name, name)))
     case _ => None
   }.map(_.dataType)
   ```



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ApplyCharTypePaddingHelper.scala:
##########
@@ -84,46 +120,41 @@ 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 
isStringConstant(lit) =>

Review Comment:
   **[5] Nit: the raw type is parsed before the constant guard.**
   
   Scala runs the extractor before the guard, so `RawTypedRef` parses the type 
string in the metadata (`CatalystSqlParser.parseDataType`) before 
`isStringConstant(lit)` is checked. For `c1 = c2` on two CHAR columns, this 
case parses `c1` and fails the guard, the next case parses `c2` and fails the 
guard, and the column case then parses both again in 
`addPaddingInStringComparison`. Before this PR, the first two cases only parsed 
when the other side was foldable. Checking the guard first avoids that, and the 
same works for the reversed case:
   
   ```scala
   case b @ BinaryComparison(e, lit) if isStringConstant(lit) => e match {
     case RawTypedRef(c: CharType) =>
       padAttrLitCmp(e, c, padCharCol, lit).map(b.withNewChildren).getOrElse(b)
     case _ => b
   }
   ```
   
   Returning `b` in the second case does not skip a later case: with a constant 
on the right, neither the reversed case nor the column case can match.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ApplyCharTypePaddingHelper.scala:
##########
@@ -48,6 +53,37 @@ 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 {
+    // A value whose type no longer matches its raw type, e.g. after a cast, 
has none.
+    def unapply(e: Expression): Option[DataType] = rawType(e).filter { rawType 
=>

Review Comment:
   **[1] The exact type check also drops the padding of a top-level CHAR column 
whose type changed.**
   
   `RawTypedRef` now requires `replaceCharVarcharWithString(rawType)` to equal 
the value's type, and this check applies to top-level columns too. Before this 
PR, `padAttrLitCmp` padded a top-level CHAR column whenever its type was a 
`StringType`. So a CHAR column whose collation changed while it kept its 
metadata, as `Project.reorderFields` does for `Dataset.to`, loses the padding 
of its literals:
   
   ```scala
   sql("CREATE TABLE t(c CHAR(3)) USING parquet")
   sql("INSERT INTO t VALUES ('a')")
   val df = spark.table("t").to(StructType.fromDDL("c STRING COLLATE 
UTF8_LCASE"))
   df.where("c = 'a'")
   ```
   
   On Spark 4.3.0, `df.where("c = 'a'")` analyzes to `Filter (c#95 = rpad(a, 3, 
 ))`, and `df.selectExpr("c = 'a'")` returns true. With this PR, the raw type 
`char(3)` becomes `StringType` (UTF8_BINARY), which is not equal to the `STRING 
COLLATE UTF8_LCASE` type of `c`. So `RawTypedRef` returns `None`, the literal 
stays `'a'`, and it no longer matches the read-padded `'a  '`. (I checked the 
4.3.0 side locally; the PR side follows from the check above.) This also 
contradicts the PR description, which says that for a column, `RawTypedRef` 
returns the same raw type as before.
   
   The check on the leaf, from [the earlier 
thread](https://github.com/apache/spark/pull/60750#discussion_r4642353982), can 
stay. It only needs to accept any string for a CHAR raw type, as 
`padAttrLitCmp` did. That still rejects a field that `Dataset.to` casts to, 
say, `INT`:
   
   ```scala
   def unapply(e: Expression): Option[DataType] = rawType(e).filter {
     case _: CharType => e.dataType.isInstanceOf[StringType]
     case rawType => DataTypeUtils.equalsIgnoreNullability(
       CharVarcharUtils.replaceCharVarcharWithString(rawType), e.dataType)
   }
   ```



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ApplyCharTypePaddingHelper.scala:
##########
@@ -84,46 +120,41 @@ 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 
isStringConstant(lit) =>
+        padAttrLitCmp(e, c, padCharCol, lit)
           .map { newChildren =>
             b.withNewChildren(newChildren)
           }
           .getOrElse(b)
 
-      case b @ BinaryComparison(lit, e @ AttrOrOuterRef(attr)) if lit.foldable 
=>
-        padAttrLitCmp(e, attr.metadata, padCharCol, lit)
+      case b @ BinaryComparison(lit, e @ RawTypedRef(c: CharType)) if 
isStringConstant(lit) =>
+        padAttrLitCmp(e, c, padCharCol, lit)
           .map { newChildren =>
             b.withNewChildren(newChildren.reverse)
           }
           .getOrElse(b)
 
-      case i @ In(e @ AttrOrOuterRef(attr), list)
-          if i.resolved && attr.dataType.isInstanceOf[StringType] && 
list.forall(_.foldable) =>
-        CharVarcharUtils
-          .getRawType(attr.metadata)
-          .flatMap {
-            case c: CharType =>
-              // Compute the length of every list element in place, so that 
each length stays
-              // aligned with the element it came from. NULL elements have no 
length: they can
-              // never match, so they are left untouched instead of being 
padded.
-              val literalCharLengths = list.map { lit =>
-                Option(lit.eval().asInstanceOf[UTF8String]).map(_.numChars())
-              }
-              val targetLen = (c.length +: literalCharLengths.flatten).max
-              Some(
-                i.copy(
-                  value = addPadding(e, c.length, targetLen, alwaysPad = 
padCharCol),
-                  list = list.zip(literalCharLengths).map {
-                    case (lit, Some(charLength)) =>
-                      addPadding(lit, charLength, targetLen, alwaysPad = false)
-                    case (lit, None) => lit
-                  }
-                )
-              )
-            case _ => None
-          }
-          .getOrElse(i)
+      case i @ In(e @ RawTypedRef(c: CharType), list)
+          if i.resolved && e.dataType.isInstanceOf[StringType] && 
list.forall(_.foldable) =>
+        val values = list.map(tryEvalString)
+        if (values.exists(_.isEmpty)) {

Review Comment:
   **[4] One failing element leaves the whole IN unpadded.**
   
   When any element fails to evaluate, the `In` is returned as is, so the 
elements that evaluate fine are not padded either. `In` stops at the first 
match, so padding them would let a row that matches an earlier element return 
true without reaching the failing one. For example, for `t(id INT, s STRUCT<c: 
CHAR(3)>)` under ANSI:
   
   ```sql
   SELECT CASE WHEN id = 1 THEN s.c IN ('a', CAST(1 / 0 AS STRING)) END FROM t
   ```
   
   `ConstantFolding` keeps the failing element, since it is inside a 
conditional expression. For a row with `id = 1` and `s.c = 'a'`, the unpadded 
`'a'` does not match `'a  '`, so `In` goes on to the failing element and the 
query fails with `DIVIDE_BY_ZERO`. If the elements that evaluate were padded, 
with the target length taken from them and the failing ones left as they are, 
the first element would match and the row would return true. This is not a 
regression, since the struct field was not padded at all before, so feel free 
to keep it if you prefer the simpler rule. Padding per element would be closer 
to `ConstantFolding`, which also folds the elements it can.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ApplyCharTypePaddingHelper.scala:
##########
@@ -161,35 +192,48 @@ object ApplyCharTypePaddingHelper {
       case other => other
     }
 
+  private def isStringConstant(e: Expression): Boolean =
+    e.foldable && e.dataType.isInstanceOf[StringType]
+
+  /**
+   * Evaluates a foldable string expression: Some(value), with a null value 
for NULL, or None if
+   * it fails. The comparison may be in a branch that is never evaluated, so 
as in
+   * ConstantFolding, the failure is left to the evaluation of the query.
+   */
+  private def tryEvalString(e: Expression): Option[Option[UTF8String]] = {
+    try {
+      Some(Option(e.eval().asInstanceOf[UTF8String]))
+    } catch {
+      case NonFatal(_) => None
+    }
+  }
+
   private def padAttrLitCmp(
       expr: Expression,
-      metadata: Metadata,
+      c: CharType,
       padCharCol: Boolean,
       lit: Expression): Option[Seq[Expression]] = {
     if (expr.dataType.isInstanceOf[StringType]) {

Review Comment:
   **[6] Nit: some checks are now redundant.**
   
   `RawTypedRef(c: CharType)` already guarantees that `e.dataType` is 
`replaceCharVarcharWithString(c)`, which is always a `StringType`. So these 
checks never fail:
   
   - the `expr.dataType.isInstanceOf[StringType]` check here, with its `else 
None` branch;
   - the `e.dataType.isInstanceOf[StringType]` guard of the IN case (L138);
   - the `ordinal < current.length` guard (L72), which always holds for a 
resolved `GetStructField`.
   
   There is also a double blank line after `RawTypedRef` (L85-L86). With the 
change in [1], the `StringType` check would live in `RawTypedRef` only.



##########
sql/core/src/test/scala/org/apache/spark/sql/CharVarcharTestSuite.scala:
##########
@@ -660,6 +660,59 @@ trait CharVarcharTestSuite extends QueryTest {
     }
   }
 
+  test("SPARK-61970: char type comparison: struct field and string literal") {
+    withTable("t") {
+      sql(s"CREATE TABLE t(s STRUCT<c: CHAR(3)>, n STRUCT<s: STRUCT<c: 
CHAR(3)>>) USING $format")
+      sql("INSERT INTO t VALUES (struct('a'), struct(struct('a')))")
+      testConditions(spark.table("t"), Seq(
+        ("s.c = 'a'", true),
+        ("'a' = s.c", true),
+        ("s.c = 'a  '", true),
+        ("s.c > 'a'", false),
+        ("s.c IN ('a', 'b')", true),
+        ("s.c = 'abcd'", false),
+        ("n.s.c = 'a'", true),
+        ("n.s.c IN ('b', 'a')", true),
+        ("s.c <=> null", false)))
+    }
+  }
+
+  test("SPARK-61970: a reordered struct field keeps its own raw type") {
+    withTable("t") {
+      sql(s"CREATE TABLE t(s STRUCT<c: CHAR(3), v: STRING>) USING $format")
+      sql("INSERT INTO t VALUES (named_struct('c', 'x', 'v', 'a'))")
+      // Dataset.to reorders the fields of the struct and keeps the column's 
metadata.
+      val df = spark.table("t").to(StructType.fromDDL("s STRUCT<v: STRING, c: 
STRING>"))
+      checkAnswer(df.selectExpr("s.v = 'a'", "s.c = 'x'"), Row(true, true))
+      // It matches field names case-insensitively, and takes the target's 
spelling.
+      val renamed = spark.table("t").to(StructType.fromDDL("s STRUCT<C: 
STRING, V: STRING>"))
+      checkAnswer(renamed.selectExpr("s.C = 'x'", "s.V = 'a'"), Row(true, 
true))
+    }
+    withTable("t") {
+      sql(s"CREATE TABLE t(n STRUCT<s: STRUCT<c: CHAR(3), v: STRING>>) USING 
$format")
+      sql("INSERT INTO t VALUES (named_struct('s', named_struct('c', 'x', 'v', 
'a')))")
+      // The fields of a nested struct are reordered too.
+      val df = spark.table("t").to(StructType.fromDDL("n STRUCT<s: STRUCT<v: 
STRING, c: STRING>>"))
+      checkAnswer(df.selectExpr("n.s.c = 'x'", "n.s.v = 'a'"), Row(true, true))
+    }
+  }
+
+  test("SPARK-61970: comparisons with a struct field keep constants that 
fail") {

Review Comment:
   **[7] The PR description could be updated.**
   
   - It says that the new tests run in `BasicCharVarcharTestSuite` and 
`FileSourceCharVarcharTestSuite`. `BasicCharVarcharTestSuite` extends 
`SharedSparkSession`, not `CharVarcharTestSuite`, so the tests run in 
`FileSourceCharVarcharTestSuite`, `DSV2CharVarcharTestSuite` and 
`HiveCharVarcharTestSuite` (in sql/hive). The CI jobs that run them passed.
   - It says that for a column, `RawTypedRef` returns the same raw type as 
before. The exact type check is new for columns as well, see [1].
   - The user-facing section covers struct fields only. A top-level CHAR column 
compared with a constant that fails, such as `CAST(1 / 0 AS STRING)` in a 
branch that is never evaluated as in this test, used to fail at analysis and 
now passes, as the reply on the earlier thread says.



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