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: [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]