spark-test commented on code in PR #60750:
URL: https://github.com/apache/spark/pull/60750#discussion_r4659441192


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ApplyCharTypePaddingHelper.scala:
##########
@@ -48,6 +53,42 @@ 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. A CHAR
+    // value is any string, as its collation can change while it keeps its 
metadata, as with
+    // Dataset.to.
+    def unapply(e: Expression): Option[DataType] = rawType(e).filter {
+      case _: CharType => e.dataType.isInstanceOf[StringType]
+      case rawType => DataTypeUtils.equalsIgnoreNullability(
+        CharVarcharUtils.replaceCharVarcharWithString(rawType), e.dataType)
+    }
+
+    private def rawType(e: Expression): Option[DataType] = e match {
+      case AttrOrOuterRef(attr) => CharVarcharUtils.getRawType(attr.metadata)

Review Comment:
   **Blocking (P1):** With `spark.sql.readSideCharPadding=false`, this parse 
turns field comparisons that work today into analysis errors when the struct 
column's declared type has a field name that the parser can't read back 
unquoted.
   
   The raw-type string is the column type's `catalogString` 
(`CharVarcharUtils.scala:103`), which writes struct field names unquoted 
(`StructType.scala:440`). `CatalystSqlParser.parseDataType` can't read such a 
name back when it has a character outside `a-z`, `A-Z`, `0-9` and `_`: 
`PostProcessor` throws `INVALID_IDENTIFIER` for a hyphen or a non-ASCII letter 
(`parsers.scala:289-307`), as `ErrorParserSuite`'s "Illegal characters in 
unquoted identifier" test pins, and a space or other punctuation is a syntax 
error. `HiveClientImpl.getSparkSQLDataType` quotes element names before calling 
`parseDataType` for this reason (`HiveClientImpl.scala:1194-1204`).
   
   Reading the code, for an external Parquet table over existing files with `` 
s STRUCT<`a-b`: CHAR(3), n: STRING> `` and read-side padding off, `SELECT * 
FROM t WHERE s.n = 'x'` returns the row on the base branch, whose literal cases 
only match bare columns, while here `RawTypedRef` parses 
`struct<a-b:char(3),n:string>` before it looks `n` up, so analysis fails. `s.n 
IN ('x', 'y')`, `s.n > 'a'` and the other operators fail the same way. With 
read-side padding on, the scan already parses this string and fails on the base 
branch, so the new failures are in the padding-off mode.
   
   Treating a raw-type string that fails to parse as absent here, by catching 
the `ParseException` and returning `None` with a comment on why such a column's 
fields aren't padded, keeps these queries working as before.
   
   **Verification:**
   - **Regression:** With read-side padding off, `SELECT * FROM t WHERE s.n = 
'x'` and `SELECT * FROM t WHERE s.n IN ('x', 'y')` on an external Parquet table 
t (s STRUCT<`a-b`: CHAR(3), n: STRING>) return the row whose n is 'x', where 
this PR's current code fails at analysis with INVALID_IDENTIFIER.
   - **Inspection:** Only the ParseException of the root raw-type parse in 
RawTypedRef is caught, and the TODO at the catch says why the fields of such a 
column are not padded.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ApplyCharTypePaddingHelper.scala:
##########
@@ -48,6 +53,42 @@ 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. A CHAR
+    // value is any string, as its collation can change while it keeps its 
metadata, as with
+    // Dataset.to.
+    def unapply(e: Expression): Option[DataType] = rawType(e).filter {
+      case _: CharType => e.dataType.isInstanceOf[StringType]
+      case 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 =>
+            // The raw struct usually has the fields of the current one. 
Dataset.to can reorder
+            // and rename the fields of a struct at any level, and keeps the 
column's metadata,
+            // so a field with another name is looked up by name, as 
Dataset.to matches them.
+            val name = current(ordinal).name
+            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)
+          case _ => None
+        }
+      case _ => None

Review Comment:
   **Non-blocking (P2):** Constants compared with CHAR array elements or map 
values still aren't padded, although reads pad those values just as they pad 
struct fields (`CharVarcharUtils.scala:323-338` and `357-370`), so these 
comparisons keep missing rows that the same comparison on a struct field now 
finds.
   
   Every extraction other than a column or `GetStructField` falls to this 
`None`. Reading the code, for `a ARRAY<CHAR(3)>`, `m MAP<STRING, CHAR(3)>` and 
`l ARRAY<STRUCT<c: CHAR(3)>>` holding `'a'`, `a[0] = 'a'`, `element_at(a, 1) = 
'a'`, `m['k'] = 'a'`, `l[0].c = 'a'` and `a[0] IN ('a', 'b')` stay false, 
comparing `'a  '` with `'a'`, while `s.c = 'a'` is now true. `get(a, 0)` and 
`try_element_at(a, 1)` behave the same, because the analyzer keeps them as 
`Get` and `TryElementAt` wrappers until the optimizer replaces them. `<>` and 
`NOT IN` keep matching those rows.
   
   Extending `rawType` so that `GetArrayItem` and `ElementAt` over an array 
