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

JingsongLi pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/paimon-rust.git


The following commit(s) were added to refs/heads/main by this push:
     new ddce4ad5 feat(datafusion): add JSON text extraction and formatting 
functions (#1279)
ddce4ad5 is described below

commit ddce4ad5cdf495a05a4074345c0b3163279f6d3e
Author: Jingsong Lee <[email protected]>
AuthorDate: Sun Nov 1 23:49:20 2026 +0800

    feat(datafusion): add JSON text extraction and formatting functions (#1279)
---
 .../integrations/datafusion/src/json_functions.rs  | 215 +++++++++++++++++++++
 crates/integrations/datafusion/src/lib.rs          |   1 +
 crates/integrations/datafusion/src/sql_context.rs  |   1 +
 .../datafusion/src/variant_functions.rs            |   6 +-
 .../datafusion/tests/json_functions.rs             | 195 +++++++++++++++++++
 docs/src/sql.md                                    |  31 +++
 6 files changed, 447 insertions(+), 2 deletions(-)

diff --git a/crates/integrations/datafusion/src/json_functions.rs 
b/crates/integrations/datafusion/src/json_functions.rs
new file mode 100644
index 00000000..2df7f6fa
--- /dev/null
+++ b/crates/integrations/datafusion/src/json_functions.rs
@@ -0,0 +1,215 @@
+// 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.
+
+use std::sync::Arc;
+
+use datafusion::arrow::array::{
+    Array, ArrayRef, BooleanBuilder, LargeStringArray, StringArray, 
StringBuilder, StringViewArray,
+};
+use datafusion::arrow::datatypes::DataType;
+use datafusion::common::{DataFusionError, Result, ScalarValue};
+use datafusion::logical_expr::{
+    ColumnarValue, ScalarFunctionArgs, ScalarUDF, ScalarUDFImpl, Signature, 
Volatility,
+};
+use datafusion::prelude::SessionContext;
+use paimon::variant::{GenericVariant, VariantKind, VariantRef};
+
+use crate::variant_functions::{variant_arrow_type, variant_children};
+
+pub(crate) fn register_json_functions(ctx: &SessionContext) {
+    for (name, kind, aliases) in [
+        ("json_value", Kind::Scalar, vec!["json_extract_scalar"]),
+        (
+            "get_json_object",
+            Kind::Fragment,
+            vec!["get_json_string", "json_extract_string", "json_get_str"],
+        ),
+        ("json_valid", Kind::Valid, vec![]),
+        ("json_format", Kind::Format, vec![]),
+    ] {
+        let signature = match kind {
+            Kind::Scalar | Kind::Fragment => Signature::string(2, 
Volatility::Immutable),
+            Kind::Valid => Signature::string(1, Volatility::Immutable),
+            Kind::Format => Signature::user_defined(Volatility::Immutable),
+        };
+        ctx.register_udf(
+            ScalarUDF::from(JsonFunction {
+                name,
+                kind,
+                signature,
+            })
+            .with_aliases(aliases),
+        );
+    }
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+enum Kind {
+    Scalar,
+    Fragment,
+    Valid,
+    Format,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+struct JsonFunction {
+    name: &'static str,
+    kind: Kind,
+    signature: Signature,
+}
+
+impl ScalarUDFImpl for JsonFunction {
+    fn name(&self) -> &str {
+        self.name
+    }
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+
+    fn coerce_types(&self, arg_types: &[DataType]) -> Result<Vec<DataType>> {
+        let [input] = arg_types else {
+            return Err(DataFusionError::Plan(
+                "json_format expects one argument".into(),
+            ));
+        };
+        let mut value = input;
+        while let DataType::Dictionary(_, inner) = value {
+            value = inner;
+        }
+        if matches!(
+            value,
+            DataType::Utf8 | DataType::LargeUtf8 | DataType::Utf8View | 
DataType::Null
+        ) {
+            return Ok(vec![value.clone()]);
+        }
+        if input == &variant_arrow_type() {
+            return Ok(vec![input.clone()]);
+        }
+        Err(DataFusionError::Plan(
+            "json_format expects JSON text or a VARIANT".into(),
+        ))
+    }
+
+    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
+        if self.kind == Kind::Format
+            && !matches!(
+                arg_types[0],
+                DataType::Utf8 | DataType::LargeUtf8 | DataType::Utf8View | 
DataType::Null
+            )
+            && arg_types[0] != variant_arrow_type()
+        {
+            return Err(DataFusionError::Plan(
+                "json_format expects JSON text or a VARIANT".into(),
+            ));
+        }
+        Ok(if self.kind == Kind::Valid {
+            DataType::Boolean
+        } else {
+            DataType::Utf8
+        })
+    }
+
+    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> 
Result<ColumnarValue> {
+        let arrays = ColumnarValue::values_to_arrays(&args.args)?;
+        let input = arrays[0].as_ref();
+        let mut strings = StringBuilder::new();
+        let mut booleans = BooleanBuilder::new();
+        let variant = if self.kind == Kind::Format && input.data_type() == 
&variant_arrow_type() {
+            variant_children(input)?
+        } else {
+            None
+        };
+        for row in 0..input.len() {
+            if input.data_type() == &DataType::Null || input.is_null(row) {
+                strings.append_null();
+                booleans.append_null();
+                continue;
+            }
+            if let Some((values, metadata)) = variant {
+                let value = VariantRef::new(values.value(row), 
metadata.value(row), 0)
+                    .and_then(|value| value.to_json())
+                    .map_err(crate::to_datafusion_error)?;
+                strings.append_value(value);
+                continue;
+            }
+            let text = string_at(input, row)?;
+            let parsed = GenericVariant::parse_json(text);
+            if self.kind == Kind::Valid {
+                booleans.append_value(parsed.is_ok());
+                continue;
+            }
+            if self.kind == Kind::Format {
+                let parsed = parsed.map_err(|error| {
+                    DataFusionError::Execution(format!("Invalid JSON: 
{error}"))
+                })?;
+                
strings.append_value(parsed.to_json().map_err(crate::to_datafusion_error)?);
+                continue;
+            }
+            let path = arrays[1].as_ref();
+            let extracted = if path.is_null(row) {
+                None
+            } else {
+                parsed.ok().and_then(|json| {
+                    extract(&json, string_at(path, row).ok()?, self.kind == 
Kind::Scalar)
+                })
+            };
+            strings.append_option(extracted);
+        }
+        let output: ArrayRef = if self.kind == Kind::Valid {
+            Arc::new(booleans.finish())
+        } else {
+            Arc::new(strings.finish())
+        };
+        if args
+            .args
+            .iter()
+            .all(|value| matches!(value, ColumnarValue::Scalar(_)))
+        {
+            Ok(ColumnarValue::Scalar(ScalarValue::try_from_array(
+                &output, 0,
+            )?))
+        } else {
+            Ok(ColumnarValue::Array(output))
+        }
+    }
+}
+
+fn extract(json: &GenericVariant, path: &str, scalar_only: bool) -> 
Option<String> {
+    let value = json.get_path(path).ok()??;
+    match value.kind().ok()? {
+        VariantKind::Null => None,
+        VariantKind::Object | VariantKind::Array if scalar_only => None,
+        VariantKind::String => value.get_string().ok(),
+        _ => value.to_json().ok(),
+    }
+}
+
+fn string_at(array: &dyn Array, row: usize) -> Result<&str> {
+    if let Some(array) = array.as_any().downcast_ref::<StringArray>() {
+        return Ok(array.value(row));
+    }
+    if let Some(array) = array.as_any().downcast_ref::<LargeStringArray>() {
+        return Ok(array.value(row));
+    }
+    if let Some(array) = array.as_any().downcast_ref::<StringViewArray>() {
+        return Ok(array.value(row));
+    }
+    Err(DataFusionError::Execution(format!(
+        "JSON function expected a string, got {}",
+        array.data_type()
+    )))
+}
diff --git a/crates/integrations/datafusion/src/lib.rs 
b/crates/integrations/datafusion/src/lib.rs
index 3ecbc26c..050fb7ce 100644
--- a/crates/integrations/datafusion/src/lib.rs
+++ b/crates/integrations/datafusion/src/lib.rs
@@ -52,6 +52,7 @@ mod full_text_search;
 #[path = "../testdata/warehouse/mod.rs"]
 mod golden_warehouse;
 mod hybrid_search;
+mod json_functions;
 mod lateral_vector_search;
 mod memory;
 mod merge_condition;
diff --git a/crates/integrations/datafusion/src/sql_context.rs 
b/crates/integrations/datafusion/src/sql_context.rs
index d2e4910e..234952ee 100644
--- a/crates/integrations/datafusion/src/sql_context.rs
+++ b/crates/integrations/datafusion/src/sql_context.rs
@@ -170,6 +170,7 @@ impl SQLContextBuilder {
         let ctx = SessionContext::new_with_state(state);
         
crate::blob_descriptor_functions::register_blob_descriptor_functions(&ctx);
         crate::variant_functions::register_variant_functions(&ctx);
+        crate::json_functions::register_json_functions(&ctx);
         SQLContext {
             ctx,
             catalogs: HashMap::new(),
diff --git a/crates/integrations/datafusion/src/variant_functions.rs 
b/crates/integrations/datafusion/src/variant_functions.rs
index bf658fcc..c55f18c2 100644
--- a/crates/integrations/datafusion/src/variant_functions.rs
+++ b/crates/integrations/datafusion/src/variant_functions.rs
@@ -670,7 +670,9 @@ fn string_at(array: &dyn Array, row: usize) -> 
DFResult<Option<String>> {
     }
 }
 
-fn variant_children(array: &dyn Array) -> DFResult<Option<(&BinaryArray, 
&BinaryArray)>> {
+pub(crate) fn variant_children(
+    array: &dyn Array,
+) -> DFResult<Option<(&BinaryArray, &BinaryArray)>> {
     let ArrowDataType::Struct(fields) = array.data_type() else {
         return Ok(None);
     };
@@ -738,7 +740,7 @@ fn variant_array(values: Vec<Option<GenericVariant>>) -> 
DFResult<ArrayRef> {
     Ok(Arc::new(array))
 }
 
-fn variant_arrow_type() -> ArrowDataType {
+pub(crate) fn variant_arrow_type() -> ArrowDataType {
     paimon::arrow::variant_arrow_type()
 }
 
diff --git a/crates/integrations/datafusion/tests/json_functions.rs 
b/crates/integrations/datafusion/tests/json_functions.rs
new file mode 100644
index 00000000..abee65bb
--- /dev/null
+++ b/crates/integrations/datafusion/tests/json_functions.rs
@@ -0,0 +1,195 @@
+// 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.
+
+use std::sync::Arc;
+
+use datafusion::arrow::array::{
+    ArrayRef, LargeStringArray, RecordBatch, StringArray, StringViewArray,
+};
+use datafusion::arrow::datatypes::{DataType, Field, Schema};
+use datafusion::common::ScalarValue;
+use paimon_datafusion::SQLContext;
+
+async fn value(ctx: &SQLContext, sql: &str) -> ScalarValue {
+    let batches = ctx.sql(sql).await.unwrap().collect().await.unwrap();
+    ScalarValue::try_from_array(batches[0].column(0), 0).unwrap()
+}
+
+#[tokio::test]
+async fn json_extraction_distinguishes_scalars_fragments_and_nulls() {
+    let ctx = SQLContext::new();
+    for (expression, expected) in [
+        (
+            "json_value('{\"a\":[1,\"hello\",true,null]}', '$.a[1]')",
+            Some("hello"),
+        ),
+        ("json_extract_scalar('{\"a\":42}', '$.a')", Some("42")),
+        ("json_value('true', '$')", Some("true")),
+        ("json_value('{\"a\":[1]}', '$.a')", None),
+        ("get_json_object('{\"a\":[1,2]}', '$.a')", Some("[1,2]")),
+        ("get_json_string('{\"a\":\"text\"}', '$.a')", Some("text")),
+        ("json_extract_string('{\"a\":false}', '$.a')", Some("false")),
+        ("json_get_str('{\"a\":\"text\"}', '$.a')", Some("text")),
+        ("json_value('{\"a\":null}', '$.a')", None),
+        ("get_json_object('{\"a\":1}', '$.missing')", None),
+        ("json_value('invalid', '$')", None),
+        ("get_json_object('{}', 'not_a_path')", None),
+        ("json_value(NULL, '$')", None),
+        ("get_json_object('{}', NULL)", None),
+        (
+            "json_value('{\"a.b\":[\"你好\"]}', '$[''a.b''][0]')",
+            Some("你好"),
+        ),
+    ] {
+        assert_eq!(
+            value(&ctx, &format!("SELECT {expression}")).await,
+            ScalarValue::Utf8(expected.map(str::to_string)),
+            "{expression}"
+        );
+    }
+}
+
+#[tokio::test]
+async fn json_validation_and_format_preserve_json_types() {
+    let ctx = SQLContext::new();
+    for (input, expected) in [
+        ("'null'", Some(true)),
+        ("'{}'", Some(true)),
+        ("'1 trailing'", Some(false)),
+        ("''", Some(false)),
+        ("NULL", None),
+    ] {
+        assert_eq!(
+            value(&ctx, &format!("SELECT json_valid({input})")).await,
+            ScalarValue::Boolean(expected)
+        );
+    }
+    for (input, expected) in [
+        ("' [1, 2] '", Some("[1,2]")),
+        ("'\"text\"'", Some("\"text\"")),
+        ("'null'", Some("null")),
+        ("parse_json('{\"a\":1}')", Some("{\"a\":1}")),
+        ("parse_json('null')", Some("null")),
+        ("try_parse_json('bad')", None),
+        ("NULL", None),
+    ] {
+        assert_eq!(
+            value(&ctx, &format!("SELECT json_format({input})")).await,
+            ScalarValue::Utf8(expected.map(str::to_string))
+        );
+    }
+    let error = ctx.sql("SELECT json_format('invalid')").await;
+    let message = match error {
+        Err(e) => e.to_string(),
+        Ok(df) => df.collect().await.unwrap_err().to_string(),
+    };
+    assert!(message.contains("Invalid JSON"), "{message}");
+    assert!(ctx.sql("SELECT json_format(42)").await.is_err());
+    assert!(ctx
+        .sql("SELECT json_format(decode('7b7d', 'hex'))")
+        .await
+        .is_err());
+    assert!(ctx.sql("SELECT json_format(named_struct('value', decode('00', 
'hex'), 'metadata', decode('00', 'hex')))").await.is_err());
+}
+
+#[tokio::test]
+async fn json_functions_evaluate_string_arrays_and_dynamic_paths() {
+    let ctx = SQLContext::new();
+    let docs = [
+        Some("{\"a\":1,\"b\":2}"),
+        Some("{\"a\":3,\"b\":4}"),
+        None,
+        Some("bad"),
+    ];
+    for array in [
+        Arc::new(StringArray::from(docs.to_vec())) as ArrayRef,
+        Arc::new(LargeStringArray::from(docs.to_vec())),
+        Arc::new(StringViewArray::from(docs.to_vec())),
+    ] {
+        let schema = Arc::new(Schema::new(vec![
+            Field::new("doc", array.data_type().clone(), true),
+            Field::new("path", DataType::Utf8, true),
+        ]));
+        let paths = Arc::new(StringArray::from(vec!["$.a", "$.b", "$", "$"]));
+        ctx.ctx()
+            .register_batch(
+                "json_inputs",
+                RecordBatch::try_new(schema, vec![array, paths]).unwrap(),
+            )
+            .unwrap();
+        let batches = ctx
+            .sql("SELECT json_value(doc, path), json_valid(doc) FROM 
json_inputs")
+            .await
+            .unwrap()
+            .collect()
+            .await
+            .unwrap();
+        let result = &batches[0];
+        for (row, expected) in [Some("1"), Some("4"), None, 
None].into_iter().enumerate() {
+            assert_eq!(
+                ScalarValue::try_from_array(result.column(0), row).unwrap(),
+                ScalarValue::Utf8(expected.map(str::to_string))
+            );
+        }
+        assert_eq!(
+            ScalarValue::try_from_array(result.column(1), 3).unwrap(),
+            ScalarValue::Boolean(Some(false))
+        );
+        ctx.ctx().deregister_table("json_inputs").unwrap();
+    }
+}
+
+#[tokio::test]
+async fn json_format_accepts_dictionary_encoded_text() {
+    use datafusion::arrow::array::{Array, DictionaryArray, Int8Array};
+    use datafusion::arrow::datatypes::Int8Type;
+    let ctx = SQLContext::new();
+    let array = DictionaryArray::<Int8Type>::try_new(
+        Int8Array::from(vec![Some(0), Some(1), None]),
+        Arc::new(StringArray::from(vec!["{\"a\":1}", "[2,3]"])),
+    )
+    .unwrap();
+    let schema = Arc::new(Schema::new(vec![Field::new(
+        "doc",
+        array.data_type().clone(),
+        true,
+    )]));
+    ctx.ctx()
+        .register_batch(
+            "dictionary_json",
+            RecordBatch::try_new(schema, vec![Arc::new(array)]).unwrap(),
+        )
+        .unwrap();
+    let batches = ctx
+        .sql(
+            "SELECT json_format(doc), json_value(doc, '$.a'), json_valid(doc) 
FROM dictionary_json",
+        )
+        .await
+        .unwrap()
+        .collect()
+        .await
+        .unwrap();
+    for (row, expected) in [Some("{\"a\":1}"), Some("[2,3]"), None]
+        .into_iter()
+        .enumerate()
+    {
+        assert_eq!(
+            ScalarValue::try_from_array(batches[0].column(0), row).unwrap(),
+            ScalarValue::Utf8(expected.map(str::to_string))
+        );
+    }
+}
diff --git a/docs/src/sql.md b/docs/src/sql.md
index 87ce2caa..6e10354a 100644
--- a/docs/src/sql.md
+++ b/docs/src/sql.md
@@ -489,6 +489,37 @@ SELECT
     is_variant_null(NULL) AS sql_null;
 ```
 
+### JSON Text Functions
+
+`SQLContext` registers these functions without requiring a catalog:
+
+| Function | Result |
+| --- | --- |
+| `json_value(text, path)`, `json_extract_scalar(text, path)` | An unquoted 
string, number, or boolean; objects and arrays return `NULL` |
+| `get_json_object(text, path)` | Unquoted strings, scalar text, or serialized 
object/array fragments |
+| `get_json_string`, `json_extract_string`, `json_get_str` | Aliases of 
`get_json_object` with the same two arguments |
+| `json_valid(text)` | Whether text can be parsed as a Paimon JSON Variant |
+| `json_format(text_or_variant)` | Compact JSON serialization, retaining JSON 
string quotes and JSON `null` |
+
+```sql
+SELECT json_value('{"a":[1,"hello"]}', '$.a[1]'); -- hello
+SELECT get_json_object('{"a":[1,2]}', '$.a'); -- [1,2]
+SELECT json_format(parse_json('{"a":1}')); -- {"a":1}
+```
+
+Extraction supports the existing Variant path subset: `$`, `.name`,
+`['name']` / `["name"]`, and zero-based `[index]`. It does not implement
+wildcards, recursive descent, JSONPath predicates, or SQL/JSON `RETURNING`,
+`ON EMPTY`, and `ON ERROR` clauses. Extraction returns SQL `NULL` for invalid
+JSON, invalid/missing paths, JSON null, or SQL null arguments.
+
+The functions use the same parser as `parse_json`, including its rejection of
+duplicate object keys. `json_valid` returns false for rejected text and SQL
+`NULL` for SQL null. `json_format` reports malformed text as an error rather
+than converting it to null. JSON text and the binary Paimon Variant encoding
+are distinct: extraction takes text; `json_format` accepts either 
representation.
+Dictionary-encoded string columns have the same JSON text semantics.
+
 ### Variant Shredding
 
 Variant shredding stores selected fields from a `VARIANT` column as typed

Reply via email to