You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by "ganeshashree (via GitHub)" <gi...@apache.org> on 2026/08/10 06:00:25 UTC

[PR] [SPARK-58685][SQL] Support the ANSI SQL/JSON JSON_VALUE scalar function [spark]

ganeshashree opened a new pull request, #57888:
URL: https://github.com/apache/spark/pull/57888

   ### What changes were proposed in this pull request?
   
   Add the ANSI SQL:2016 `JSON_VALUE` scalar function (feature T821):
   
   ```
       JSON_VALUE(jsonExpr, path
                  [ RETURNING <type> ]
                  [ (NULL | ERROR | DEFAULT expr) ON EMPTY ]
                  [ (NULL | ERROR | DEFAULT expr) ON ERROR ])
   ```
   
   It extracts the scalar at `path`, cast to the RETURNING type (default STRING). A missing path fires ON EMPTY; malformed JSON, a non-scalar match, or a failed cast fires ON ERROR; both default to NULL. An explicit JSON null returns SQL NULL, and a SQL NULL input propagates to NULL.
   
   Grammar adds non-reserved keywords `JSON_VALUE`, `RETURNING`, `EMPTY` and a dedicated production, mirroring `JSON_TABLE` (SPARK-58366). Evaluation reuses JSON_TABLE's token-aware path evaluator via a new `JsonTableEvaluator.lookup` entry point that preserves the missing / JSON-null / found distinction. The extracted-scalar cast is always ANSI (throwing) so ON ERROR governs a failed conversion regardless of `spark.sql.ansi.enabled`.
   
   v1 supports STRING input and scalar (string/numeric/boolean/datetime) RETURNING types per ANSI 9075-2 6.28; VARIANT RETURNING and PASSING are deferred.
   
   ### Why are the changes needed?
   
   Spark implements none of the ANSI scalar JSON functions. `JSON_VALUE` is near-universal (Oracle, SQL Server, PostgreSQL, Trino, BigQuery, ...), so its absence forces migrated queries to rewrite to `CAST(get_json_object(...))`,
   which is STRING-only, cannot express RETURNING, and conflates missing vs. error.
   
   ### Does this PR introduce _any_ user-facing change?
   
   Yes. It adds the new `JSON_VALUE` SQL function. The new keywords are non-reserved in both ANSI and default modes, so existing identifiers named `json_value` /`returning` / `empty` continue to work.
   
   ### How was this patch tested?
   
   New `JsonValueSuite` (both ANSI modes), `json-functions.sql` golden files, `ExpressionParserSuite`, `SQLKeywordSuite`, and `SparkThrowableSuite` for the new error conditions.
   
   ### Was this patch authored or co-authored using generative AI tooling?
   Yes, Claude Opus 4.8.


-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-58685][SQL] Support the ANSI SQL/JSON JSON_VALUE scalar function [spark]

Posted by "ganeshashree (via GitHub)" <gi...@apache.org>.
ganeshashree commented on code in PR #57888:
URL: https://github.com/apache/spark/pull/57888#discussion_r3751210048


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/jsonExpressions.scala:
##########
@@ -637,6 +637,215 @@ case class JsonTable(
     copy(child = newChild)
 }
 
