sandip-db commented on code in PR #60484:
URL: https://github.com/apache/spark/pull/60484#discussion_r4582961777


##########
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:
   Done in 59daa315dbf, and confirmed by running it: with 
`allowNumericLeadingZeros`, `007`, `-007.50` and `0001e2` are stored as `"7"`, 
`"-7.50"` and `"1e2"` through both a file read and `from_json`. The docs row 
and the `VariantBuilder`, `JSONOptions` and `DataSourceOptions` comments now 
state the exception, and `JsonSuite` has a test for it.



##########
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:
   Done in 59daa315dbf with the suggested wording. The conf has defaulted to 
`true` since 4.2.0, so the unset behavior has to stay as it is.



##########
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:
   Done in 59daa315dbf.



##########
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:
   Done in 59daa315dbf: the schema now has three fields to match the record, 
with an option-off control asserting `BIGINT`.



##########
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:
   Done in 59daa315dbf: `checkError` on `_LEGACY_ERROR_TEMP_2147` with 
`paramName` = `variantPrimitivesAsString`.



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