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


##########
docs/sql-data-sources-json.md:
##########
@@ -219,6 +219,12 @@ Data source options of JSON can be set via:
     <td>If specified, the entire JSON record is parsed and stored as a single 
column of <code>VariantType</code> with the given column name, instead of being 
split into individual fields.</td>
     <td>read</td>
   </tr>
+  <tr>
+    <td><code>variantPrimitivesAsString</code></td>
+    <td><code>false</code></td>
+    <td>When reading into a <code>VARIANT</code> (see 
<code>singleVariantColumn</code>, or a <code>VariantType</code> column in the 
schema), stores JSON numbers and booleans as strings holding their text exactly 
as written, instead of numeric or boolean values. For example, <code>1e2</code> 
is kept as the string <code>"1e2"</code> instead of the double 
<code>100.0</code>, and a number with more digits than a decimal can hold is 
kept as written instead of being rounded to a double. JSON nulls remain variant 
nulls. This option does not affect non-variant columns; see 
<code>primitivesAsString</code> for those. JSON built-in functions such as 
<code>from_json</code> also observe this option.</td>

Review Comment:
   **Non-blocking (P2):** This row says number tokens keep their text exactly 
as written, and the new `VariantBuilder` Javadoc and field comment and the 
`JSONOptions` and `DataSourceOptions` comments make the same promise, but it 
does not hold when `allowNumericLeadingZeros` is enabled. `buildJson` stores 
`parser.getText()`, and jackson-core 2.22.4 documents for 
`ALLOW_LEADING_ZEROS_FOR_NUMBERS` that the extra zeros are not included in the 
text `getText()` exposes; both `UTF8StreamJsonParser` and 
`ReaderBasedJsonParser` skip them before buffering, and Jackson's own test 
expects `"3"` for `00003`. So, going by the code (this was not run here), 
`spark.read.option("singleVariantColumn", 
"v").option("variantPrimitivesAsString", 
"true").option("allowNumericLeadingZeros", "true").json(path)` over `{"id": 
007, "x": -007.50}` stores `{"id":"7","x":"-7.50"}`, and `from_json` with the 
same options does too. Users who enable leading zeros to read zero-padded 
values such as identifiers lose the 
 padding while the docs say it is kept.
   
   The zeros are removed by the parser under that leniency option, not by the 
type inference this option turns off, and the base branch already drops them 
(`007` becomes the long `7`), so the option does not need to keep them; it just 
should not promise to. Please state the exception here and in those comments 
(in `VariantBuilder`, which does not know Spark's option names, say that it 
stores the parser's token text, which omits leading zeros when the parser 
allows them), and add a JSON test that reads such a record with both options 
through a file read and `from_json`; none of the new tests uses a number with 
leading zeros. For this row, something like:
   
   ```suggestion
       <td>When reading into a <code>VARIANT</code> (see 
<code>singleVariantColumn</code>, or a <code>VariantType</code> column in the 
schema), stores JSON numbers and booleans as strings holding their text exactly 
as written, instead of numeric or boolean values. For example, <code>1e2</code> 
is kept as the string <code>"1e2"</code> instead of the double 
<code>100.0</code>, and a number with more digits than a decimal can hold is 
kept as written instead of being rounded to a double. A number that is accepted 
only because <code>allowNumericLeadingZeros</code> is enabled is stored without 
its leading zeros, which the JSON parser drops (for example, <code>007</code> 
is stored as <code>"7"</code>). JSON nulls remain variant nulls. This option 
does not affect non-variant columns; see <code>primitivesAsString</code> for 
those. JSON built-in functions such as <code>from_json</code> also observe this 
option.</td>
   ```
   
   **Verification:**
   - **Behavior:** With variantPrimitivesAsString and allowNumericLeadingZeros 
both enabled, JSON numbers written with leading zeros that are read into a 
VARIANT, through a file read and through from_json with a variant schema, are 
stored as strings without the leading zeros, for integer and fractional, 
positive and negative numbers, exactly as the documentation now states.
   - **Inspection:** The JSON option documentation and every comment that 
describes the JSON string mode, in the docs, VariantBuilder, JSONOptions and 
DataSourceOptions, state the leading-zero exception, and none still says that 
every number token keeps its input text exactly.



##########
docs/sql-data-sources-xml.md:
##########
@@ -112,6 +112,13 @@ Data source options of XML can be set via:
       <td>read/write</td>
   </tr>
 