+/**
+ * Behavior of `JSON_VALUE`'s `ON EMPTY` / `ON ERROR` clause: what to produce when the path matches
+ * nothing, or when the input/extraction fails.
+ */
+sealed trait JsonValueBehavior
+object JsonValueBehavior {
+  /** Produce SQL NULL (the SQL-standard default for both ON EMPTY and ON ERROR). */
+  case object Null extends JsonValueBehavior
+  /** Raise an error. */
+  case object Error extends JsonValueBehavior
+  /** Produce the value of a `DEFAULT` expression, cast to the RETURNING type. */
+  case object Default extends JsonValueBehavior
+}
+
+// scalastyle:off line.size.limit
+/**
+ * The SQL:2016 `JSON_VALUE` scalar function (feature T821): extracts a single scalar located by a
+ * SQL/JSON `path` from a JSON input, casts it to the `RETURNING` type (default STRING), and applies
+ * the `ON EMPTY` / `ON ERROR` behavior when the path matches nothing or the extraction/cast fails:
+ *
+ *   - missing path                       -> ON EMPTY behavior
+ *   - explicit JSON `null`                -> SQL NULL
+ *   - non-scalar (object/array) match     -> ON ERROR behavior
+ *   - malformed / non-single-value input  -> ON ERROR behavior
+ *   - scalar match, cast fails            -> ON ERROR behavior
+ *   - scalar match, cast succeeds         -> the cast value
+ *
+ * Both clauses default to NULL per the standard. A `null` JSON input yields SQL NULL directly, not
+ * the ON EMPTY/ERROR path.
+ *
+ * `emptyDefault` / `errorDefault` hold the `DEFAULT <expr>` expressions, present only for the
+ * corresponding `Default` behavior. The child list is variable (0-2 defaults), so this extends
+ * `Expression` directly rather than `UnaryExpression`.
+ *
+ * {{{
+ *   JSON_VALUE('{"id":7}', '$.id' RETURNING INT)                    -- 7
+ *   JSON_VALUE('{"id":7}', '$.missing' DEFAULT -1 ON EMPTY)          -- -1
+ *   JSON_VALUE('{"a":{}}', '$.a' ERROR ON ERROR)                     -- raises (non-scalar)
+ * }}}
+ */
+// scalastyle:on line.size.limit
+case class JsonValue(
+    child: Expression,
+    path: String,
+    returning: DataType,
+    onEmpty: JsonValueBehavior,
+    onError: JsonValueBehavior,
+    emptyDefault: Option[Expression],
+    errorDefault: Option[Expression],
+    timeZoneId: Option[String] = None,
+    ansiEnabled: Boolean = SQLConf.get.ansiEnabled)
+  extends Expression
+  with TimeZoneAwareExpression
+  with CodegenFallback
+  with ExpectsInputTypes
+  with QueryErrorsBase {
+
+  override def nullable: Boolean = true
+
+  // Children: the JSON input first, then whichever DEFAULT expressions are present. The two
+  // defaults are resolved/coerced through the normal child machinery; their cast to `returning`
+  // happens at eval time via `emptyDefaultCast` / `errorDefaultCast`.
+  override def children: Seq[Expression] =
+    child +: (emptyDefault.toSeq ++ errorDefault.toSeq)
+
+  // One entry per child: the JSON input must be STRING; the DEFAULT children accept anything (they
+  // are cast to `returning` explicitly at eval). One entry per child is required because the
+  // coercion rule zips `children` against `inputTypes` and rebuilds via `withNewChildren`; a
+  // shorter list would truncate the zip and pass the wrong child count.
+  override def inputTypes: Seq[AbstractDataType] =
+    StringTypeWithCollation(supportsTrimCollation = true) +:
+      children.tail.map(_ => AnyDataType)
+
+  override def dataType: DataType = returning
+
+  override def withTimeZone(timeZoneId: String): TimeZoneAwareExpression =
+    copy(timeZoneId = Option(timeZoneId))
+
+  override def checkInputDataTypes(): TypeCheckResult = {
+    val inputCheck = super.checkInputDataTypes()
+    if (inputCheck.isFailure) {
+      inputCheck
+    } else if (!JsonPathParser.hasWildcard(path).contains(false)) {
+      // The path must parse and be wildcard-free (JSON_VALUE returns a single scalar).
+      DataTypeMismatch(
+        errorSubClass = "INVALID_JSON_PATH",
+        messageParameters = Map(
+          "functionName" -> toSQLId(prettyName), "path" -> toSQLValue(path)))
+    } else if (!JsonValue.isValidReturningType(returning)) {
+      // RETURNING is restricted to scalar (atomic) types per ANSI 9075-2 6.28.
+      DataTypeMismatch(
+        errorSubClass = "INVALID_JSON_SCALAR_RETURNING_TYPE",
+        messageParameters = Map(
+          "functionName" -> toSQLId(prettyName), "returningType" -> toSQLType(returning)))
+    } else {
+      TypeCheckResult.TypeCheckSuccess
+    }
+  }
+
+  // Eval mode for the user-provided DEFAULT expression casts: follows the session ANSI setting like
+  // any ordinary value cast. The extracted-scalar cast is separate (see `valueCast`).
+  @transient private lazy val defaultEvalMode = EvalMode.fromBoolean(ansiEnabled)
+
+  // Path parsed once (the grammar makes it a string literal). `checkInputDataTypes` guarantees it
+  // parses and is wildcard-free, so the evaluator is only built for a valid path.
+  @transient private lazy val evaluator: JsonTableEvaluator =
+    JsonTableEvaluator(JsonPathParser.parse(path).getOrElse(Nil), explodeRoot = false)
+
+  // Cast from the extracted scalar's STRING form to the RETURNING type, built once over a reused
+  // input slot to avoid per-row allocation. Always an ANSI (throwing) cast, independent of the
+  // session's ANSI setting, so a failed conversion always routes to ON ERROR (see `eval`) rather
+  // than being silently turned into NULL by a non-ANSI session.
+  @transient private lazy val valueCast: Expression =
+    Cast(BoundReference(0, StringType, nullable = true), returning, timeZoneId, EvalMode.ANSI)
+  @transient private lazy val castInput: GenericInternalRow = new GenericInternalRow(1)

Review Comment:
   Done. Added `override def stateful: Boolean = true` (the cast reuses a mutable input row), plus a regression assertion in JsonExpressionsSuite's "... are stateful ..." test alongside the neighboring JSON expressions.



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-58685][SQL] Support the ANSI SQL/JSON JSON_VALUE scalar function [spark]

