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