+  <tr>
+      <td><code>variantPrimitivesAsString</code></td>
+      <td><code>false</code></td>
+      <td>When reading into a <code>VARIANT</code> (see 
<code>singleVariantColumn</code>, or a <code>VariantType</code> column in the 
schema), stores element text, attribute values and value tags as strings 
holding their text from the input, instead of a type inferred from that text 
(boolean, long or decimal). For example, <code>007</code> is kept as the string 
<code>"007"</code> instead of the integer <code>7</code>. Surrounding spaces 
are still trimmed when <code>ignoreSurroundingSpaces</code> is enabled, and 
null values, including those matching <code>nullValue</code>, remain variant 
nulls. XML built-in functions such as <code>from_xml</code> also observe this 
option.</td>

Review Comment:
   **Non-blocking (P2):** When this option is not set, `XmlOptions` resolves it 
to `!inferSchema && SQLConf.get.xmlVariantRespectInferSchema`, and 
`spark.sql.xml.variant.respectInferSchema` defaults to `true`, so every XML 
VARIANT read with `inferSchema=false` behaves as if this option were `true`; 
the new `XmlVariantSuite` test asserts exactly that. For example, 
`spark.read.option("rowTag", "ROW").option("inferSchema", 
"false").option("singleVariantColumn", "v").xml(path)` keeps `<id>007</id>` as 
the string `"007"`, while a default of `false` here means the inferred integer 
`7`. Since the PR also makes the conf internal and drops it from the `from_xml` 
notes, this row is now the only place users can learn the default, and it is 
wrong for those reads; users who want inferred types with `inferSchema=false` 
are not told to set this option to `false`. Something like:
   
   ```suggestion
         <td><code>true</code> if <code>inferSchema</code> is 
<code>false</code>, otherwise <code>false</code></td>
         <td>When reading into a <code>VARIANT</code> (see 
<code>singleVariantColumn</code>, or a <code>VariantType</code> column in the 
schema), stores element text, attribute values and value tags as strings 
holding their text from the input, instead of a type inferred from that text 
(boolean, long or decimal). For example, <code>007</code> is kept as the string 
<code>"007"</code> instead of the integer <code>7</code>. Surrounding spaces 
are still trimmed when <code>ignoreSurroundingSpaces</code> is enabled, and 
null values, including those matching <code>nullValue</code>, remain variant 
nulls. When the option is not set, values are kept as strings only if 
<code>inferSchema</code> is <code>false</code>; when it is set, it applies 
regardless of <code>inferSchema</code>, so set it to <code>false</code> to get 
inferred types with <code>inferSchema</code> set to <code>false</code>. XML 
built-in functions such as <code>from_xml</code> also observe this option.</td>
   ```
   
   **Verification:**
   - **Inspection:** The XML option row's default and description match the 
unset behavior the code implements, strings when inferSchema is false and 
inferred types otherwise, and the effect of setting the option explicitly in 
either direction.



##########
sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/csv/CSVSuite.scala:
##########
@@ -4130,6 +4131,118 @@ abstract class CSVSuite
     }
   }
 
