This is an automated email from the ASF dual-hosted git repository.

uros-b pushed a commit to branch branch-4.x
in repository https://gitbox.apache.org/repos/asf/spark.git


The following commit(s) were added to refs/heads/branch-4.x by this push:
     new 2e2cb90e0310 [SPARK-58222][SQL] Add `try_variant_array_append` 
expression
2e2cb90e0310 is described below

commit 2e2cb90e0310506558d49b3825019e08ff86d93e
Author: bojana-db <[email protected]>
AuthorDate: Tue Jul 21 11:16:28 2026 +0000

    [SPARK-58222][SQL] Add `try_variant_array_append` expression
    
    ### What changes were proposed in this pull request?
    Adds the SQL function `try_variant_array_append(v, path, val)`, the 
error-tolerant counterpart of `variant_array_append`. It appends a value to the 
array in a Variant value at a single JSONPath location, returning NULL instead 
of failing the query when the operation hits a recoverable error.
    
    Details:
    
    - On a valid append, behaves exactly like `variant_array_append`: appends 
`val` as a new last element of the array at `path` (e.g. `$.a`, `$[0]`, 
`$.a[1]`); the root path `$` targets the whole Variant, which must itself be an 
array; a missing key or out-of-range array index along the path leaves `v` 
unchanged;
    - Recoverable errors are caught and return NULL instead of throwing: a path 
type mismatch (`VARIANT_PATH_TYPE_MISMATCH`), raised when a path segment is 
applied to a value of an incompatible type or when the target is not an array;
    - Non-recoverable errors still throw, matching `variant_array_append`: a 
malformed path is rejected with `INVALID_VARIANT_PATH` (the path is parsed 
before the append), and a result exceeding the size limit raises 
`VARIANT_SIZE_LIMIT`;
    - Any NULL argument returns NULL;
    - The value may be any expression castable to variant. An array value is 
appended as a single nested element rather than flattened, and a variant null 
appends a null element.
    
    ### Why are the changes needed?
    Error-tolerant counterpart of `variant_array_append`.
    
    ### Does this PR introduce _any_ user-facing change?
    Yes, a new SQL function `try_variant_array_append` (and the corresponding 
Scala/Python `functions` API).
    
    ### How was this patch tested?
    Unit tests.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    Generated-by: Cursor with Claude Opus 4.8
    
    Closes #57378 from bojana-db/try-variant-array-append.
    
    Authored-by: bojana-db <[email protected]>
    Signed-off-by: Uros Bojanic <[email protected]>
    (cherry picked from commit f0cbaf7862b5f054b5a9d9f83e278abba48373a4)
    Signed-off-by: Uros Bojanic <[email protected]>
---
 .../source/reference/pyspark.sql/functions.rst     |   1 +
 python/pyspark/sql/connect/functions/builtin.py    |  10 ++
 python/pyspark/sql/functions/__init__.py           |   1 +
 python/pyspark/sql/functions/builtin.py            |  61 +++++++-
 python/pyspark/sql/tests/test_functions.py         |   9 ++
 .../scala/org/apache/spark/sql/functions.scala     |  45 +++++-
 .../sql/catalyst/analysis/FunctionRegistry.scala   |   3 +-
 .../variant/VariantExpressionEvalUtils.scala       |  13 +-
 .../expressions/variant/variantExpressions.scala   | 174 ++++++++++++++-------
 .../variant/VariantExpressionSuite.scala           | 116 +++++++++-----
 .../apache/spark/sql/PlanGenerationTestSuite.scala |   4 +
 .../function_try_variant_array_append.explain      |   2 +
 .../function_variant_array_append.explain          |   2 +-
 .../queries/function_try_variant_array_append.json | 125 +++++++++++++++
 .../function_try_variant_array_append.proto.bin    | Bin 0 -> 1169 bytes
 .../sql-functions/sql-expression-schema.md         |   3 +-
 .../scala/org/apache/spark/sql/VariantSuite.scala  |  50 ++++++
 17 files changed, 513 insertions(+), 106 deletions(-)

diff --git a/python/docs/source/reference/pyspark.sql/functions.rst 
b/python/docs/source/reference/pyspark.sql/functions.rst
index 2ccfde351d87..2e6049f37870 100644
--- a/python/docs/source/reference/pyspark.sql/functions.rst
+++ b/python/docs/source/reference/pyspark.sql/functions.rst
@@ -603,6 +603,7 @@ VARIANT Functions
     schema_of_variant_agg
     try_variant_get
     variant_array_append
+    try_variant_array_append
     variant_delete
     variant_get
     variant_insert