take the declared element type, `GetMapValue` and `ElementAt` over a map take 
the declared value type, and `Get` and `TryElementAt` resolve through their 
replacement would pad these the same way; a struct field below one of them then 
goes through the existing `GetStructField` case.
   
   **Verification:**
   - **Regression:** For a table with ARRAY<CHAR(3)>, MAP<STRING, CHAR(3)> and 
ARRAY<STRUCT<c: CHAR(3)>> columns holding 'a', comparing `a[0]`, `element_at(a, 
1)`, `get(a, 0)`, `try_element_at(a, 1)`, `m['k']`, `element_at(m, 'k')` and 
`l[0].c` with 'a', and `a[0] IN ('a', 'b')`, returns true, where the base 
branch returns false.
   - **Behavior:** Array elements and map values of CHAR type compared with 
string constants by =, <=>, >, IN and a constant longer than the CHAR length 
give the padded CHAR results in projections and WHERE filters, and with 
read-side padding off values stored as 'a' and as 'a  ' both match 'a' and 'a  
'.
   - **Compatibility:** Comparisons of array elements and map values whose 
declared type is STRING or VARCHAR return the same results as before.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ApplyCharTypePaddingHelper.scala:
##########
@@ -161,38 +193,44 @@ 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

Review Comment:
   **Nit (P3):** The method returns `Some(None)` for a NULL constant (line 
206), which both callers rely on when they flatten the result, but this 
sentence reads as `Some(null)`. Naming the shapes removes the ambiguity:
   
   ```suggestion
      * Evaluates a foldable string expression: Some(Some(value)), Some(None) 
for NULL, or None if
   ```
   
   **Verification:**
   - **Inspection:** The tryEvalString scaladoc names Some(None) as the result 
for a NULL constant and no longer speaks of a null value.



##########
sql/core/src/test/scala/org/apache/spark/sql/CharVarcharTestSuite.scala:
##########
@@ -4151,6 +4242,20 @@ class FileSourceCharVarcharTestSuite extends 
CharVarcharTestSuite with SharedSpa
     }
   }
 