+  test("csv variant keeps primitives as strings with 
variantPrimitivesAsString") {
+    withTempPath { path =>
+      val data =
+        """0001,+5,1e9,True
+          |2000-01-01,2000-01-01 01:02:03,n/a,
+          |""".stripMargin
+      Files.write(path.toPath, data.getBytes(StandardCharsets.UTF_8))
+
+      def checkSingleVariant(options: Map[String, String], expected: String*): 
Unit = {
+        val allOptions = options ++ Map("singleVariantColumn" -> "v", 
"nullValue" -> "n/a")
+        checkAnswer(
+          
spark.read.options(allOptions).csv(path.getCanonicalPath).selectExpr("cast(v as 
string)"),
+          expected.map(Row(_)))
+      }
+
+      val asStrings = Seq(
+        """{"_c0":"0001","_c1":"+5","_c2":"1e9","_c3":"True"}""",
+        """{"_c0":"2000-01-01","_c1":"2000-01-01 
01:02:03","_c2":null,"_c3":null}""")
+      val inferred = Seq(
+        """{"_c0":1,"_c1":5,"_c2":1000000000,"_c3":true}""",
+        """{"_c0":"2000-01-01","_c1":"2000-01-01 
01:02:03+00:00","_c2":null,"_c3":null}""")
+
+      // A small partition size ensures each value is parsed independently and 
would otherwise get
+      // its type inferred. The time parser policy is pinned because the 
inferred timestamp is
+      // rendered differently under LEGACY (see CSVLegacyTimeParserSuite).
+      withSQLConf(SQLConf.FILES_MAX_PARTITION_BYTES.key -> "10",
+        SQLConf.SESSION_LOCAL_TIMEZONE.key -> "UTC",
+        SQLConf.LEGACY_TIME_PARSER_POLICY.key -> "CORRECTED") {
+        // The option keeps every non-null value as a string regardless of 
inferSchema. Null and
+        // nullValue tokens remain variant nulls.
+        for (inferSchema <- Seq(None, Some("true"), Some("false"))) {
+          checkSingleVariant(
+            Map("variantPrimitivesAsString" -> "true") ++ 
inferSchema.map("inferSchema" -> _),
+            asStrings: _*)
+        }
+
+        // The option takes precedence over the deprecated 
variantRespectInferSchema option in
+        // both directions.
+        checkSingleVariant(
+          Map("variantPrimitivesAsString" -> "true", 
"variantRespectInferSchema" -> "false"),
+          asStrings: _*)
+        checkSingleVariant(
+          Map("variantPrimitivesAsString" -> "false", 
"variantRespectInferSchema" -> "true",
+            "inferSchema" -> "false"),
+          inferred: _*)
+
+        // Without the option, values are inferred by default.
+        checkSingleVariant(Map.empty, inferred: _*)
+      }
+
+      // Field names from the header are not affected; values stay strings.
+      Files.write(path.toPath, 
"id,flag\n0001,true\n".getBytes(StandardCharsets.UTF_8))
+      checkSingleVariant(Map("header" -> "true", "variantPrimitivesAsString" 
-> "true"),
+        """{"flag":"true","id":"0001"}""")
+    }
+  }
+
+  test("csv variant columns keep primitives as strings with 
variantPrimitivesAsString") {
+    // Explicit schemas with VariantType columns share a converter with 
singleVariantColumn, so
+    // the option applies there too. Check the type using schema_of_variant.
+    withTempPath { path =>
+      Files.write(path.toPath, 
"1000,0001,true,\n".getBytes(StandardCharsets.UTF_8))
+      val schema = "c1 variant, c2 variant, c3 variant, c4 variant"
+      val exprs = Seq("schema_of_variant(c1)", "schema_of_variant(c2)", 
"schema_of_variant(c3)",
+        "schema_of_variant(c4)")
+
+      val retained = spark.read.schema(schema)
+        .option("variantPrimitivesAsString", "true")
+        .csv(path.getCanonicalPath)
+      checkAnswer(retained.selectExpr(exprs: _*), Row("STRING", "STRING", 
"STRING", "VOID"))
+
+      val inferred = spark.read.schema(schema)
+        .option("variantPrimitivesAsString", "false")
+        .csv(path.getCanonicalPath)
+      checkAnswer(inferred.selectExpr(exprs: _*), Row("BIGINT", "BIGINT", 
"BOOLEAN", "VOID"))
+    }
+  }
+
+  test("csv variantPrimitivesAsString records whether the user set it") {
+    def options(params: (String, String)*): CSVOptions =
+      new CSVOptions(params.toMap, columnPruning = false, "UTC")
+
+    // Not set: no user value, and the effective value comes from the 
deprecated option.
+    assert(options().variantPrimitivesAsStringOpt.isEmpty)
+    assert(!options().variantPrimitivesAsString)
+    val legacy = options("variantRespectInferSchema" -> "true")
+    assert(legacy.variantPrimitivesAsStringOpt.isEmpty)
+    assert(legacy.variantPrimitivesAsString)
+
+    // Set: the user value is kept, including an explicit false.
+    for (value <- Seq(true, false)) {
+      val opts = options("variantPrimitivesAsString" -> value.toString)
+      assert(opts.variantPrimitivesAsStringOpt.contains(value))
+      assert(opts.variantPrimitivesAsString == value)
+    }
+
+    // When set, the deprecated option is not consulted, so even an invalid 
value is ignored.
+    assert(options("variantPrimitivesAsString" -> "true",
+      "variantRespectInferSchema" -> "yes").variantPrimitivesAsString)
+  }
+
+  test("csv variantPrimitivesAsString must be a boolean") {
+    withTempPath { path =>
+      Files.write(path.toPath, "1\n".getBytes(StandardCharsets.UTF_8))
+      val e = intercept[Exception] {
+        spark.read.options(Map("singleVariantColumn" -> "v", 
"variantPrimitivesAsString" -> "yes"))
+          .csv(path.getCanonicalPath).collect()
+      }
+      assert(e.getMessage.contains("variantPrimitivesAsString"))

Review Comment:
   **Nit (P3):** `intercept[Exception]` plus a substring check passes for any 
failure whose message mentions the option, so it would not notice if the 
boolean validation were replaced by a different or wrapped error. A non-boolean 
value is rejected by `CSVOptions.getBool` with 
`QueryExecutionErrors.paramIsNotBooleanValueError`, a `SparkException` with 
condition `_LEGACY_ERROR_TEMP_2147` and parameter `paramName`, thrown on the 
driver while the options are built for schema inference, and this suite already 
asserts that condition with `checkError` for `treatNullAsEmptyString`:
   
   ```suggestion
         checkError(
           exception = intercept[SparkException] {
             spark.read
               .options(Map("singleVariantColumn" -> "v", 
"variantPrimitivesAsString" -> "yes"))
               .csv(path.getCanonicalPath).collect()
           },
           condition = "_LEGACY_ERROR_TEMP_2147",
           parameters = Map("paramName" -> "variantPrimitivesAsString"))
   ```
   
   **Verification:**
   - **Behavior:** A CSV read with variantPrimitivesAsString set to a 
non-boolean value fails with the boolean-option error condition whose parameter 
names variantPrimitivesAsString, and the assertion fails if the condition or 
the parameter differs.



##########
sql/core/src/test/scala/org/apache/spark/sql/CsvFunctionsSuite.scala:
##########
@@ -1021,6 +1021,35 @@ class CsvFunctionsSuite extends SharedSparkSession {
       Seq(Row("BIGINT")))
   }
 
+  test("from_csv with variant: variantPrimitivesAsString keeps primitives as 
strings") {
+    val df = Seq("0001,true,").toDF("value")
+    val schema = StructType.fromDDL("v variant")
+
+    // The option keeps every non-null value as a string regardless of 
inferSchema, and takes
+    // precedence over the deprecated variantRespectInferSchema option.
+    for (extra <- Seq(
+        Map.empty[String, String],
+        Map("inferSchema" -> "true"),
+        Map("variantRespectInferSchema" -> "false"))) {
+      val options = Map("singleVariantColumn" -> "v", 
"variantPrimitivesAsString" -> "true") ++
+        extra
+      checkAnswer(
+        df.select(from_csv($"value", schema, options).cast("string")),
+        Seq(Row("""{{"_c0":"0001","_c1":"true","_c2":null}}""")))
+    }
+    checkAnswer(
+      df.select(from_csv($"value", schema, Map("singleVariantColumn" -> "v",
+        "variantPrimitivesAsString" -> "false", "variantRespectInferSchema" -> 
"true",
+        "inferSchema" -> "false")).cast("string")),
+      Seq(Row("""{{"_c0":1,"_c1":true,"_c2":null}}""")))
+
+    // Explicit VariantType columns behave the same.
+    checkAnswer(
+      df.selectExpr("schema_of_variant(from_csv(value, 'a variant, b variant', 
" +
+        "map('variantPrimitivesAsString', 'true')).a)"),
+      Seq(Row("STRING")))

Review Comment:
   **Nit (P3):** `df` holds `"0001,true,"`, whose trailing comma gives three 
tokens (the `singleVariantColumn` assertions above expect `_c2`), but this 
schema has two fields. Because the options map is non-empty, 
`OptimizeCsvJsonExprs` does not prune the schema, so `UnivocityParser.convert` 
sees 3 tokens for 2 fields, records a malformed-record error and throws 
`BadRecordException` with the partial row, which PERMISSIVE mode returns. The 
`STRING` asserted here therefore comes from malformed-record recovery rather 
than a normal parse of explicit variant columns, and a change to partial-result 
handling would break this check for an unrelated reason. Matching the schema to 
the record keeps it on the normal path, and a control with the option off shows 
the difference:
   
   ```suggestion
       checkAnswer(
         df.selectExpr("schema_of_variant(from_csv(value, 'a variant, b 
variant, c variant', " +
           "map('variantPrimitivesAsString', 'true')).a)"),
         Seq(Row("STRING")))
       checkAnswer(
         df.selectExpr("schema_of_variant(from_csv(value, 'a variant, b 
variant, c variant', " +
           "map('variantPrimitivesAsString', 'false')).a)"),
         Seq(Row("BIGINT")))
   ```
   
   **Verification:**
   - **Behavior:** from_csv with explicit VariantType columns, on a record 
whose field count matches the schema, yields a string variant for 0001 with 
variantPrimitivesAsString and an integer variant without it.



##########
docs/sql-data-sources-csv.md:
##########
@@ -231,13 +231,13 @@ Data source options of CSV can be set via:
   <tr>
     <td><code>singleVariantColumn</code></td>
     <td>(none)</td>
-    <td>If specified, the entire CSV record is parsed and stored as a single 
column of <code>VariantType</code> with the given column name, instead of being 
split into individual fields. By default, scalar values are type-inferred 
inside the variant on a best-effort basis (for example, <code>"0001"</code> may 
be inferred as the integer <code>1</code>). To preserve scalar values as 
strings, set <code>variantRespectInferSchema</code> to <code>true</code> and 
<code>inferSchema</code> to <code>false</code>.</td>
+    <td>If specified, the entire CSV record is parsed and stored as a single 
column of <code>VariantType</code> with the given column name, instead of being 
split into individual fields. By default, scalar values are type-inferred 
inside the variant on a best-effort basis (for example, <code>"0001"</code> may 
be inferred as the integer <code>1</code>). To preserve scalar values as 
strings, set <code>variantPrimitivesAsString</code> to <code>true</code>.</td>
     <td>read</td>
   </tr>
   <tr>
-    <td><code>variantRespectInferSchema</code></td>
+    <td><code>variantPrimitivesAsString</code></td>
     <td>false</td>
-    <td>When reading into a <code>VARIANT</code> (see 
<code>singleVariantColumn</code> or a <code>VariantType</code> column in the 
schema), controls whether the <code>inferSchema</code> option is honored. When 
<code>true</code> and <code>inferSchema</code> is <code>false</code>, scalar 
values are preserved as strings inside the variant instead of being inferred as 
boolean, long, decimal, date, or timestamp. When <code>false</code> (the 
default), scalar types are inferred on a best-effort basis regardless of 
<code>inferSchema</code>. Enabling this option forces <code>from_csv</code> to 
observe <code>inferSchema</code> when reading into a <code>VARIANT</code>.</td>
+    <td>When reading into a <code>VARIANT</code> (see 
<code>singleVariantColumn</code>, or a <code>VariantType</code> column in the 
schema), stores every non-null value as a string holding its text from the 
input, instead of a type inferred from that text (boolean, long, decimal, date 
or timestamp). For example, <code>0001</code> is kept as the string 
<code>"0001"</code> instead of the integer <code>1</code>. Null values, 
including those matching <code>nullValue</code>, remain variant nulls. Unlike 
most options here, CSV built-in functions such as <code>from_csv</code> also 
observe this option.</td>

Review Comment:
   **Nit (P3):** "Unlike most options here" is inaccurate: the page's preamble 
lists `from_csv`, `to_csv` and `schema_of_csv` among the ways to set these 
options, and only 9 of the 40 rows say CSV built-in functions ignore them, so 
options without that note, such as `nullValue` or `mode`, do apply in 
`from_csv`. A reader can take this sentence to mean they do not. The JSON and 
XML rows just say the built-in functions also observe the option:
   
   ```suggestion
       <td>When reading into a <code>VARIANT</code> (see 
<code>singleVariantColumn</code>, or a <code>VariantType</code> column in the 
schema), stores every non-null value as a string holding its text from the 
input, instead of a type inferred from that text (boolean, long, decimal, date 
or timestamp). For example, <code>0001</code> is kept as the string 
<code>"0001"</code> instead of the integer <code>1</code>. Null values, 
including those matching <code>nullValue</code>, remain variant nulls. CSV 
built-in functions such as <code>from_csv</code> also observe this option.</td>
   ```
   
   **Verification:**
   - **Inspection:** The CSV option row says that the built-in functions 
observe the option without contrasting it with the other options on the page.



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