Posted by "ganeshashree (via GitHub)" <gi...@apache.org>.
ganeshashree commented on code in PR #57888:
URL: https://github.com/apache/spark/pull/57888#discussion_r3751199392


##########
docs/sql-ref-ansi-compliance.md:
##########
@@ -618,6 +619,7 @@ Below is a list of all the keywords in Spark SQL.
 |JOIN|reserved|strict-non-reserved|reserved|
 |JSON|non-reserved|non-reserved|non-reserved|
 |JSON_TABLE|non-reserved|non-reserved|reserved|
+|JSON_VALUE|non-reserved|non-reserved|reserved|

Review Comment:
   Done. Added docs/sql-ref-syntax-qry-select-json-value.md covering the syntax, RETURNING, both ON EMPTY / ON ERROR clauses, defaults, supported result types, and the unsupported forms, and linked it from sql-ref-syntax.md and sql-ref-syntax-qry-select.md.



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-58685][SQL] Support the ANSI SQL/JSON JSON_VALUE scalar function [spark]

Posted by "ganeshashree (via GitHub)" <gi...@apache.org>.
ganeshashree commented on code in PR #57888:
URL: https://github.com/apache/spark/pull/57888#discussion_r3751205947


##########
sql/core/src/test/scala/org/apache/spark/sql/JsonValueSuite.scala:
##########
@@ -0,0 +1,216 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql
+
+import org.apache.spark.SparkRuntimeException
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.test.SharedSparkSession
+import org.apache.spark.sql.types.{IntegerType, StringType}
+
+/**
+ * End-to-end tests for the SQL:2016 `JSON_VALUE` scalar function.
+ */
+class JsonValueSuite extends QueryTest with SharedSparkSession {
+  import testImplicits._
+
+  private val doc =
+    """{"id":7,"name":"Ada","tags":["x","y"],"addr":{"city":"NYC"},"score":null,"f":"3.14"}"""
+
+  test("extract a scalar value as STRING by default") {
+    checkAnswer(sql(s"SELECT json_value('$doc', '$$.name')"), Row("Ada"))
+    // Numbers and booleans come back as their JSON text under the default STRING RETURNING.
+    checkAnswer(sql(s"SELECT json_value('$doc', '$$.id')"), Row("7"))
+  }
+
+  test("RETURNING casts the scalar to the requested type") {
+    checkAnswer(sql(s"SELECT json_value('$doc', '$$.id' RETURNING INT)"), Row(7))
+    assert(sql(s"SELECT json_value('$doc', '$$.id' RETURNING INT)").schema.head.dataType
+      === IntegerType)
+    checkAnswer(sql(s"SELECT json_value('$doc', '$$.f' RETURNING DOUBLE)"), Row(3.14d))
+    checkAnswer(sql("SELECT json_value('{\"v\":\"true\"}', '$.v' RETURNING BOOLEAN)"), Row(true))
+    checkAnswer(
+      sql("SELECT json_value('{\"v\":\"2020-01-02\"}', '$.v' RETURNING DATE)"),
+      Row(java.sql.Date.valueOf("2020-01-02")))
+  }
+
+  test("default RETURNING type is STRING") {
+    assert(sql(s"SELECT json_value('$doc', '$$.name')").schema.head.dataType === StringType)
+  }
+
+  test("a present JSON null yields SQL NULL") {
+    checkAnswer(sql(s"SELECT json_value('$doc', '$$.score')"), Row(null))
+  }
+
+  test("a non-scalar (object/array) match is an ON ERROR case, NULL by default") {
+    checkAnswer(sql(s"SELECT json_value('$doc', '$$.addr')"), Row(null))
+    checkAnswer(sql(s"SELECT json_value('$doc', '$$.tags')"), Row(null))
+  }
+
+  test("a missing path is an ON EMPTY case, NULL by default") {
+    checkAnswer(sql(s"SELECT json_value('$doc', '$$.missing')"), Row(null))
+    checkAnswer(sql(s"SELECT json_value('$doc', '$$.addr.zip')"), Row(null))
+  }
+
+  test("NULL JSON input propagates to NULL (not ON EMPTY / ON ERROR)") {
+    checkAnswer(sql("SELECT json_value(CAST(NULL AS STRING), '$.a' ERROR ON EMPTY ERROR ON ERROR)"),
+      Row(null))
+  }
+
+  test("DEFAULT ON EMPTY") {
+    checkAnswer(sql(s"SELECT json_value('$doc', '$$.missing' DEFAULT '?' ON EMPTY)"), Row("?"))
+    checkAnswer(
+      sql(s"SELECT json_value('$doc', '$$.missing' RETURNING INT DEFAULT 42 ON EMPTY)"), Row(42))
+  }
+
+  test("ERROR ON EMPTY raises for a missing path") {
+    val e = intercept[SparkRuntimeException] {
+      sql(s"SELECT json_value('$doc', '$$.missing' ERROR ON EMPTY)").collect()
+    }
+    assert(e.getCondition == "JSON_VALUE_ON_ERROR.EMPTY")
+  }
+
+  test("DEFAULT ON ERROR for a non-scalar match and for malformed input") {
+    checkAnswer(sql(s"SELECT json_value('$doc', '$$.addr' DEFAULT 'n/a' ON ERROR)"), Row("n/a"))
+    checkAnswer(sql("SELECT json_value('not json', '$.a' DEFAULT 'bad' ON ERROR)"), Row("bad"))
+  }
+
+  test("ERROR ON ERROR raises for malformed input") {
+    val e = intercept[SparkRuntimeException] {
+      sql("SELECT json_value('not json', '$.a' ERROR ON ERROR)").collect()
+    }
+    assert(e.getCondition == "JSON_VALUE_ON_ERROR.ERROR")
+  }
+
+  test("ERROR ON ERROR raises for a non-scalar match") {
+    val e = intercept[SparkRuntimeException] {
+      sql(s"SELECT json_value('$doc', '$$.addr' ERROR ON ERROR)").collect()
+    }
+    assert(e.getCondition == "JSON_VALUE_ON_ERROR.ERROR")
+  }
+
+  test("a failed cast is an ON ERROR case") {
+    // NULL ON ERROR default.
+    checkAnswer(sql(s"SELECT json_value('$doc', '$$.name' RETURNING INT)"), Row(null))
+    // DEFAULT ON ERROR.
+    checkAnswer(
+      sql(s"SELECT json_value('$doc', '$$.name' RETURNING INT DEFAULT -1 ON ERROR)"), Row(-1))
+    // ERROR ON ERROR.
+    val e = intercept[SparkRuntimeException] {
+      sql(s"SELECT json_value('$doc', '$$.name' RETURNING INT ERROR ON ERROR)").collect()
+    }
+    assert(e.getCondition == "JSON_VALUE_ON_ERROR.ERROR")
+  }
+
+  test("independent ON EMPTY and ON ERROR behaviors") {
+    // Missing path -> ON EMPTY branch; a malformed / non-scalar -> ON ERROR branch.

Review Comment:
   Applied.



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-58685][SQL] Support the ANSI SQL/JSON JSON_VALUE scalar function [spark]

Posted by "ganeshashree (via GitHub)" <gi...@apache.org>.
ganeshashree commented on code in PR #57888:
URL: https://github.com/apache/spark/pull/57888#discussion_r3751203876


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/json/JsonExpressionEvalUtils.scala:
##########
@@ -483,6 +483,36 @@ case class JsonTableEvaluator(containerPath: Seq[PathInstruction], explodeRoot:
     }
   }
 