+  test("SPARK-61970: struct field and string literal without read-side 
padding") {
+    withTempPath { dir =>
+      withTable("t") {
+        sql("SELECT named_struct('c', 'a') AS 
s").write.format(format).save(dir.toString)
+        sql(s"CREATE TABLE t (s STRUCT<c: CHAR(3)>) USING $format LOCATION 
'$dir'")
+        withSQLConf(SQLConf.READ_SIDE_CHAR_PADDING.key -> "false") {
+          // The field, which the scan doesn't pad, is padded in the 
comparison too.
+          checkAnswer(sql("SELECT s.c FROM t WHERE s.c = 'a'"), Row("a"))

Review Comment:
   **Non-blocking (P2):** This assertion and the `IN` one after it hold whether 
or not the field and the constant are padded, so the test also passes on the 
base branch, which never pads a struct field, and wouldn't catch a regression 
back to that behavior with read-side padding off.
   
   The stored value is an unpadded `'a'` and the constants are `'a'` and `('a', 
'b')`, so `'a' = 'a'` holds with no padding just as `rpad('a', 3) = rpad('a', 
3)` does; the assertions fail only if the constant alone is padded. What this 
mode needs, as `SPARK-48498: always do char padding in predicates` checks for 
columns, is a stored value and a constant that differ only in trailing spaces: 
storing both `'a'` and `'a  '` and asserting that each matches `s.c = 'a'`, 
`s.c = 'a  '`, `s.c IN ('a')` and `s.c IN ('a  ')` fails on the base branch and 
whenever the field side is left unpadded.
   
   This extends existing discussions 
[1](https://github.com/apache/spark/pull/60750#discussion_r4647438098), 
[2](https://github.com/apache/spark/pull/60750#pullrequestreview-5999054579).
   
   **Verification:**
   - **Regression:** With read-side padding off, a CHAR(3) struct field stored 
as 'a  ' matches `s.c = 'a'` and one stored as 'a' matches `s.c = 'a  '`, by = 
and by IN, while on the base branch both comparisons are false.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ApplyCharTypePaddingHelper.scala:
##########
@@ -84,46 +125,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)
-          .map { newChildren =>
-            b.withNewChildren(newChildren)
-          }
-          .getOrElse(b)
+      // The constant is checked first, so that the raw type is only parsed 
when it is needed.
+      // With a constant on one side, none of the cases below can match.
+      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
+      }
 
-      case b @ BinaryComparison(lit, e @ AttrOrOuterRef(attr)) if lit.foldable 
=>
-        padAttrLitCmp(e, attr.metadata, 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
+      case b @ BinaryComparison(lit, e) if isStringConstant(lit) => e match {
+        case RawTypedRef(c: CharType) =>
+          padAttrLitCmp(e, c, padCharCol, lit)
+            .map(newChildren => b.withNewChildren(newChildren.reverse))
+            .getOrElse(b)
+        case _ => b
+      }
+
+      case i @ In(e @ RawTypedRef(c: CharType), list) if i.resolved && 
list.forall(_.foldable) =>

Review Comment:
   **Nit (P3):** This pattern runs `RawTypedRef`, and so parses the root 
column's raw-type string, before the guard is checked, so INs that can't be 
padded now pay a parse that the base branch skipped.
   
   The base branch checked `i.resolved && 
attr.dataType.isInstanceOf[StringType] && list.forall(_.foldable)` before 
parsing. Here `s IN (named_struct('c', 'x'))` on a struct column, or `s.c IN 
(x, 'a')` with a non-constant element, parses once with no change to the plan, 
and `c1 IN (c2, c3)` parses `c1` once more before the attribute-list case 
parses all three. As in the two binary-comparison cases above, matching `case i 
@ In(e, list) if e.dataType.isInstanceOf[StringType] && i.resolved && 
list.forall(_.foldable)` and only then `RawTypedRef(c: CharType)` on `e`, 
returning `i` otherwise, removes the extra parse without changing any result: a 
list of constants reaches the attribute-list case only when it is empty.
   
   This extends existing discussions 
[1](https://github.com/apache/spark/pull/60750#discussion_r4647438140), 
[2](https://github.com/apache/spark/pull/60750#pullrequestreview-5999054579).
   
   **Verification:**
   - **Inspection:** In the IN case, the string-type, resolution and 
all-constants checks come before the RawTypedRef match, as in the two 
binary-comparison cases, and a non-matching value leaves the IN unchanged.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ApplyCharTypePaddingHelper.scala:
##########
@@ -48,6 +53,42 @@ 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. A CHAR
+    // value is any string, as its collation can change while it keeps its 
metadata, as with
+    // Dataset.to.
+    def unapply(e: Expression): Option[DataType] = rawType(e).filter {
+      case _: CharType => e.dataType.isInstanceOf[StringType]
+      case rawType => DataTypeUtils.equalsIgnoreNullability(

Review Comment:
   **Nit (P3):** No caller can observe this branch: all three uses of 
`RawTypedRef` (lines 131, 137 and 144) match `RawTypedRef(c: CharType)`, so 
keeping or dropping a non-CHAR raw type here never changes which case matches; 
it only runs a type rewrite and a comparison. The example it was added for, a 
field that `Dataset.to` casts to `INT`, is already rejected by the CHAR 
branch's string check. Returning `Option[CharType]`, for example 
`rawType(e).collect { case c: CharType if e.dataType.isInstanceOf[StringType] 
=> c }`, and rewording the comment at lines 62-64 to describe that check keeps 
every result.
   
   **Verification:**
   - **Inspection:** RawTypedRef has no branch for raw types other than CHAR, 
its comment describes the CHAR check, and every use of it matches a CHAR result.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/ApplyCharTypePaddingHelper.scala:
##########
@@ -84,46 +125,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)
-          .map { newChildren =>
-            b.withNewChildren(newChildren)
-          }
-          .getOrElse(b)
+      // The constant is checked first, so that the raw type is only parsed 
when it is needed.
+      // With a constant on one side, none of the cases below can match.
+      case b @ BinaryComparison(e, lit) if isStringConstant(lit) => e match {

Review Comment:
   **Nit (P3):** Nothing in this helper says that comparisons between two CHAR 
values that aren't both columns are left unpadded, so a reader can't tell that 
the fix is partial. The PR description leaves comparisons between two struct 
fields, or a struct field and a column, unchanged, but they don't go through 
`addPaddingInStringComparison` as it says: `s.c = s2.c` and `s.c = c5` match 
neither these literal cases nor the column-to-column case, which needs two bare 
columns, so a CHAR(3) field read as `'a  '` still doesn't equal a CHAR(5) field 
or column read as `'a    '`. The comment on that case at line 160 even mentions 
inner fields. A TODO next to it naming field-to-field and field-to-column 
comparisons as not padded yet would mark the limit.
   
   **Verification:**
   - **Inspection:** The comparison padding helper carries a TODO, next to the 
case that pads two columns, naming field-to-field and field-to-column CHAR 
comparisons as not padded yet.



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