diff --git a/python/pyspark/sql/connect/functions/builtin.py 
b/python/pyspark/sql/connect/functions/builtin.py
index 1caa3a9bf7f2..be5e5a4f0c6d 100644
--- a/python/pyspark/sql/connect/functions/builtin.py
+++ b/python/pyspark/sql/connect/functions/builtin.py
@@ -2262,6 +2262,16 @@ def variant_array_append(
 variant_array_append.__doc__ = pysparkfuncs.variant_array_append.__doc__
 
 
+def try_variant_array_append(
+    v: "ColumnOrName", path: Union[Column, str], value: "ColumnOrName"
+) -> Column:
+    path_col = path if isinstance(path, Column) else lit(path)
+    return _invoke_function("try_variant_array_append", _to_col(v), path_col, 
_to_col(value))
+
+
+try_variant_array_append.__doc__ = 
pysparkfuncs.try_variant_array_append.__doc__
+
+
 def variant_get(v: "ColumnOrName", path: Union[Column, str], targetType: str) 
-> Column:
     assert isinstance(path, (Column, str))
     if isinstance(path, str):
diff --git a/python/pyspark/sql/functions/__init__.py 
b/python/pyspark/sql/functions/__init__.py
index b3da0adee990..f1a0e1de5b75 100644
--- a/python/pyspark/sql/functions/__init__.py
+++ b/python/pyspark/sql/functions/__init__.py
@@ -481,6 +481,7 @@ __all__ = [  # noqa: F405
     "schema_of_variant_agg",
     "try_variant_get",
     "variant_array_append",
+    "try_variant_array_append",
     "variant_delete",
     "variant_get",
     "variant_insert",
diff --git a/python/pyspark/sql/functions/builtin.py 
b/python/pyspark/sql/functions/builtin.py
index 724d1f90e568..9e092ef1c4fb 100644
--- a/python/pyspark/sql/functions/builtin.py
+++ b/python/pyspark/sql/functions/builtin.py
@@ -22859,8 +22859,8 @@ def variant_array_append(
 ) -> Column:
     """
     Appends a value to the array in a variant at the given JSONPath location. 
Returns the variant
-    unchanged if a path key or index is absent, throws an error if a path 
segment hits a value of
-    an incompatible type or the target is not an array, and returns NULL if 
any argument is NULL.
+    unchanged if a path key or index is absent. Throws an error if a path 
segment hits a value of
+    an incompatible type or the target is not an array. Returns NULL if any 
argument is NULL.
 
     .. versionadded:: 4.3.0
 
@@ -22914,6 +22914,63 @@ def variant_array_append(
     )
 
 
+@_try_remote_functions
+def try_variant_array_append(
+    v: "ColumnOrName", path: Union[Column, str], value: "ColumnOrName"
+) -> Column:
+    """
+    Appends a value to the array in a variant at the given JSONPath location. 
Returns the variant
+    unchanged if a path key or index is absent. Returns NULL if a path segment 
hits a value of an
+    incompatible type, the target is not an array, or if any argument is NULL.
+
+    .. versionadded:: 4.3.0
+
+    Parameters
+    ----------
+    v : :class:`~pyspark.sql.Column` or str
+        a variant column or column name
+    path : :class:`~pyspark.sql.Column` or str
+        the JSONPath target array. A `str` is a literal path; a 
:class:`~pyspark.sql.Column`
+        supplies the path at runtime. A valid path should start with `$` and 
is followed by zero or
+        more segments like `[123]`, `.name`, `['name']`, or `["name"]`.
+    value : :class:`~pyspark.sql.Column` or str
+        the value to append. Any expression castable to variant.
+
+    Returns
+    -------
+    :class:`~pyspark.sql.Column`
+        a variant column with `value` appended to the array at `path`
+
+    Examples
+    --------
+    >>> from pyspark.sql.functions import lit, parse_json, to_json, 
try_variant_array_append
+    >>> df = spark.createDataFrame([{
+    ...     'json': '''[[1, 2], 5]''',
+    ...     'path': '$[0]'
+    ... }])
+    >>> v = parse_json(df.json)
+    >>> df.select(to_json(try_variant_array_append(v, "$", 
lit(3))).alias("r")).collect()
+    [Row(r='[[1,2],5,3]')]
+    >>> df.select(to_json(try_variant_array_append(v, "$[5]", 
lit(3))).alias("r")).collect()
+    [Row(r='[[1,2],5]')]
+    >>> df.select(to_json(try_variant_array_append(v, df.path, 
lit(9))).alias("r")).collect()
+    [Row(r='[[1,2,9],5]')]
+    >>> df.select(to_json(try_variant_array_append(v, "$[1]", 
lit(9))).alias("r")).collect()
+    [Row(r=None)]
+    >>> df.select(try_variant_array_append(v, "$", 
lit(None)).alias("r")).collect()
+    [Row(r=None)]
+    """
+    from pyspark.sql.classic.column import _to_java_column
+
+    path_col = path if isinstance(path, Column) else lit(path)
+    return _invoke_function(
+        "try_variant_array_append",
+        _to_java_column(v),
+        _to_java_column(path_col),
+        _to_java_column(value),
+    )
+
+
 @_try_remote_functions
 def variant_get(v: "ColumnOrName", path: Union[Column, str], targetType: str) 
-> Column:
     """
diff --git a/python/pyspark/sql/tests/test_functions.py 
b/python/pyspark/sql/tests/test_functions.py
index 6367ebfdd9bf..2594c8c60b76 100644
--- a/python/pyspark/sql/tests/test_functions.py
+++ b/python/pyspark/sql/tests/test_functions.py
@@ -3569,6 +3569,15 @@ class FunctionsTestsMixin:
             df.select(F.to_json(F.variant_array_append(arr, df.arrpath, 
F.lit(9)))),
             ["[1,2,9]", "[[3,9],4]"],
         )
+        check(
+            df.select(F.to_json(F.try_variant_array_append(arr, "$", 
F.lit(9)))),
+            ["[1,2,9]", "[[3],4,9]"],
+        )
+        check(df.select(F.to_json(F.try_variant_array_append(arr, "$.a", 
F.lit(9)))), [None, None])
+        check(
+            df.select(F.to_json(F.try_variant_array_append(arr, df.arrpath, 
F.lit(9)))),
+            ["[1,2,9]", "[[3,9],4]"],
+        )
         check(df.select(F.schema_of_variant(v)), ["OBJECT<a: BIGINT>", 
"OBJECT<b: BIGINT>"])
         check(df.select(F.schema_of_variant_agg(v)), ["OBJECT<a: BIGINT, b: 
BIGINT>"])
 
diff --git a/sql/api/src/main/scala/org/apache/spark/sql/functions.scala 
b/sql/api/src/main/scala/org/apache/spark/sql/functions.scala
index 59af71017882..6d824a675223 100644
--- a/sql/api/src/main/scala/org/apache/spark/sql/functions.scala
+++ b/sql/api/src/main/scala/org/apache/spark/sql/functions.scala
@@ -14292,8 +14292,8 @@ object functions {
 
   /**
    * Appends a value to the array in a variant at the given JSONPath location. 
Returns the variant
-   * unchanged if a path key or index is absent, throws an error if a path 
segment hits a value of
-   * an incompatible type or the target is not an array, and returns NULL if 
any argument is NULL.
+   * unchanged if a path key or index is absent. Throws an error if a path 
segment hits a value of
+   * an incompatible type or the target is not an array. Returns NULL if any 
argument is NULL.
    *
    * @param v
    *   a variant column. A column that evaluates to a variant.
@@ -14311,8 +14311,8 @@ object functions {
 
   /**
    * Appends a value to the array in a variant at the given JSONPath location. 
Returns the variant
-   * unchanged if a path key or index is absent, throws an error if a path 
segment hits a value of
-   * an incompatible type or the target is not an array, and returns NULL if 
any argument is NULL.
+   * unchanged if a path key or index is absent. Throws an error if a path 
segment hits a value of
+   * an incompatible type or the target is not an array. Returns NULL if any 
argument is NULL.
    *
    * @param v
    *   a variant column. A column that evaluates to a variant.
@@ -14328,6 +14328,43 @@ object functions {
   def variant_array_append(v: Column, path: String, value: Column): Column =
     Column.fn("variant_array_append", v, lit(path), value)
 
+  /**
+   * Appends a value to the array in a variant at the given JSONPath location. 
Returns the variant
+   * unchanged if a path key or index is absent. Returns NULL if a path 
segment hits a value of an
+   * incompatible type, the target is not an array, or if any argument is NULL.
+   *
+   * @param v
+   *   a variant column.
+   * @param path
+   *   the column containing the JSONPath string identifying the target array. 
A valid path should
+   *   start with `$` and is followed by zero or more segments like `[123]`, 
`.name`, `['name']`,
+   *   or `["name"]`.
+   * @param value
+   *   the value to append. Any expression castable to variant.
+   * @group variant_funcs
+   * @since 4.3.0
+   */
+  def try_variant_array_append(v: Column, path: Column, value: Column): Column 
=
+    Column.fn("try_variant_array_append", v, path, value)
+
+  /**
+   * Appends a value to the array in a variant at the given JSONPath location. 
Returns the variant
+   * unchanged if a path key or index is absent. Returns NULL if a path 
segment hits a value of an
+   * incompatible type, the target is not an array, or if any argument is NULL.
+   *
+   * @param v
+   *   a variant column.
+   * @param path
+   *   the JSONPath identifying the target array. A valid path should start 
with `$` and is
+   *   followed by zero or more segments like `[123]`, `.name`, `['name']`, or 
`["name"]`.
+   * @param value
+   *   the value to append. Any expression castable to variant.
+   * @group variant_funcs
+   * @since 4.3.0
+   */
+  def try_variant_array_append(v: Column, path: String, value: Column): Column 
=
+    Column.fn("try_variant_array_append", v, lit(path), value)
+
   /**
    * Extracts a sub-variant from `v` according to `path` string, and then cast 
the sub-variant to
    * `targetType`. Returns null if the path does not exist. Throws an 
exception if the cast fails.
diff --git 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/FunctionRegistry.scala
 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/FunctionRegistry.scala
index a9be95d7b951..b34a5b7ad1b0 100644
--- 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/FunctionRegistry.scala
+++ 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/FunctionRegistry.scala
@@ -989,7 +989,8 @@ object FunctionRegistry {
     expressionBuilder("variant_insert", VariantInsertExpressionBuilder),
     expressionBuilder("try_variant_insert", TryVariantInsertExpressionBuilder),
     expressionBuilder("variant_set", VariantSetExpressionBuilder),
-    expression[VariantArrayAppend]("variant_array_append"),
+    expressionBuilder("variant_array_append", 
VariantArrayAppendExpressionBuilder),
+    expressionBuilder("try_variant_array_append", 
TryVariantArrayAppendExpressionBuilder),
 
     // Spatial
     expression[ST_AsBinary]("st_asbinary"),
diff --git 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/variant/VariantExpressionEvalUtils.scala
 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/variant/VariantExpressionEvalUtils.scala
index ba5d72c56474..0872cda99801 100644
--- 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/variant/VariantExpressionEvalUtils.scala
+++ 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/variant/VariantExpressionEvalUtils.scala
@@ -224,7 +224,9 @@ object VariantExpressionEvalUtils {
    * Append `value` to the array in `input` at `javaSegments`. `path` is the 
source string used in
    * error messages. `value` is cast to a variant first; a size overflow maps 
to
    * `VARIANT_SIZE_LIMIT` and a target that is not an array (or an 
incompatible path segment) maps
-   * to `VARIANT_PATH_TYPE_MISMATCH`.
+   * to `VARIANT_PATH_TYPE_MISMATCH`. When `failOnError` is false (the 
`try_variant_array_append`
+   * mode), a path type mismatch returns null instead of throwing; a size 
overflow (and a malformed
+   * path, rejected earlier during parsing) is still raised.
    */
   def arrayAppendAtPath(
       input: VariantVal,
@@ -232,7 +234,8 @@ object VariantExpressionEvalUtils {
       path: String,
       value: Any,
       valueDataType: DataType,
-      functionName: String): VariantVal = {
+      functionName: String,
+      failOnError: Boolean): VariantVal = {
     val v = new Variant(input.getValue, input.getMetadata)
     try {
       val valVal = castToVariant(value, valueDataType)
@@ -240,6 +243,7 @@ object VariantExpressionEvalUtils {
       val out = VariantBuilder.arrayAppendAtPath(v, javaSegments, valVariant)
       new VariantVal(out.getValue, out.getMetadata)
     } catch {
+      case _: VariantPathTypeMismatchException if !failOnError => null
       case e: VariantPathTypeMismatchException =>
         throw QueryExecutionErrors.variantPathTypeMismatch(
           path, renderVariantPath(javaSegments.take(e.depth)), functionName)
@@ -253,10 +257,11 @@ object VariantExpressionEvalUtils {
       path: UTF8String,
       value: Any,
       valueDataType: DataType,
-      functionName: String): VariantVal = {
+      functionName: String,
+      failOnError: Boolean): VariantVal = {
     val pathStr = path.toString
     val javaSegments = toJavaSegments(parseVariantPath(pathStr, functionName, 
allowRoot = true))
-    arrayAppendAtPath(input, javaSegments, pathStr, value, valueDataType, 
functionName)
+    arrayAppendAtPath(input, javaSegments, pathStr, value, valueDataType, 
functionName, failOnError)
   }
 
   /** Cast a Spark value from `dataType` into the variant type. */
diff --git 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/variant/variantExpressions.scala
 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/variant/variantExpressions.scala
index 469dc57a50ae..fa6a955097d9 100644
--- 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/variant/variantExpressions.scala
+++ 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/variant/variantExpressions.scala
@@ -1192,40 +1192,11 @@ object VariantSetExpressionBuilder extends 
ExpressionBuilder {
   }
 }
 
-// scalastyle:off line.size.limit
-@ExpressionDescription(
-  usage = "_FUNC_(v, path, val) - Appends a value to the array in a variant at 
the given JSONPath " +
-    "location. Returns the variant unchanged if a path key or index is absent. 
Throws an error " +
-    "if a path segment hits a value of an incompatible type or the target is 
not an array. " +
-    "Returns NULL if any argument is NULL.",
-  arguments = """
-    Arguments:
-      * v - A variant value to mutate.
-      * path - A string expression evaluating to a JSONPath identifying the 
target array. A valid
-          path should start with `$` and is followed by zero or more segments 
like `[123]`, `.name`,
-          `['name']`, or `["name"]`.
-      * val - Any expression castable to variant.
-  """,
-  examples = """
-    Examples:
-      > SELECT _FUNC_(parse_json('[1, 2, 3]'), '$', 4);
-       [1,2,3,4]
-      > SELECT _FUNC_(parse_json('{"a": [1, 2]}'), '$.a', 3);
-       {"a":[1,2,3]}
-      > SELECT _FUNC_(parse_json('[1]'), '$', parse_json('[2, 3]'));
-       [1,[2,3]]
-      > SELECT _FUNC_(parse_json('{"a": 1}'), '$.missing', 2);
-       {"a":1}
-      > SELECT _FUNC_(parse_json('[1, 2]'), '$', parse_json('null'));
-       [1,2,null]
-      > SELECT _FUNC_(parse_json('[1, 2]'), '$', null);
-       NULL
-  """,
-  since = "4.3.0",
-  group = "variant_funcs"
-)
-// scalastyle:on line.size.limit
-case class VariantArrayAppend(input: Expression, path: Expression, value: 
Expression)
+case class VariantArrayAppend(
+    input: Expression,
+    path: Expression,
+    value: Expression,
+    failOnError: Boolean = true)
     extends TernaryExpression
     with ExpectsInputTypes
     with QueryErrorsBase {
@@ -1235,6 +1206,7 @@ case class VariantArrayAppend(input: Expression, path: 
Expression, value: Expres
   override def third: Expression = value
 
   override def nullIntolerant: Boolean = true
+  override def nullable: Boolean = !failOnError || children.exists(_.nullable)
 
   override def dataType: DataType = VariantType
   override def inputTypes: Seq[AbstractDataType] =
@@ -1279,34 +1251,47 @@ case class VariantArrayAppend(input: Expression, path: 
Expression, value: Expres
     foldablePath match {
       case Some(parsed) =>
         VariantExpressionEvalUtils.arrayAppendAtPath(
-          inputVariant, parsed.javaSegments, parsed.pathStr, valValue, 
value.dataType, prettyName)
+          inputVariant, parsed.javaSegments, parsed.pathStr, valValue, 
value.dataType, prettyName,
+          failOnError)
       case None =>
         VariantExpressionEvalUtils.arrayAppendAtPath(
-          inputVariant, p.asInstanceOf[UTF8String], valValue, value.dataType, 
prettyName)
+          inputVariant, p.asInstanceOf[UTF8String], valValue, value.dataType, 
prettyName,
+          failOnError)
     }
   }
 
   override protected def doGenCode(ctx: CodegenContext, ev: ExprCode): 
ExprCode = {
     val cls = VariantExpressionEvalUtils.getClass.getName.stripSuffix("$")
-    nullSafeCodeGen(ctx, ev, (vVal, pVal, valVal) => {
-      val fromArg = ctx.addReferenceObj("from", value.dataType)
-      foldablePath match {
-        case Some(parsed) =>
-          val parsedArg = ctx.addReferenceObj("appendPath", parsed)
-          s"""
-             |${ev.value} = $cls.arrayAppendAtPath(
-             |  $vVal, $parsedArg.javaSegments(), $parsedArg.pathStr(), 
$valVal, $fromArg,
-             |  "$prettyName");
-           """.stripMargin
-        case None =>
-          s"""
-             |${ev.value} = $cls.arrayAppendAtPath($vVal, $pVal, $valVal, 
$fromArg, "$prettyName");
-           """.stripMargin
-      }
-    })
+    val fromArg = ctx.addReferenceObj("from", value.dataType)
+    def call(vVal: String, pVal: String, valVal: String): String = 
foldablePath match {
+      case Some(parsed) =>
+        val parsedArg = ctx.addReferenceObj("appendPath", parsed)
+        s"""$cls.arrayAppendAtPath(
+           |  $vVal, $parsedArg.javaSegments(), $parsedArg.pathStr(), $valVal, 
$fromArg,
+           |  "$prettyName", $failOnError)""".stripMargin
+      case None =>
+        s"""$cls.arrayAppendAtPath($vVal, $pVal, $valVal, $fromArg, 
"$prettyName", $failOnError)"""
+    }
+    if (failOnError) {
+      nullSafeCodeGen(ctx, ev,
+        (vVal, pVal, valVal) => s"${ev.value} = ${call(vVal, pVal, valVal)};")
+    } else {
+      val resultType = CodeGenerator.javaType(VariantType)
+      val tmp = ctx.freshName("appendResult")
+      nullSafeCodeGen(ctx, ev, (vVal, pVal, valVal) =>
+        s"""
+           |$resultType $tmp = ${call(vVal, pVal, valVal)};
+           |if ($tmp == null) {
+           |  ${ev.isNull} = true;
+           |} else {
+           |  ${ev.value} = $tmp;
+           |}
+         """.stripMargin)
+    }
   }
 
-  override def prettyName: String = "variant_array_append"
+  override def prettyName: String =
+    if (failOnError) "variant_array_append" else "try_variant_array_append"
 
   override protected def withNewChildrenInternal(
       newFirst: Expression, newSecond: Expression, newThird: Expression): 
VariantArrayAppend =
@@ -1323,6 +1308,89 @@ object VariantArrayAppend {
   }
 }
 
+abstract class VariantArrayAppendExpressionBuilderBase(failOnError: Boolean)
+    extends ExpressionBuilder {
+  override def build(funcName: String, expressions: Seq[Expression]): 
Expression = {
+    val numArgs = expressions.length
+    if (numArgs == 3) {
+      VariantArrayAppend(expressions(0), expressions(1), expressions(2), 
failOnError)
+    } else {
+      throw QueryCompilationErrors.wrongNumArgsError(funcName, Seq(3), numArgs)
+    }
+  }
+}
+
+// scalastyle:off line.size.limit
+@ExpressionDescription(
+  usage = "_FUNC_(v, path, val) - Appends a value to the array in a variant at 
the given JSONPath " +
+    "location. Returns the variant unchanged if a path key or index is absent. 
Throws an error " +
+    "if a path segment hits a value of an incompatible type or the target is 
not an array. " +
+    "Returns NULL if any argument is NULL.",
+  arguments = """
+    Arguments:
+      * v - A variant value to mutate.
+      * path - A string expression evaluating to a JSONPath identifying the 
target array. A valid
+          path should start with `$` and is followed by zero or more segments 
like `[123]`, `.name`,
+          `['name']`, or `["name"]`.
+      * val - Any expression castable to variant.
+  """,
+  examples = """
+    Examples:
+      > SELECT _FUNC_(parse_json('[1, 2, 3]'), '$', 4);
+       [1,2,3,4]
+      > SELECT _FUNC_(parse_json('{"a": [1, 2]}'), '$.a', 3);
+       {"a":[1,2,3]}
+      > SELECT _FUNC_(parse_json('[1]'), '$', parse_json('[2, 3]'));
+       [1,[2,3]]
+      > SELECT _FUNC_(parse_json('{"a": 1}'), '$.missing', 2);
+       {"a":1}
+      > SELECT _FUNC_(parse_json('[1, 2]'), '$', parse_json('null'));
+       [1,2,null]
+      > SELECT _FUNC_(parse_json('[1, 2]'), '$', null);
+       NULL
+  """,
+  since = "4.3.0",
+  group = "variant_funcs"
+)
+// scalastyle:on line.size.limit
+object VariantArrayAppendExpressionBuilder extends 
VariantArrayAppendExpressionBuilderBase(true)
+
+// scalastyle:off line.size.limit
+@ExpressionDescription(
+  usage = "_FUNC_(v, path, val) - Appends a value to the array in a variant at 
the given JSONPath " +
+    "location. Returns the variant unchanged if a path key or index is absent. 
Returns NULL if a " +
+    "path segment hits a value of an incompatible type, the target is not an 
array, or if any " +
+    "argument is NULL.",
+  arguments = """
+    Arguments:
+      * v - A variant value to mutate.
+      * path - A string expression evaluating to a JSONPath identifying the 
target array. A valid
+          path should start with `$` and is followed by zero or more segments 
like `[123]`, `.name`,
+          `['name']`, or `["name"]`.
+      * val - Any expression castable to variant.
+  """,
+  examples = """
+    Examples:
+      > SELECT _FUNC_(parse_json('[1, 2, 3]'), '$', 4);
+       [1,2,3,4]
+      > SELECT _FUNC_(parse_json('{"a": [1, 2]}'), '$.a', 3);
+       {"a":[1,2,3]}
+      > SELECT _FUNC_(parse_json('[1]'), '$', parse_json('[2, 3]'));
+       [1,[2,3]]
+      > SELECT _FUNC_(parse_json('{"a": 1}'), '$.missing', 2);
+       {"a":1}
+      > SELECT _FUNC_(parse_json('{"a": 1}'), '$.a', 2);
+       NULL
+      > SELECT _FUNC_(parse_json('[1, 2]'), '$', null);
+       NULL
+  """,
+  since = "4.3.0",
+  group = "variant_funcs"
+)
+// scalastyle:on line.size.limit
+object TryVariantArrayAppendExpressionBuilder
+    extends VariantArrayAppendExpressionBuilderBase(false)
+
 case class VariantExplode(child: Expression) extends UnaryExpression with 
Generator
   with ExpectsInputTypes {
   override def inputTypes: Seq[AbstractDataType] = Seq(VariantType)
diff --git 
a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/variant/VariantExpressionSuite.scala
 
b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/variant/VariantExpressionSuite.scala
index c5488e1f52ff..92f20bcc3127 100644
--- 
a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/variant/VariantExpressionSuite.scala
+++ 
b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/variant/VariantExpressionSuite.scala
@@ -1657,11 +1657,49 @@ class VariantExpressionSuite extends SparkFunSuite with 
ExpressionEvalHelper {
 
   test("variant_array_append") {
     def checkAppend(input: String, path: String, value: Expression, expected: 
String): Unit = {
-      val expr = VariantArrayAppend(
-        Literal(parseJson(input)), Literal.create(path, StringType), value)
+      Seq(true, false).foreach { failOnError =>
+        val expr = VariantArrayAppend(
+          Literal(parseJson(input)), Literal.create(path, StringType), value, 
failOnError)
+        checkEvaluation(
+          ResolveTimeZone.resolveTimeZones(Cast(expr, StringType)),
+          expected)
+      }
+    }
+
+    // A recoverable error: `variant_array_append` throws, but 
`try_variant_array_append` returns
+    // NULL.
+    def checkAppendRecoverableError(
+        input: String,
+        path: String,
+        value: Expression,
+        condition: String,
+        parameters: Map[String, String]): Unit = {
+      checkErrorInExpression[SparkRuntimeException](
+        VariantArrayAppend(Literal(parseJson(input)), Literal.create(path, 
StringType), value),
+        condition,
+        parameters)
       checkEvaluation(
-        ResolveTimeZone.resolveTimeZones(Cast(expr, StringType)),
-        expected)
+        VariantArrayAppend(Literal(parseJson(input)), Literal.create(path, 
StringType), value,
+          failOnError = false),
+        null)
+    }
+
+    // An unrecoverable error (a malformed path or a size overflow): both 
functions throw, and only
+    // the `functionName` in the error message differs.
+    def checkAppendUnrecoverableError(
+        input: String,
+        path: String,
+        value: Expression,
+        condition: String,
+        parameters: String => Map[String, String]): Unit = {
+      Seq("variant_array_append" -> true, "try_variant_array_append" -> 
false).foreach {
+        case (name, failOnError) =>
+          checkErrorInExpression[SparkRuntimeException](
+            VariantArrayAppend(Literal(parseJson(input)), Literal.create(path, 
StringType), value,
+              failOnError),
+            condition,
+            parameters(name))
+      }
     }
 
     // Append to the root array, and to nested arrays reached through object 
keys / array indices.
@@ -1691,46 +1729,45 @@ class VariantExpressionSuite extends SparkFunSuite with 
ExpressionEvalHelper {
     checkAppend("""{"a": [1]}""", "$.missing", Literal(2), """{"a":[1]}""")
     checkAppend("[[1]]", "$[5]", Literal(2), "[[1]]")
 
-    // NULL-intolerant: any NULL argument yields NULL.
-    checkEvaluation(
-      VariantArrayAppend(Literal.create(null, VariantType), Literal("$"), 
Literal(1)),
-      null)
+    Seq(true, false).foreach { failOnError =>
+      checkEvaluation(
+        VariantArrayAppend(
+          Literal.create(null, VariantType), Literal("$"), Literal(1), 
failOnError),
+        null)
+    }
     checkAppend("[1]", null, Literal(1), null)
     checkAppend("[1]", "$", Literal.create(null, VariantType), null)
     checkAppend("[1]", "$", Literal.create(null, NullType), null)
 
-    // Dynamic (non-foldable) path.
-    val dynamic = VariantArrayAppend(
-      Literal(parseJson("""{"a": [1, 2]}""")),
-      BoundReference(0, StringType, nullable = true),
-      Literal(3))
-    checkEvaluation(
-      ResolveTimeZone.resolveTimeZones(Cast(dynamic, StringType)),
-      """{"a":[1,2,3]}""",
-      InternalRow(UTF8String.fromString("$.a")))
+    Seq(true, false).foreach { failOnError =>
+      val dynamic = VariantArrayAppend(
+        Literal(parseJson("""{"a": [1, 2]}""")),
+        BoundReference(0, StringType, nullable = true),
+        Literal(3),
+        failOnError)
+      checkEvaluation(
+        ResolveTimeZone.resolveTimeZones(Cast(dynamic, StringType)),
+        """{"a":[1,2,3]}""",
+        InternalRow(UTF8String.fromString("$.a")))
+    }
 
+    // Recoverable errors: `variant_array_append` throws; 
`try_variant_array_append` returns NULL.
     // The target is not an array (a scalar leaf, or an object at the root).
-    checkErrorInExpression[SparkRuntimeException](
-      VariantArrayAppend(Literal(parseJson("""{"a": 1}""")), Literal("$.a"), 
Literal(2)),
+    checkAppendRecoverableError("""{"a": 1}""", "$.a", Literal(2),
       "VARIANT_PATH_TYPE_MISMATCH",
       Map("path" -> "$.a", "failedAt" -> "$.a", "functionName" -> 
"`variant_array_append`"))
-    checkErrorInExpression[SparkRuntimeException](
-      VariantArrayAppend(Literal(parseJson("""{"a": 1}""")), Literal("$"), 
Literal(2)),
+    checkAppendRecoverableError("""{"a": 1}""", "$", Literal(2),
       "VARIANT_PATH_TYPE_MISMATCH",
       Map("path" -> "$", "failedAt" -> "$", "functionName" -> 
"`variant_array_append`"))
-
     // A segment applied to an incompatible container: descending into a 
scalar, an array index on
     // an object, or an object key on an array.
-    checkErrorInExpression[SparkRuntimeException](
-      VariantArrayAppend(Literal(parseJson("""{"a": 1}""")), Literal("$.a.b"), 
Literal(2)),
+    checkAppendRecoverableError("""{"a": 1}""", "$.a.b", Literal(2),
       "VARIANT_PATH_TYPE_MISMATCH",
       Map("path" -> "$.a.b", "failedAt" -> "$.a", "functionName" -> 
"`variant_array_append`"))
-    checkErrorInExpression[SparkRuntimeException](
-      VariantArrayAppend(Literal(parseJson("""{"a": 1}""")), Literal("$[0]"), 
Literal(2)),
+    checkAppendRecoverableError("""{"a": 1}""", "$[0]", Literal(2),
       "VARIANT_PATH_TYPE_MISMATCH",
       Map("path" -> "$[0]", "failedAt" -> "$", "functionName" -> 
"`variant_array_append`"))
-    checkErrorInExpression[SparkRuntimeException](
-      VariantArrayAppend(Literal(parseJson("[1, 2]")), Literal("$.a"), 
Literal(2)),
+    checkAppendRecoverableError("[1, 2]", "$.a", Literal(2),
       "VARIANT_PATH_TYPE_MISMATCH",
       Map("path" -> "$.a", "failedAt" -> "$", "functionName" -> 
"`variant_array_append`"))
 
@@ -1739,26 +1776,25 @@ class VariantExpressionSuite extends SparkFunSuite with 
ExpressionEvalHelper {
       Literal.create(null, MapType(StringType, IntegerType)),
       Literal.create(null, StructType(Seq(StructField("x", IntegerType))))
     ).foreach { v =>
-      assert(
-        VariantArrayAppend(Literal(parseJson("[]")), Literal("$"), 
v).checkInputDataTypes()
-          .isFailure)
+      Seq(true, false).foreach { failOnError =>
+        assert(
+          VariantArrayAppend(Literal(parseJson("[]")), Literal("$"), v, 
failOnError)
+            .checkInputDataTypes().isFailure)
+      }
     }
 
-    // The root `$` is a valid target here, but a malformed path is still 
rejected.
-    checkErrorInExpression[SparkRuntimeException](
-      VariantArrayAppend(Literal(parseJson("[]")), Literal("abc"), Literal(1)),
+    // Unrecoverable errors: both functions throw. The root `$` is a valid 
target, but a malformed
+    // path is still rejected, and a size overflow surfaces as 
VARIANT_SIZE_LIMIT.
+    checkAppendUnrecoverableError("[]", "abc", Literal(1),
       "INVALID_VARIANT_PATH",
-      Map("path" -> "abc", "functionName" -> "`variant_array_append`"))
+      name => Map("path" -> "abc", "functionName" -> s"`$name`"))
     checkErrorInExpression[SparkRuntimeException](
       VariantArrayAppend(Literal(parseJson("[]")), Literal(""), Literal(1)),
       "INVALID_VARIANT_PATH",
       Map("path" -> "", "functionName" -> "`variant_array_append`"))
-
-    // Appending a value that overflows the variant size limit surfaces as 
VARIANT_SIZE_LIMIT.
     val tooBig = "x".repeat(16 * 1024 * 1024)
-    checkErrorInExpression[SparkRuntimeException](
-      VariantArrayAppend(Literal(parseJson("[]")), Literal("$"), 
Literal(tooBig)),
+    checkAppendUnrecoverableError("[]", "$", Literal(tooBig),
       "VARIANT_SIZE_LIMIT",
-      Map("sizeLimit" -> "16.0 MiB", "functionName" -> 
"`variant_array_append`"))
+      name => Map("sizeLimit" -> "16.0 MiB", "functionName" -> s"`$name`"))
   }
 }
diff --git 
a/sql/connect/client/jvm/src/test/scala/org/apache/spark/sql/PlanGenerationTestSuite.scala
 
b/sql/connect/client/jvm/src/test/scala/org/apache/spark/sql/PlanGenerationTestSuite.scala
index 77ec3eacc510..068460293f15 100644
--- 
a/sql/connect/client/jvm/src/test/scala/org/apache/spark/sql/PlanGenerationTestSuite.scala
+++ 
b/sql/connect/client/jvm/src/test/scala/org/apache/spark/sql/PlanGenerationTestSuite.scala
@@ -2783,6 +2783,10 @@ class PlanGenerationTestSuite extends ConnectFunSuite 
with Logging {
     fn.variant_array_append(fn.parse_json(fn.col("g")), "$.a", fn.lit(1))
   }
 
+  functionTest("try_variant_array_append") {
+    fn.try_variant_array_append(fn.parse_json(fn.col("g")), "$.a", fn.lit(1))
+  }
+
   functionTest("variant_get") {
     fn.variant_get(fn.parse_json(fn.col("g")), "$", "int")
   }
diff --git 
a/sql/connect/common/src/test/resources/query-tests/explain-results/function_try_variant_array_append.explain
 
b/sql/connect/common/src/test/resources/query-tests/explain-results/function_try_variant_array_append.explain
new file mode 100644
index 000000000000..0905c744ce77
--- /dev/null
+++ 
b/sql/connect/common/src/test/resources/query-tests/explain-results/function_try_variant_array_append.explain
@@ -0,0 +1,2 @@
+Project 
[try_variant_array_append(static_invoke(VariantExpressionEvalUtils.parseJson(g#0,
 false, true, true)), $.a, 1, false) AS try_variant_array_append(parse_json(g), 
$.a, 1)#0]
++- LocalRelation <empty>, [id#0L, a#0, b#0, d#0, e#0, f#0, g#0]
diff --git 
a/sql/connect/common/src/test/resources/query-tests/explain-results/function_variant_array_append.explain
 
b/sql/connect/common/src/test/resources/query-tests/explain-results/function_variant_array_append.explain
index 4ebc4a11af67..4fcec34c6c2d 100644
--- 
a/sql/connect/common/src/test/resources/query-tests/explain-results/function_variant_array_append.explain
+++ 
b/sql/connect/common/src/test/resources/query-tests/explain-results/function_variant_array_append.explain
@@ -1,2 +1,2 @@
-Project 
[variant_array_append(static_invoke(VariantExpressionEvalUtils.parseJson(g#0, 
false, true, true)), $.a, 1) AS variant_array_append(parse_json(g), $.a, 1)#0]
+Project 
[variant_array_append(static_invoke(VariantExpressionEvalUtils.parseJson(g#0, 
false, true, true)), $.a, 1, true) AS variant_array_append(parse_json(g), $.a, 
1)#0]
 +- LocalRelation <empty>, [id#0L, a#0, b#0, d#0, e#0, f#0, g#0]
diff --git 
a/sql/connect/common/src/test/resources/query-tests/queries/function_try_variant_array_append.json
 
b/sql/connect/common/src/test/resources/query-tests/queries/function_try_variant_array_append.json
new file mode 100644
index 000000000000..225fe01bb676
--- /dev/null
+++ 
b/sql/connect/common/src/test/resources/query-tests/queries/function_try_variant_array_append.json
@@ -0,0 +1,125 @@
+{
+  "common": {
+    "planId": "1"
+  },
+  "project": {
+    "input": {
+      "common": {
+        "planId": "0"
+      },
+      "localRelation": {
+        "schema": 
"struct\u003cid:bigint,a:int,b:double,d:struct\u003cid:bigint,a:int,b:double\u003e,e:array\u003cint\u003e,f:map\u003cstring,struct\u003cid:bigint,a:int,b:double\u003e\u003e,g:string\u003e"
+      }
+    },
+    "expressions": [{
+      "unresolvedFunction": {
+        "functionName": "try_variant_array_append",
+        "arguments": [{
+          "unresolvedFunction": {
+            "functionName": "parse_json",
+            "arguments": [{
+              "unresolvedAttribute": {
+                "unparsedIdentifier": "g"
+              },
+              "common": {
+                "origin": {
+                  "jvmOrigin": {
+                    "stackTrace": [{
+                      "classLoaderName": "app",
+                      "declaringClass": "org.apache.spark.sql.functions$",
+                      "methodName": "col",
+                      "fileName": "functions.scala"
+                    }, {
+                      "classLoaderName": "app",
+                      "declaringClass": 
"org.apache.spark.sql.PlanGenerationTestSuite",
+                      "methodName": "~~trimmed~anonfun~~",
+                      "fileName": "PlanGenerationTestSuite.scala"
+                    }]
+                  }
+                }
+              }
+            }],
+            "isInternal": false
+          },
+          "common": {
+            "origin": {
+              "jvmOrigin": {
+                "stackTrace": [{
+                  "classLoaderName": "app",
+                  "declaringClass": "org.apache.spark.sql.functions$",
+                  "methodName": "parse_json",
+                  "fileName": "functions.scala"
+                }, {
+                  "classLoaderName": "app",
+                  "declaringClass": 
"org.apache.spark.sql.PlanGenerationTestSuite",
+                  "methodName": "~~trimmed~anonfun~~",
+                  "fileName": "PlanGenerationTestSuite.scala"
+                }]
+              }
+            }
+          }
+        }, {
+          "literal": {
+            "string": "$.a"
+          },
+          "common": {
+            "origin": {
+              "jvmOrigin": {
+                "stackTrace": [{
+                  "classLoaderName": "app",
+                  "declaringClass": "org.apache.spark.sql.functions$",
+                  "methodName": "try_variant_array_append",
+                  "fileName": "functions.scala"
+                }, {
+                  "classLoaderName": "app",
+                  "declaringClass": 
"org.apache.spark.sql.PlanGenerationTestSuite",
+                  "methodName": "~~trimmed~anonfun~~",
+                  "fileName": "PlanGenerationTestSuite.scala"
+                }]
+              }
+            }
+          }
+        }, {
+          "literal": {
+            "integer": 1
+          },
+          "common": {
+            "origin": {
+              "jvmOrigin": {
+                "stackTrace": [{
+                  "classLoaderName": "app",
+                  "declaringClass": "org.apache.spark.sql.functions$",
+                  "methodName": "lit",
+                  "fileName": "functions.scala"
+                }, {
+                  "classLoaderName": "app",
+                  "declaringClass": 
"org.apache.spark.sql.PlanGenerationTestSuite",
+                  "methodName": "~~trimmed~anonfun~~",
+                  "fileName": "PlanGenerationTestSuite.scala"
+                }]
+              }
+            }
+          }
+        }],
+        "isInternal": false
+      },
+      "common": {
+        "origin": {
+          "jvmOrigin": {
+            "stackTrace": [{
+              "classLoaderName": "app",
+              "declaringClass": "org.apache.spark.sql.functions$",
+              "methodName": "try_variant_array_append",
+              "fileName": "functions.scala"
+            }, {
+              "classLoaderName": "app",
+              "declaringClass": "org.apache.spark.sql.PlanGenerationTestSuite",
+              "methodName": "~~trimmed~anonfun~~",
+              "fileName": "PlanGenerationTestSuite.scala"
+            }]
+          }
+        }
+      }
+    }]
+  }
+}
\ No newline at end of file
diff --git 
a/sql/connect/common/src/test/resources/query-tests/queries/function_try_variant_array_append.proto.bin
 
b/sql/connect/common/src/test/resources/query-tests/queries/function_try_variant_array_append.proto.bin
new file mode 100644
index 000000000000..3124014ef2a2
Binary files /dev/null and 
b/sql/connect/common/src/test/resources/query-tests/queries/function_try_variant_array_append.proto.bin
 differ
diff --git a/sql/core/src/test/resources/sql-functions/sql-expression-schema.md 
b/sql/core/src/test/resources/sql-functions/sql-expression-schema.md
index 481c17e12486..4ed20ba4aa93 100644
--- a/sql/core/src/test/resources/sql-functions/sql-expression-schema.md
+++ b/sql/core/src/test/resources/sql-functions/sql-expression-schema.md
@@ -554,9 +554,10 @@
 | org.apache.spark.sql.catalyst.expressions.variant.SchemaOfVariantAgg | 
schema_of_variant_agg | SELECT schema_of_variant_agg(parse_json(j)) FROM VALUES 
('1'), ('2'), ('3') AS tab(j) | 
struct<schema_of_variant_agg(parse_json(j)):string> |
 | org.apache.spark.sql.catalyst.expressions.variant.ToVariantObject | 
to_variant_object | SELECT to_variant_object(named_struct('a', 1, 'b', 2)) | 
struct<to_variant_object(named_struct(a, 1, b, 2)):variant> |
 | 
org.apache.spark.sql.catalyst.expressions.variant.TryParseJsonExpressionBuilder 
| try_parse_json | SELECT try_parse_json('{"a":1,"b":0.8}') | 
struct<try_parse_json({"a":1,"b":0.8}):variant> |
+| 
org.apache.spark.sql.catalyst.expressions.variant.TryVariantArrayAppendExpressionBuilder
 | try_variant_array_append | SELECT try_variant_array_append(parse_json('[1, 
2, 3]'), '$', 4) | struct<try_variant_array_append(parse_json([1, 2, 3]), $, 
4):variant> |
 | 
org.apache.spark.sql.catalyst.expressions.variant.TryVariantGetExpressionBuilder
 | try_variant_get | SELECT try_variant_get(parse_json('{"a": 1}'), '$.a', 
'int') | struct<try_variant_get(parse_json({"a": 1}), $.a):int> |
 | 
org.apache.spark.sql.catalyst.expressions.variant.TryVariantInsertExpressionBuilder
 | try_variant_insert | SELECT try_variant_insert(parse_json('{"a": 1}'), 
'$.b', 2) | struct<try_variant_insert(parse_json({"a": 1}), $.b, 2):variant> |
-| org.apache.spark.sql.catalyst.expressions.variant.VariantArrayAppend | 
variant_array_append | SELECT variant_array_append(parse_json('[1, 2, 3]'), 
'$', 4) | struct<variant_array_append(parse_json([1, 2, 3]), $, 4):variant> |
+| 
org.apache.spark.sql.catalyst.expressions.variant.VariantArrayAppendExpressionBuilder
 | variant_array_append | SELECT variant_array_append(parse_json('[1, 2, 3]'), 
'$', 4) | struct<variant_array_append(parse_json([1, 2, 3]), $, 4):variant> |
 | org.apache.spark.sql.catalyst.expressions.variant.VariantDelete | 
variant_delete | SELECT variant_delete(parse_json('{"a": 1, "b": 2, "c": 3, 
"items": [1, 2, 3]}'), NULL, '$.a', '$.c') | 
struct<variant_delete(parse_json({"a": 1, "b": 2, "c": 3, "items": [1, 2, 3]}), 
NULL, $.a, $.c):variant> |
 | 
org.apache.spark.sql.catalyst.expressions.variant.VariantGetExpressionBuilder | 
variant_get | SELECT variant_get(parse_json('{"a": 1}'), '$.a', 'int') | 
struct<variant_get(parse_json({"a": 1}), $.a):int> |
 | 
org.apache.spark.sql.catalyst.expressions.variant.VariantInsertExpressionBuilder
 | variant_insert | SELECT variant_insert(parse_json('{"a": 1}'), '$.b', 2) | 
struct<variant_insert(parse_json({"a": 1}), $.b, 2):variant> |
diff --git a/sql/core/src/test/scala/org/apache/spark/sql/VariantSuite.scala 
b/sql/core/src/test/scala/org/apache/spark/sql/VariantSuite.scala
index 02f56c6d0892..fe4dde44ec99 100644
--- a/sql/core/src/test/scala/org/apache/spark/sql/VariantSuite.scala
+++ b/sql/core/src/test/scala/org/apache/spark/sql/VariantSuite.scala
@@ -581,6 +581,56 @@ class VariantSuite extends SharedSparkSession with 
ExpressionEvalHelper {
     }
   }
 
+  test("try_variant_array_append with literal arguments") {
+    def rows(results: Any*): Seq[Row] = results.map(Row(_))
+
+    checkAnswer(
+      sql("SELECT to_json(try_variant_array_append(parse_json('{\"a\": [1, 
2]}'), '$.a', 3))"),
+      rows("""{"a":[1,2,3]}"""))
+    checkAnswer(
+      sql("SELECT to_json(try_variant_array_append(parse_json('[1, 2]'), '$', 
3))"),
+      rows("[1,2,3]"))
+
+    checkAnswer(
+      sql("SELECT to_json(try_variant_array_append(parse_json('{\"a\": 1}'), 
'$.a', 2))"),
+      rows(null))
+
+    checkAnswer(
+      sql("SELECT to_json(try_variant_array_append(parse_json('[1]'), '$', 
NULL))"),
+      rows(null))
+
+    checkError(
+      exception = intercept[SparkRuntimeException] {
+        sql("SELECT try_variant_array_append(parse_json('[]'), 'bad', 
1)").collect()
+      },
+      condition = "INVALID_VARIANT_PATH",
+      parameters = Map("path" -> "bad", "functionName" -> 
toSQLId("try_variant_array_append")))
+  }
+
+  test("try_variant_array_append with dynamic arguments") {
+    def rows(results: Any*): Seq[Row] = results.map(Row(_))
+    Seq("CODEGEN_ONLY", "NO_CODEGEN").foreach { codegenMode =>
+      withSQLConf(SQLConf.CODEGEN_FACTORY_MODE.key -> codegenMode) {
+        val df = Seq(
+          ("""{"a": [1, 2]}""", "$.a", 3),
+          ("""{"a": 1}""", "$.a", 9),
+          (null, "$", 2)
+        ).toDF("json", "path", "val")
+        val v = parse_json(col("json"))
+
+        checkAnswer(
+          df.select(to_json(try_variant_array_append(v, col("path"), 
col("val"))).alias("r")),
+          rows("""{"a":[1,2,3]}""", null, null))
+
+        val arrDf = Seq(("[1, 2]", 3), (null, 3)).toDF("json", "val")
+        val arrV = parse_json(arrDf("json"))
+        checkAnswer(
+          arrDf.select(to_json(try_variant_array_append(arrV, "$", 
col("val"))).alias("r")),
+          rows("[1,2,3]", null))
+      }
+    }
+  }
+
   test("round trip tests") {
     withSQLConf(SQLConf.VARIANT_INFER_SHREDDING_SCHEMA.key -> "false") {
       val rand = new Random(42)


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]


Reply via email to