+  /**
+   * Resolves `containerPath` against a single JSON value, preserving the missing / JSON-null /
+   * found distinction that [[evaluate]] collapses. Returns:
+   *
+   *   - `None` if the input is not a single well-formed JSON value (malformed / trailing garbage /
+   *     empty);
+   *   - `Some(Missing)` if the path matches nothing;
+   *   - `Some(NullValue)` if the path matches an explicit JSON `null`;
+   *   - `Some(Found(raw))` if the path matches a value, where `raw` is its verbatim JSON text
+   *     (strings keep their enclosing quotes; an object/array is the whole fragment).
+   *
+   * A `null` input is the caller's responsibility. `explodeRoot` is ignored: this is a single-value
+   * lookup, so construct the evaluator with `explodeRoot = false`.
+   */
+  final def lookup(json: UTF8String): Option[JsonPathResult] = {
+    if (!isSingleWellFormedValue(json)) return None

Review Comment:
   Done. lookup now uses a single parser: it navigates to and serializes the matched value, then drainToRootEnd consumes the rest of the root and rejects any trailing content, so malformed/trailing-garbage inputs are caught without the second O(document size) pass.



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-58685][SQL] Support the ANSI SQL/JSON JSON_VALUE scalar function [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on PR #57888:
URL: https://github.com/apache/spark/pull/57888#issuecomment-5253217449

   **Merge Summary:**
   - merged into master https://github.com/apache/spark/commit/f777036d64d0c0b7413907526f869bd7cb44e49b
   - merged into branch-4.x https://github.com/apache/spark/commit/fa967817f73a559aabfa05513fb2f1d1928bf7c8
   
   *Posted by `merge_spark_pr.py`*


-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-58685][SQL] Support the ANSI SQL/JSON JSON_VALUE scalar function [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #57888:
URL: https://github.com/apache/spark/pull/57888#discussion_r3749198951


##########
docs/sql-ref-ansi-compliance.md:
##########
@@ -618,6 +619,7 @@ Below is a list of all the keywords in Spark SQL.
 |JOIN|reserved|strict-non-reserved|reserved|
 |JSON|non-reserved|non-reserved|non-reserved|
 |JSON_TABLE|non-reserved|non-reserved|reserved|
+|JSON_VALUE|non-reserved|non-reserved|reserved|

Review Comment:
   Please add a `JSON_VALUE` SQL reference page and link it from the SQL syntax index. This exposes RETURNING and both behavior clauses as a public SQL contract, but the keyword table is currently the only user documentation, so the syntax, defaults, supported result types, and unsupported forms are not discoverable.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/json/JsonExpressionEvalUtils.scala:
##########
@@ -483,6 +483,36 @@ case class JsonTableEvaluator(containerPath: Seq[PathInstruction], explodeRoot:
     }
   }
 
