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 aec0ce70 feat(datafusion): support binary lengths, slices and 
split_index (#1311)
aec0ce70 is described below

commit aec0ce7090b800aa1a432546b44db60fa62711cd
Author: Jingsong Lee <[email protected]>
AuthorDate: Mon Nov 2 22:42:03 2026 +0800

    feat(datafusion): support binary lengths, slices and split_index (#1311)
---
 crates/integrations/datafusion/README.md           |   3 +
 .../integrations/datafusion/src/scalar_compat.rs   |  36 ++++-
 .../integrations/datafusion/src/spark_functions.rs | 121 ++++++++++++++--
 crates/integrations/datafusion/src/sql_context.rs  |   4 +-
 .../datafusion/tests/binary_split_compat.rs        | 161 +++++++++++++++++++++
 docs/src/sql.md                                    |  16 ++
 6 files changed, 325 insertions(+), 16 deletions(-)

diff --git a/crates/integrations/datafusion/README.md 
b/crates/integrations/datafusion/README.md
index f3efefc4..20e53b13 100644
--- a/crates/integrations/datafusion/README.md
+++ b/crates/integrations/datafusion/README.md
@@ -32,6 +32,9 @@ functions with the same name; application registrations made 
afterward take
 priority. Paimon-specific Variant functions, metadata SQL and compatibility
 extensions remain available.
 
+Additional adapters cover binary length and slicing. The separate `split_index`
+extension follows Flink's zero-based contract.
+
 The [SQL guide](../../../docs/src/sql.md#spark-compatible-functions) describes
 the supported subset and migration differences, including legacy `size(NULL)`
 behavior, ANSI remainder handling and date-difference result types. This 
package
diff --git a/crates/integrations/datafusion/src/scalar_compat.rs 
b/crates/integrations/datafusion/src/scalar_compat.rs
index fa663102..68e9bce6 100644
--- a/crates/integrations/datafusion/src/scalar_compat.rs
+++ b/crates/integrations/datafusion/src/scalar_compat.rs
@@ -32,6 +32,7 @@ use std::sync::Arc;
 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
 enum Kind {
     Split,
+    SplitIndex,
     Locate,
     Typeof,
 }
@@ -41,9 +42,14 @@ struct Function {
     signature: Signature,
 }
 pub(crate) fn register(ctx: &SessionContext) {
-    for kind in [Kind::Split, Kind::Locate, Kind::Typeof] {
+    for kind in [Kind::Split, Kind::SplitIndex, Kind::Locate, Kind::Typeof] {
         let signature = if kind == Kind::Typeof {
             Signature::any(1, Volatility::Immutable)
+        } else if kind == Kind::SplitIndex {
+            Signature::exact(
+                vec![DataType::Utf8, DataType::Utf8, DataType::Int64],
+                Volatility::Immutable,
+            )
         } else {
             Signature::one_of(
                 vec![
@@ -69,6 +75,7 @@ impl ScalarUDFImpl for Function {
     fn name(&self) -> &str {
         match self.kind {
             Kind::Split => "split",
+            Kind::SplitIndex => "split_index",
             Kind::Locate => "locate",
             Kind::Typeof => "typeof",
         }
@@ -80,7 +87,7 @@ impl ScalarUDFImpl for Function {
         Ok(match self.kind {
             Kind::Split => DataType::List(Arc::new(Field::new("item", 
DataType::Utf8, true))),
             Kind::Locate => DataType::Int32,
-            Kind::Typeof => DataType::Utf8,
+            Kind::Typeof | Kind::SplitIndex => DataType::Utf8,
         })
     }
     fn invoke_with_args(&self, args: ScalarFunctionArgs) -> 
Result<ColumnarValue> {
@@ -91,6 +98,26 @@ impl ScalarUDFImpl for Function {
         }
         let arrays = ColumnarValue::values_to_arrays(&args.args)?;
         let output: ArrayRef = match self.kind {
+            Kind::SplitIndex => {
+                let text = 
arrays[0].as_any().downcast_ref::<StringArray>().unwrap();
+                let separators = 
arrays[1].as_any().downcast_ref::<StringArray>().unwrap();
+                let indexes = 
arrays[2].as_any().downcast_ref::<Int64Array>().unwrap();
+                let output = (0..text.len())
+                    .map(|i| {
+                        if arrays.iter().any(|a| a.is_null(i)) || 
text.value(i).is_empty() {
+                            return None;
+                        }
+                        let index = usize::try_from(indexes.value(i)).ok()?;
+                        let separator = separators.value(i);
+                        if separator.is_empty() {
+                            text.value(i).split(java_whitespace).nth(index)
+                        } else {
+                            text.value(i).split(separator).nth(index)
+                        }
+                    })
+                    .collect::<StringArray>();
+                Arc::new(output)
+            }
             Kind::Split => {
                 let text = 
arrays[0].as_any().downcast_ref::<StringArray>().unwrap();
                 let patterns = 
arrays[1].as_any().downcast_ref::<StringArray>().unwrap();
@@ -198,6 +225,11 @@ impl ScalarUDFImpl for Function {
         }
     }
 }
+// StringUtils uses Java Character.isWhitespace when the whole separator is 
empty.
+fn java_whitespace(ch: char) -> bool {
+    matches!(ch, '\u{0009}'..='\u{000d}' | '\u{001c}'..='\u{0020}' | 
'\u{1680}' |
+        '\u{2000}'..='\u{2006}' | '\u{2008}'..='\u{200a}' | '\u{2028}' | 
'\u{2029}' | '\u{205f}' | '\u{3000}')
+}
 fn sql_type(ty: &DataType) -> String {
     if decoded_type(ty) == &paimon::arrow::variant_arrow_type() {
         return "variant".into();
diff --git a/crates/integrations/datafusion/src/spark_functions.rs 
b/crates/integrations/datafusion/src/spark_functions.rs
index a553a381..317d695b 100644
--- a/crates/integrations/datafusion/src/spark_functions.rs
+++ b/crates/integrations/datafusion/src/spark_functions.rs
@@ -15,8 +15,9 @@
 // specific language governing permissions and limitations
 // under the License.
 
-use datafusion::arrow::array::{new_empty_array, ArrayRef, BooleanArray};
-use datafusion::arrow::compute::filter;
+use datafusion::arrow::array::{new_empty_array, Array, ArrayRef, BooleanArray, 
Int32Array};
+use datafusion::arrow::compute::kernels::length::length;
+use datafusion::arrow::compute::{cast, filter};
 use datafusion::arrow::datatypes::{DataType, Field, FieldRef, TimeUnit};
 use datafusion::common::config::ConfigOptions;
 use datafusion::common::utils::SingleRowListArrayBuilder;
@@ -33,9 +34,15 @@ use datafusion::logical_expr::{
 use datafusion::prelude::SessionContext;
 use std::sync::Arc;
 
-// Adapt input and return types while retaining upstream evaluation and 
simplification.
+// Adapt input and return types while retaining upstream behavior.
 pub(crate) fn apply_compatibility_fixes(ctx: &SessionContext) {
     ctx.register_udf(date_part().as_ref().clone());
+    for bits in [false, true] {
+        ctx.register_udf(ScalarUDF::from(ByteLength {
+            bits,
+            signature: 
Signature::user_defined(datafusion::logical_expr::Volatility::Immutable),
+        }));
+    }
     for name in [
         "base64",
         "sha2",
@@ -48,6 +55,8 @@ pub(crate) fn apply_compatibility_fixes(ctx: &SessionContext) 
{
         "unhex",
         "hour",
         "size",
+        "length",
+        "substring",
     ] {
         let inner = Arc::clone(&ctx.state().scalar_functions()[name]);
         ctx.register_udf(ScalarUDF::from(Inputs::new(inner)));
@@ -65,14 +74,95 @@ fn date_part() -> Arc<ScalarUDF> {
 }
 
 #[derive(Debug)]
-pub(crate) struct DatePartPlanner;
+pub(crate) struct FunctionPlanner;
 
-impl ExprPlanner for DatePartPlanner {
+impl ExprPlanner for FunctionPlanner {
     fn plan_extract(&self, args: Vec<Expr>) -> 
Result<PlannerResult<Vec<Expr>>> {
         Ok(PlannerResult::Planned(Expr::ScalarFunction(
             ScalarFunction::new_udf(date_part(), args),
         )))
     }
+    fn plan_substring(&self, args: Vec<Expr>) -> 
Result<PlannerResult<Vec<Expr>>> {
+        Ok(PlannerResult::Planned(Expr::ScalarFunction(
+            ScalarFunction::new_udf(
+                Arc::new(ScalarUDF::from(Inputs::new(
+                    datafusion_spark::function::string::substring(),
+                ))),
+                args,
+            ),
+        )))
+    }
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+struct ByteLength {
+    bits: bool,
+    signature: Signature,
+}
+
+impl ScalarUDFImpl for ByteLength {
+    fn name(&self) -> &str {
+        if self.bits {
+            "bit_length"
+        } else {
+            "octet_length"
+        }
+    }
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+    fn coerce_types(&self, types: &[DataType]) -> Result<Vec<DataType>> {
+        let [ty] = types else {
+            return Err(DataFusionError::Plan(format!(
+                "{} expects one argument",
+                self.name()
+            )));
+        };
+        Ok(vec![match decoded(ty) {
+            DataType::Null => DataType::Utf8,
+            DataType::FixedSizeBinary(_) => DataType::Binary,
+            ty if ty.is_binary()
+                || matches!(
+                    ty,
+                    DataType::Utf8 | DataType::LargeUtf8 | DataType::Utf8View
+                ) =>
+            {
+                ty.clone()
+            }
+            ty => {
+                return Err(DataFusionError::Plan(format!(
+                    "{} requires string or binary, got {ty}",
+                    self.name()
+                )))
+            }
+        }])
+    }
+    fn return_type(&self, _: &[DataType]) -> Result<DataType> {
+        Ok(DataType::Int32)
+    }
+    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> 
Result<ColumnarValue> {
+        let arrays = ColumnarValue::values_to_arrays(&args.args)?;
+        let lengths = cast(&length(arrays[0].as_ref())?, &DataType::Int32)?;
+        let output: ArrayRef = if self.bits {
+            let lengths = 
lengths.as_any().downcast_ref::<Int32Array>().unwrap();
+            Arc::new(
+                lengths
+                    .iter()
+                    .map(|v| v.map(|n| n.wrapping_mul(8)))
+                    .collect::<Int32Array>(),
+            )
+        } else {
+            lengths
+        };
+        if matches!(args.args[0], ColumnarValue::Scalar(_)) {
+            Ok(ColumnarValue::Scalar(ScalarValue::try_from_array(
+                output.as_ref(),
+                0,
+            )?))
+        } else {
+            Ok(ColumnarValue::Array(output))
+        }
+    }
 }
 
 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
@@ -262,17 +352,19 @@ struct Inputs {
 }
 impl Inputs {
     fn new(inner: Arc<ScalarUDF>) -> Self {
-        Self {
-            signature: Signature::user_defined(inner.signature().volatility),
-            inner,
-        }
+        let mut signature = 
Signature::user_defined(inner.signature().volatility);
+        signature.parameter_names = inner.signature().parameter_names.clone();
+        Self { signature, inner }
     }
 }
 fn decoded(mut ty: &DataType) -> &DataType {
-    while let DataType::Dictionary(_, value) = ty {
-        ty = value;
+    loop {
+        ty = match ty {
+            DataType::Dictionary(_, value) => value,
+            DataType::RunEndEncoded(_, value) => value.data_type(),
+            _ => return ty,
+        };
     }
-    ty
 }
 impl ScalarUDFImpl for Inputs {
     fn name(&self) -> &str {
@@ -290,6 +382,11 @@ impl ScalarUDFImpl for Inputs {
             .map(|ty| decoded(ty).clone())
             .collect::<Vec<_>>();
         match (self.name(), types.as_mut_slice()) {
+            ("length" | "substring", [value, ..])
+                if matches!(value, DataType::FixedSizeBinary(_)) =>
+            {
+                *value = DataType::Binary;
+            }
             ("hex", [value]) if *value == DataType::BinaryView => *value = 
DataType::Binary,
             ("sha2", [value, _]) if matches!(value, 
DataType::FixedSizeBinary(_)) => {
                 *value = DataType::Binary;
diff --git a/crates/integrations/datafusion/src/sql_context.rs 
b/crates/integrations/datafusion/src/sql_context.rs
index e73947bf..0adf576e 100644
--- a/crates/integrations/datafusion/src/sql_context.rs
+++ b/crates/integrations/datafusion/src/sql_context.rs
@@ -171,11 +171,11 @@ impl SQLContextBuilder {
         if let Some(runtime_env) = self.runtime_env {
             state_builder = state_builder.with_runtime_env(runtime_env);
         }
-        // EXTRACT bypasses the function registry, so intercept it before 
Spark's planner.
+        // EXTRACT and SUBSTRING bypass the registry; apply the same adapters 
to their syntax.
         state_builder
             .expr_planners()
             .get_or_insert_with(Vec::new)
-            .insert(0, Arc::new(crate::spark_functions::DatePartPlanner));
+            .insert(0, Arc::new(crate::spark_functions::FunctionPlanner));
         let state = state_builder.build();
         let mut ctx = SessionContext::new_with_state(state);
         crate::spark_functions::apply_compatibility_fixes(&ctx);
diff --git a/crates/integrations/datafusion/tests/binary_split_compat.rs 
b/crates/integrations/datafusion/tests/binary_split_compat.rs
new file mode 100644
index 00000000..468e5d0c
--- /dev/null
+++ b/crates/integrations/datafusion/tests/binary_split_compat.rs
@@ -0,0 +1,161 @@
+// 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 datafusion::common::ScalarValue;
+use paimon_datafusion::SQLContext;
+
+async fn check(ctx: &SQLContext, sql: &str, expected: &[&str]) {
+    let batches = ctx
+        .sql(sql)
+        .await
+        .unwrap_or_else(|e| panic!("{sql}: {e}"))
+        .collect()
+        .await
+        .unwrap_or_else(|e| panic!("{sql}: {e}"));
+    let rows = batches
+        .iter()
+        .flat_map(|batch| {
+            (0..batch.num_rows()).map(|row| {
+                (0..batch.num_columns())
+                    .map(|col| {
+                        ScalarValue::try_from_array(batch.column(col), row)
+                            .unwrap()
+                            .to_string()
+                    })
+                    .collect::<Vec<_>>()
+                    .join("|")
+            })
+        })
+        .collect::<Vec<_>>();
+    assert_eq!(rows, expected, "{sql}");
+}
+
+#[tokio::test]
+async fn binary_lengths_and_slices_preserve_bytes_and_spark_integer_results() {
+    let ctx = SQLContext::new();
+    for ty in ["Binary", "BinaryView", "LargeBinary", "FixedSizeBinary(2)"] {
+        check(&ctx, &format!("SELECT 
octet_length(b),bit_length(b),length(b),hex(substring(b,2,1)),hex(SUBSTRING(b 
FROM 1 FOR 1)),arrow_typeof(octet_length(b)),arrow_typeof(bit_length(b)) FROM 
(SELECT arrow_cast(decode('00ff','hex'),'{ty}') b)"), 
&["2|16|2|FF|00|Int32|Int32"]).await;
+    }
+    check(&ctx, "SELECT 
octet_length('中a'),bit_length('中a'),length('中a'),octet_length(NULL),bit_length(NULL)",
 &["4|32|2|NULL|NULL"]).await;
+    check(&ctx, "SELECT substring(length => 1, str => 'Spark SQL', pos => 
5),substr(pos => 1, length => 2, str => '中ab')", &["k|中a"]).await;
+    for ty in ["Utf8", "Utf8View", "LargeUtf8"] {
+        check(&ctx, &format!("SELECT 
octet_length(arrow_cast('中a','{ty}')),arrow_typeof(octet_length(arrow_cast('中a','{ty}')))"),
 &["4|Int32"]).await;
+    }
+}
+
+#[tokio::test]
+async fn split_index_extends_without_changing_spark_split_part() {
+    let ctx = SQLContext::new();
+    check(&ctx, "SELECT 
split_index('a_b_c','_',0),split_index('a_b_c','_',1),split_index('a_b_c','_',2),split_index('a_b_c','_',3),split_index('a_b_c','_',-1)",
 &["a|b|c|NULL|NULL"]).await;
+    check(&ctx, "SELECT 
split_index('a..b.','.',1),split_index('a..b.','.',3),split_index('中🙂末','🙂',1),split_index('abc','',0),split_index(NULL,'_',1),split_index('a','_',NULL)",
 &["||末|abc|NULL|NULL"]).await;
+    check(
+        &ctx,
+        "SELECT 
split_part('a_b_c','_',1),split_part('a_b_c','_',-1),split_part('a_b_c','_',9)",
+        &["a|c|"],
+    )
+    .await;
+    check(&ctx, "SELECT split_index('',',',0),split_index('a  b 
','',1),split_index('a  b ','',3),split_index('a b','',0)", &["NULL|||a 
b"]).await;
+    check(&ctx, "SELECT split_index(s,d,i) FROM (VALUES 
('a_b','_',1),('a.b','.',0),('x','_',9),(NULL,'_',0),('x',NULL,0),('x','_',NULL))
 t(s,d,i)", &["b","a","NULL","NULL","NULL","NULL"]).await;
+}
+
+#[tokio::test]
+async fn binary_functions_decode_dictionary_value_and_key_nulls() {
+    use datafusion::arrow::array::{
+        Array, ArrayRef, BinaryArray, DictionaryArray, Int8Array, RecordBatch,
+    };
+    use datafusion::arrow::compute::cast;
+    use datafusion::arrow::datatypes::{DataType, Field, Int8Type, Schema};
+    use std::sync::Arc;
+    for ty in [
+        DataType::Binary,
+        DataType::BinaryView,
+        DataType::LargeBinary,
+        DataType::FixedSizeBinary(2),
+    ] {
+        let ctx = SQLContext::new();
+        let bytes: ArrayRef = Arc::new(BinaryArray::from(vec![Some(&[0_u8, 
255][..]), None]));
+        let values = cast(&bytes, &ty).unwrap();
+        let values = DictionaryArray::<Int8Type>::try_new(
+            Int8Array::from(vec![Some(0), Some(1), None]),
+            values,
+        )
+        .unwrap();
+        let schema = Arc::new(Schema::new(vec![Field::new(
+            "b",
+            values.data_type().clone(),
+            true,
+        )]));
+        ctx.ctx()
+            .register_batch(
+                "bytes",
+                RecordBatch::try_new(schema, vec![Arc::new(values)]).unwrap(),
+            )
+            .unwrap();
+        check(
+            &ctx,
+            "SELECT octet_length(b),bit_length(b),len(b),hex(SUBSTRING(b FROM 
2 FOR 1)) FROM bytes",
+            &["2|16|2|FF", "NULL|NULL|NULL|NULL", "NULL|NULL|NULL|NULL"],
+        )
+        .await;
+    }
+}
+
+#[tokio::test]
+async fn byte_lengths_preserve_run_end_encoded_strings_and_slices() {
+    use datafusion::arrow::array::{
+        Array, ArrayRef, Int32Array, RecordBatch, RunArray, StringArray,
+    };
+    use datafusion::arrow::compute::cast;
+    use datafusion::arrow::datatypes::{DataType, Field, Int32Type, Schema};
+    use std::sync::Arc;
+
+    for ty in [DataType::Utf8, DataType::Utf8View, DataType::LargeUtf8] {
+        let ctx = SQLContext::new();
+        let values = cast(&StringArray::from(vec![Some("中a"), None, 
Some("")]), &ty).unwrap();
+        let runs: ArrayRef = Arc::new(
+            RunArray::<Int32Type>::try_new(&Int32Array::from(vec![2, 3, 5]), 
values.as_ref())
+                .unwrap(),
+        );
+        for (name, values, expected) in [
+            (
+                "runs",
+                Arc::clone(&runs),
+                &["4|32", "4|32", "NULL|NULL", "0|0", "0|0"][..],
+            ),
+            (
+                "sliced_runs",
+                runs.slice(1, 3),
+                &["4|32", "NULL|NULL", "0|0"][..],
+            ),
+        ] {
+            let schema = Arc::new(Schema::new(vec![Field::new(
+                "s",
+                values.data_type().clone(),
+                true,
+            )]));
+            ctx.ctx()
+                .register_batch(name, RecordBatch::try_new(schema, 
vec![values]).unwrap())
+                .unwrap();
+            check(
+                &ctx,
+                &format!("SELECT octet_length(s),bit_length(s) FROM {name}"),
+                expected,
+            )
+            .await;
+        }
+    }
+}
diff --git a/docs/src/sql.md b/docs/src/sql.md
index bee22a12..f3216c35 100644
--- a/docs/src/sql.md
+++ b/docs/src/sql.md
@@ -2044,6 +2044,22 @@ aggregates and the additional functions documented below 
remain available.
 This enables the upstream function subset; it does not enable every Spark SQL
 syntax, cast mode or configuration option.
 
+SQLContext also adapts binary inputs for length and substring functions in the
+pinned upstream version. `octet_length` and `bit_length` accept strings and 
binary
+values and return Spark INT results, including for Arrow large-offset
+representations. String byte lengths count UTF-8 bytes; `length` continues to
+count characters for strings. Fixed-size and dictionary binary inputs work with
+length functions and both function-call and SQL `SUBSTRING` syntax without
+decoding bytes as text.
+
+### Split-index extension
+
+`split_index(text, delimiter, index)` provides Flink's zero-based splitting
+contract without changing Spark `split` or one-based `split_part`. The 
delimiter
+is literal and empty pieces are preserved. NULL arguments, an empty input,
+negative indexes and indexes outside the result return NULL. An empty delimiter
+uses Java whitespace as the separator.
+
 ### Aggregate compatibility
 
 SQLContext accepts the following aggregates in queries and view definitions.

Reply via email to