+  /**
+   * Resolves `containerPath` against a single JSON value, preserving the missing / JSON-null /
+   * found distinction that [[evaluate]] collapses. Returns:
+   *
+   *   - `None` if the input is not a single well-formed JSON value (malformed / trailing garbage /
+   *     empty);
+   *   - `Some(Missing)` if the path matches nothing;
+   *   - `Some(NullValue)` if the path matches an explicit JSON `null`;
+   *   - `Some(Found(raw))` if the path matches a value, where `raw` is its verbatim JSON text
+   *     (strings keep their enclosing quotes; an object/array is the whole fragment).
+   *
+   * A `null` input is the caller's responsibility. `explodeRoot` is ignored: this is a single-value
+   * lookup, so construct the evaluator with `explodeRoot = false`.
+   */
+  final def lookup(json: UTF8String): Option[JsonPathResult] = {
+    if (!isSingleWellFormedValue(json)) return None

Review Comment:
   Can we validate and navigate with one parser here? This line fully traverses every non-null document, then `lookup` creates a second parser and traverses it again, adding an extra O(document size) pass per row. Capture the matched value, consume the rest of the root, and reject any trailing token before returning it.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/jsonExpressions.scala:
##########
@@ -637,6 +637,215 @@ case class JsonTable(
     copy(child = newChild)
 }
 
+/**
+ * Behavior of `JSON_VALUE`'s `ON EMPTY` / `ON ERROR` clause: what to produce when the path matches
+ * nothing, or when the input/extraction fails.
+ */
+sealed trait JsonValueBehavior
+object JsonValueBehavior {
+  /** Produce SQL NULL (the SQL-standard default for both ON EMPTY and ON ERROR). */
+  case object Null extends JsonValueBehavior
+  /** Raise an error. */
+  case object Error extends JsonValueBehavior
+  /** Produce the value of a `DEFAULT` expression, cast to the RETURNING type. */
+  case object Default extends JsonValueBehavior
+}
+
+// scalastyle:off line.size.limit
+/**
+ * The SQL:2016 `JSON_VALUE` scalar function (feature T821): extracts a single scalar located by a
+ * SQL/JSON `path` from a JSON input, casts it to the `RETURNING` type (default STRING), and applies
+ * the `ON EMPTY` / `ON ERROR` behavior when the path matches nothing or the extraction/cast fails:
+ *
+ *   - missing path                       -> ON EMPTY behavior
+ *   - explicit JSON `null`                -> SQL NULL
+ *   - non-scalar (object/array) match     -> ON ERROR behavior
+ *   - malformed / non-single-value input  -> ON ERROR behavior
+ *   - scalar match, cast fails            -> ON ERROR behavior
+ *   - scalar match, cast succeeds         -> the cast value
+ *
+ * Both clauses default to NULL per the standard. A `null` JSON input yields SQL NULL directly, not
+ * the ON EMPTY/ERROR path.
+ *
+ * `emptyDefault` / `errorDefault` hold the `DEFAULT <expr>` expressions, present only for the
+ * corresponding `Default` behavior. The child list is variable (0-2 defaults), so this extends
+ * `Expression` directly rather than `UnaryExpression`.
+ *
+ * {{{
+ *   JSON_VALUE('{"id":7}', '$.id' RETURNING INT)                    -- 7
+ *   JSON_VALUE('{"id":7}', '$.missing' DEFAULT -1 ON EMPTY)          -- -1
+ *   JSON_VALUE('{"a":{}}', '$.a' ERROR ON ERROR)                     -- raises (non-scalar)
+ * }}}
+ */
+// scalastyle:on line.size.limit
+case class JsonValue(
+    child: Expression,
+    path: String,
+    returning: DataType,
+    onEmpty: JsonValueBehavior,
+    onError: JsonValueBehavior,
+    emptyDefault: Option[Expression],
+    errorDefault: Option[Expression],
+    timeZoneId: Option[String] = None,
+    ansiEnabled: Boolean = SQLConf.get.ansiEnabled)
+  extends Expression
+  with TimeZoneAwareExpression
+  with CodegenFallback
+  with ExpectsInputTypes
+  with QueryErrorsBase {
+
+  override def nullable: Boolean = true
+
+  // Children: the JSON input first, then whichever DEFAULT expressions are present. The two
+  // defaults are resolved/coerced through the normal child machinery; their cast to `returning`
+  // happens at eval time via `emptyDefaultCast` / `errorDefaultCast`.
+  override def children: Seq[Expression] =
+    child +: (emptyDefault.toSeq ++ errorDefault.toSeq)
+
+  // One entry per child: the JSON input must be STRING; the DEFAULT children accept anything (they
+  // are cast to `returning` explicitly at eval). One entry per child is required because the
+  // coercion rule zips `children` against `inputTypes` and rebuilds via `withNewChildren`; a
+  // shorter list would truncate the zip and pass the wrong child count.
+  override def inputTypes: Seq[AbstractDataType] =
+    StringTypeWithCollation(supportsTrimCollation = true) +:
+      children.tail.map(_ => AnyDataType)
+
+  override def dataType: DataType = returning
+
+  override def withTimeZone(timeZoneId: String): TimeZoneAwareExpression =
+    copy(timeZoneId = Option(timeZoneId))
+
+  override def checkInputDataTypes(): TypeCheckResult = {
+    val inputCheck = super.checkInputDataTypes()
+    if (inputCheck.isFailure) {
+      inputCheck
+    } else if (!JsonPathParser.hasWildcard(path).contains(false)) {
+      // The path must parse and be wildcard-free (JSON_VALUE returns a single scalar).
+      DataTypeMismatch(
+        errorSubClass = "INVALID_JSON_PATH",
+        messageParameters = Map(
+          "functionName" -> toSQLId(prettyName), "path" -> toSQLValue(path)))
+    } else if (!JsonValue.isValidReturningType(returning)) {
+      // RETURNING is restricted to scalar (atomic) types per ANSI 9075-2 6.28.
+      DataTypeMismatch(
+        errorSubClass = "INVALID_JSON_SCALAR_RETURNING_TYPE",
+        messageParameters = Map(
+          "functionName" -> toSQLId(prettyName), "returningType" -> toSQLType(returning)))
+    } else {
+      TypeCheckResult.TypeCheckSuccess
+    }
+  }
+
+  // Eval mode for the user-provided DEFAULT expression casts: follows the session ANSI setting like
+  // any ordinary value cast. The extracted-scalar cast is separate (see `valueCast`).
+  @transient private lazy val defaultEvalMode = EvalMode.fromBoolean(ansiEnabled)
+
+  // Path parsed once (the grammar makes it a string literal). `checkInputDataTypes` guarantees it
+  // parses and is wildcard-free, so the evaluator is only built for a valid path.
+  @transient private lazy val evaluator: JsonTableEvaluator =
+    JsonTableEvaluator(JsonPathParser.parse(path).getOrElse(Nil), explodeRoot = false)
+
+  // Cast from the extracted scalar's STRING form to the RETURNING type, built once over a reused
+  // input slot to avoid per-row allocation. Always an ANSI (throwing) cast, independent of the
+  // session's ANSI setting, so a failed conversion always routes to ON ERROR (see `eval`) rather
+  // than being silently turned into NULL by a non-ANSI session.
+  @transient private lazy val valueCast: Expression =
+    Cast(BoundReference(0, StringType, nullable = true), returning, timeZoneId, EvalMode.ANSI)
+  @transient private lazy val castInput: GenericInternalRow = new GenericInternalRow(1)

Review Comment:
   Please mark `JsonValue` stateful. This mutable row is reused by `castScalar`, but `Expression.stateful` defaults to false, so interpreted execution may share the same instance instead of fresh-copying it and concurrent evaluations can cast each other's value. Add `override def stateful: Boolean = true` and a shared-expression regression test, matching the neighboring JSON expressions' evaluator isolation.



##########
sql/core/src/test/scala/org/apache/spark/sql/JsonValueSuite.scala:
##########
@@ -0,0 +1,216 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql
+
+import org.apache.spark.SparkRuntimeException
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.test.SharedSparkSession
+import org.apache.spark.sql.types.{IntegerType, StringType}
+
+/**
+ * End-to-end tests for the SQL:2016 `JSON_VALUE` scalar function.
+ */
+class JsonValueSuite extends QueryTest with SharedSparkSession {
+  import testImplicits._
+
+  private val doc =
+    """{"id":7,"name":"Ada","tags":["x","y"],"addr":{"city":"NYC"},"score":null,"f":"3.14"}"""
+
+  test("extract a scalar value as STRING by default") {
+    checkAnswer(sql(s"SELECT json_value('$doc', '$$.name')"), Row("Ada"))
+    // Numbers and booleans come back as their JSON text under the default STRING RETURNING.
+    checkAnswer(sql(s"SELECT json_value('$doc', '$$.id')"), Row("7"))
+  }
+
+  test("RETURNING casts the scalar to the requested type") {
+    checkAnswer(sql(s"SELECT json_value('$doc', '$$.id' RETURNING INT)"), Row(7))
+    assert(sql(s"SELECT json_value('$doc', '$$.id' RETURNING INT)").schema.head.dataType
+      === IntegerType)
+    checkAnswer(sql(s"SELECT json_value('$doc', '$$.f' RETURNING DOUBLE)"), Row(3.14d))
+    checkAnswer(sql("SELECT json_value('{\"v\":\"true\"}', '$.v' RETURNING BOOLEAN)"), Row(true))
+    checkAnswer(
+      sql("SELECT json_value('{\"v\":\"2020-01-02\"}', '$.v' RETURNING DATE)"),
+      Row(java.sql.Date.valueOf("2020-01-02")))
+  }
+
+  test("default RETURNING type is STRING") {
+    assert(sql(s"SELECT json_value('$doc', '$$.name')").schema.head.dataType === StringType)
+  }
+
+  test("a present JSON null yields SQL NULL") {
+    checkAnswer(sql(s"SELECT json_value('$doc', '$$.score')"), Row(null))
+  }
+
+  test("a non-scalar (object/array) match is an ON ERROR case, NULL by default") {
+    checkAnswer(sql(s"SELECT json_value('$doc', '$$.addr')"), Row(null))
+    checkAnswer(sql(s"SELECT json_value('$doc', '$$.tags')"), Row(null))
+  }
+
+  test("a missing path is an ON EMPTY case, NULL by default") {
+    checkAnswer(sql(s"SELECT json_value('$doc', '$$.missing')"), Row(null))
+    checkAnswer(sql(s"SELECT json_value('$doc', '$$.addr.zip')"), Row(null))
+  }
+
+  test("NULL JSON input propagates to NULL (not ON EMPTY / ON ERROR)") {
+    checkAnswer(sql("SELECT json_value(CAST(NULL AS STRING), '$.a' ERROR ON EMPTY ERROR ON ERROR)"),
+      Row(null))
+  }
+
+  test("DEFAULT ON EMPTY") {
+    checkAnswer(sql(s"SELECT json_value('$doc', '$$.missing' DEFAULT '?' ON EMPTY)"), Row("?"))
+    checkAnswer(
+      sql(s"SELECT json_value('$doc', '$$.missing' RETURNING INT DEFAULT 42 ON EMPTY)"), Row(42))
+  }
+
+  test("ERROR ON EMPTY raises for a missing path") {
+    val e = intercept[SparkRuntimeException] {
+      sql(s"SELECT json_value('$doc', '$$.missing' ERROR ON EMPTY)").collect()
+    }
+    assert(e.getCondition == "JSON_VALUE_ON_ERROR.EMPTY")
+  }
+
+  test("DEFAULT ON ERROR for a non-scalar match and for malformed input") {
+    checkAnswer(sql(s"SELECT json_value('$doc', '$$.addr' DEFAULT 'n/a' ON ERROR)"), Row("n/a"))
+    checkAnswer(sql("SELECT json_value('not json', '$.a' DEFAULT 'bad' ON ERROR)"), Row("bad"))
+  }
+
+  test("ERROR ON ERROR raises for malformed input") {
+    val e = intercept[SparkRuntimeException] {
+      sql("SELECT json_value('not json', '$.a' ERROR ON ERROR)").collect()
+    }
+    assert(e.getCondition == "JSON_VALUE_ON_ERROR.ERROR")
+  }
+
+  test("ERROR ON ERROR raises for a non-scalar match") {
+    val e = intercept[SparkRuntimeException] {
+      sql(s"SELECT json_value('$doc', '$$.addr' ERROR ON ERROR)").collect()
+    }
+    assert(e.getCondition == "JSON_VALUE_ON_ERROR.ERROR")
+  }
+
+  test("a failed cast is an ON ERROR case") {
+    // NULL ON ERROR default.
+    checkAnswer(sql(s"SELECT json_value('$doc', '$$.name' RETURNING INT)"), Row(null))
+    // DEFAULT ON ERROR.
+    checkAnswer(
+      sql(s"SELECT json_value('$doc', '$$.name' RETURNING INT DEFAULT -1 ON ERROR)"), Row(-1))
+    // ERROR ON ERROR.
+    val e = intercept[SparkRuntimeException] {
+      sql(s"SELECT json_value('$doc', '$$.name' RETURNING INT ERROR ON ERROR)").collect()
+    }
+    assert(e.getCondition == "JSON_VALUE_ON_ERROR.ERROR")
+  }
+
+  test("independent ON EMPTY and ON ERROR behaviors") {
+    // Missing path -> ON EMPTY branch; a malformed / non-scalar -> ON ERROR branch.

Review Comment:
   ```suggestion
       // Missing path -> ON EMPTY branch; malformed input / non-scalar value -> ON ERROR branch.
   ```



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-58685][SQL] Support the ANSI SQL/JSON JSON_VALUE scalar function [spark]

Posted by "ganeshashree (via GitHub)" <gi...@apache.org>.
ganeshashree commented on code in PR #57888:
URL: https://github.com/apache/spark/pull/57888#discussion_r3756890189


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/json/JsonExpressionEvalUtils.scala:
##########
@@ -483,6 +483,63 @@ case class JsonTableEvaluator(containerPath: Seq[PathInstruction], explodeRoot:
     }
   }
 
+  /**
+   * Resolves `containerPath` against a single JSON value, preserving the missing / JSON-null /
+   * found distinction that [[evaluate]] collapses. Returns:
+   *
+   *   - `None` if the input is not a single well-formed JSON value (malformed / trailing garbage /
+   *     empty);
+   *   - `Some(Missing)` if the path matches nothing;
+   *   - `Some(NullValue)` if the path matches an explicit JSON `null`;
+   *   - `Some(Found(raw))` if the path matches a value, where `raw` is its verbatim JSON text
+   *     (strings keep their enclosing quotes; an object/array is the whole fragment).
+   *
+   * A `null` input is the caller's responsibility. `explodeRoot` is ignored: this is a single-value
+   * lookup, so construct the evaluator with `explodeRoot = false`.
+   *
+   * A single parser both navigates the path and validates well-formedness: after the matched value
+   * is captured (or the path is found missing), [[drainToRootEnd]] consumes the rest of the root
+   * value and rejects any trailing content, so a valid prefix followed by garbage (or a second
+   * root value) is rejected exactly as a fully malformed document is. This avoids the extra
+   * O(document size) validation pass a separate `isSingleWellFormedValue` scan would add per row.
+   */
+  final def lookup(json: UTF8String): Option[JsonPathResult] = {
+    Utils.tryWithResource(CreateJacksonParser.utf8String(jsonFactory, json)) { parser =>
+      try {
+        if (parser.nextToken() == null) {
+          None // empty or whitespace-only
+        } else {
+          val result = positionAt(parser, containerPath) match {
+            case PositionResult.Missing => JsonPathResult.Missing
+            case PositionResult.NullValue => JsonPathResult.NullValue
+            case PositionResult.AtValue => JsonPathResult.Found(serializeCurrentValue(parser))

Review Comment:
   Done.



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-58685][SQL] Support the ANSI SQL/JSON JSON_VALUE scalar function [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #57888:
URL: https://github.com/apache/spark/pull/57888#discussion_r3756210355


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/json/JsonExpressionEvalUtils.scala:
##########
@@ -483,6 +483,63 @@ case class JsonTableEvaluator(containerPath: Seq[PathInstruction], explodeRoot:
     }
   }
 
+  /**
+   * Resolves `containerPath` against a single JSON value, preserving the missing / JSON-null /
+   * found distinction that [[evaluate]] collapses. Returns:
+   *
+   *   - `None` if the input is not a single well-formed JSON value (malformed / trailing garbage /
+   *     empty);
+   *   - `Some(Missing)` if the path matches nothing;
+   *   - `Some(NullValue)` if the path matches an explicit JSON `null`;
+   *   - `Some(Found(raw))` if the path matches a value, where `raw` is its verbatim JSON text
+   *     (strings keep their enclosing quotes; an object/array is the whole fragment).
+   *
+   * A `null` input is the caller's responsibility. `explodeRoot` is ignored: this is a single-value
+   * lookup, so construct the evaluator with `explodeRoot = false`.
+   *
+   * A single parser both navigates the path and validates well-formedness: after the matched value
+   * is captured (or the path is found missing), [[drainToRootEnd]] consumes the rest of the root
+   * value and rejects any trailing content, so a valid prefix followed by garbage (or a second
+   * root value) is rejected exactly as a fully malformed document is. This avoids the extra
+   * O(document size) validation pass a separate `isSingleWellFormedValue` scan would add per row.
+   */
+  final def lookup(json: UTF8String): Option[JsonPathResult] = {
+    Utils.tryWithResource(CreateJacksonParser.utf8String(jsonFactory, json)) { parser =>
+      try {
+        if (parser.nextToken() == null) {
+          None // empty or whitespace-only
+        } else {
+          val result = positionAt(parser, containerPath) match {
+            case PositionResult.Missing => JsonPathResult.Missing
+            case PositionResult.NullValue => JsonPathResult.NullValue
+            case PositionResult.AtValue => JsonPathResult.Found(serializeCurrentValue(parser))

Review Comment:
   **Non-blocking:**
   
   Return the matched scalar token text directly from this parser instead of serializing it first. `castScalar` reparses string fragments in `unquotedString`, so the current path copies every matched value and performs a second parse for every matched string row; a scalar/non-scalar result from `lookup` can preserve `drainToRootEnd` validation without that work.



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-58685][SQL] Support the ANSI SQL/JSON JSON_VALUE scalar function [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan closed pull request #57888: [SPARK-58685][SQL] Support the ANSI SQL/JSON JSON_VALUE scalar function
URL: https://github.com/apache/spark/pull/57888


-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org