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 4bece778 feat(datafusion): support binary casts and byte widths (#1288)
4bece778 is described below

commit 4bece7781d75bbaae5a4349f8637dbf16798efa9
Author: Jingsong Lee <[email protected]>
AuthorDate: Mon Nov 2 09:09:49 2026 +0800

    feat(datafusion): support binary casts and byte widths (#1288)
---
 crates/integrations/datafusion/src/binary_cast.rs  | 153 +++++++++++++++++++++
 crates/integrations/datafusion/src/lib.rs          |   1 +
 crates/integrations/datafusion/src/sql_context.rs  |  39 +++++-
 crates/integrations/datafusion/src/sql_function.rs |   1 +
 .../integrations/datafusion/tests/binary_cast.rs   | 132 ++++++++++++++++++
 docs/src/sql.md                                    |  21 +++
 6 files changed, 346 insertions(+), 1 deletion(-)

diff --git a/crates/integrations/datafusion/src/binary_cast.rs 
b/crates/integrations/datafusion/src/binary_cast.rs
new file mode 100644
index 00000000..4fe636fb
--- /dev/null
+++ b/crates/integrations/datafusion/src/binary_cast.rs
@@ -0,0 +1,153 @@
+// 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::arrow::array::{Array, BinaryArray, BinaryBuilder, 
BooleanArray, Int64Array};
+use datafusion::arrow::datatypes::{DataType, Field, FieldRef};
+use datafusion::common::{DataFusionError, Result};
+use datafusion::logical_expr::planner::TypePlanner;
+use datafusion::logical_expr::{
+    ColumnarValue, ScalarFunctionArgs, ScalarUDF, ScalarUDFImpl, Signature, 
Volatility,
+};
+use datafusion::prelude::SessionContext;
+use datafusion::sql::sqlparser::ast::{
+    visit_expressions_mut, BinaryLength, DataType as SqlType, Expr, 
FunctionArg, FunctionArgExpr,
+    FunctionArguments, Statement,
+};
+use datafusion::sql::sqlparser::{dialect::GenericDialect, parser::Parser};
+use std::ops::ControlFlow;
+use std::sync::Arc;
+
+#[derive(Debug)]
+pub(crate) struct BinaryTypePlanner;
+impl TypePlanner for BinaryTypePlanner {
+    fn plan_type_field(&self, sql_type: &SqlType) -> Result<Option<FieldRef>> {
+        if matches!(sql_type, SqlType::Binary(_) | SqlType::Varbinary(_)) {
+            width(sql_type)?;
+            Ok(Some(Arc::new(Field::new("", DataType::Binary, true))))
+        } else {
+            Ok(None)
+        }
+    }
+}
+fn width(sql_type: &SqlType) -> Result<Option<(u64, bool)>> {
+    let value = match sql_type {
+        SqlType::Binary(Some(n)) => Some((*n, true)),
+        SqlType::Varbinary(Some(BinaryLength::IntegerLength { length })) => 
Some((*length, false)),
+        _ => None,
+    };
+    if value.is_some_and(|(n, _)| n == 0 || n > i32::MAX as u64) {
+        return Err(DataFusionError::Plan(
+            "Binary length must be between 1 and 2147483647".into(),
+        ));
+    }
+    Ok(value)
+}
+pub(crate) fn rewrite(statement: &mut Statement) -> Result<bool> {
+    let mut changed = false;
+    let flow = visit_expressions_mut(statement, |node| {
+        let Expr::Cast { data_type, .. } = node else {
+            return ControlFlow::Continue(());
+        };
+        let (n, pad) = match width(data_type) {
+            Ok(Some(pair)) => pair,
+            Ok(None) => return ControlFlow::Continue(()),
+            Err(e) => return ControlFlow::Break(e),
+        };
+        let mut cast = node.clone();
+        if let Expr::Cast { data_type, .. } = &mut cast {
+            *data_type = SqlType::Bytea;
+        }
+        let template = format!("__paimon_binary_width(NULL, {n}, {pad})");
+        let call = Parser::new(&GenericDialect {})
+            .try_with_sql(&template)
+            .and_then(|mut p| p.parse_expr());
+        let mut call = match call {
+            Ok(expr) => expr,
+            Err(e) => return 
ControlFlow::Break(DataFusionError::Plan(e.to_string())),
+        };
+        if let Expr::Function(function) = &mut call {
+            if let FunctionArguments::List(args) = &mut function.args {
+                args.args[0] = 
FunctionArg::Unnamed(FunctionArgExpr::Expr(cast));
+            }
+        }
+        *node = call;
+        changed = true;
+        ControlFlow::Continue(())
+    });
+    match flow {
+        ControlFlow::Break(e) => Err(e),
+        _ => Ok(changed),
+    }
+}
+pub(crate) fn register(ctx: &SessionContext) {
+    ctx.register_udf(ScalarUDF::from(BinaryWidth {
+        signature: Signature::exact(
+            vec![DataType::Binary, DataType::Int64, DataType::Boolean],
+            Volatility::Immutable,
+        ),
+    }));
+}
+#[derive(Debug, PartialEq, Eq, Hash)]
+struct BinaryWidth {
+    signature: Signature,
+}
+impl ScalarUDFImpl for BinaryWidth {
+    fn name(&self) -> &str {
+        "__paimon_binary_width"
+    }
+    fn signature(&self) -> &Signature {
+        &self.signature
+    }
+    fn return_type(&self, _: &[DataType]) -> Result<DataType> {
+        Ok(DataType::Binary)
+    }
+    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> 
Result<ColumnarValue> {
+        let arrays = ColumnarValue::values_to_arrays(&args.args)?;
+        let input = arrays[0].as_any().downcast_ref::<BinaryArray>().unwrap();
+        let lengths = arrays[1].as_any().downcast_ref::<Int64Array>().unwrap();
+        let pads = arrays[2].as_any().downcast_ref::<BooleanArray>().unwrap();
+        let mut output = BinaryBuilder::new();
+        for i in 0..input.len() {
+            if input.is_null(i) || lengths.is_null(i) || pads.is_null(i) {
+                output.append_null();
+                continue;
+            }
+            let n = lengths.value(i);
+            if n <= 0 || n > i32::MAX as i64 {
+                return Err(DataFusionError::Execution("Invalid binary 
length".into()));
+            }
+            let input = input.value(i);
+            let mut value = input[..input.len().min(n as usize)].to_vec();
+            if pads.value(i) {
+                value.resize(n as usize, 0);
+            }
+            output.append_value(value);
+        }
+        let result = Arc::new(output.finish());
+        if args
+            .args
+            .iter()
+            .all(|v| matches!(v, ColumnarValue::Scalar(_)))
+        {
+            Ok(ColumnarValue::Scalar(
+                
datafusion::common::ScalarValue::try_from_array(result.as_ref(), 0)?,
+            ))
+        } else {
+            Ok(ColumnarValue::Array(result))
+        }
+    }
+}
diff --git a/crates/integrations/datafusion/src/lib.rs 
b/crates/integrations/datafusion/src/lib.rs
index 6809f9bd..871208f5 100644
--- a/crates/integrations/datafusion/src/lib.rs
+++ b/crates/integrations/datafusion/src/lib.rs
@@ -36,6 +36,7 @@
 //! This version supports partition predicate pushdown by extracting
 //! translatable partition-only conjuncts from DataFusion filters.
 
+mod binary_cast;
 mod blob_descriptor_functions;
 mod blob_reader;
 mod blob_view;
diff --git a/crates/integrations/datafusion/src/sql_context.rs 
b/crates/integrations/datafusion/src/sql_context.rs
index c36c9f90..8abb50c1 100644
--- a/crates/integrations/datafusion/src/sql_context.rs
+++ b/crates/integrations/datafusion/src/sql_context.rs
@@ -157,6 +157,7 @@ impl SQLContextBuilder {
         let mut state_builder = SessionStateBuilder::new()
             .with_config(crate::lateral_vector_search::session_config())
             .with_default_features()
+            .with_type_planner(Arc::new(crate::binary_cast::BinaryTypePlanner))
             .with_relation_planners(vec![Arc::new(
                 crate::relation_planner::PaimonRelationPlanner::new(),
             )])
@@ -170,6 +171,7 @@ impl SQLContextBuilder {
         let state = state_builder.build();
         let ctx = SessionContext::new_with_state(state);
         crate::compat_functions::register_compat_functions(&ctx);
+        crate::binary_cast::register(&ctx);
         crate::scalar_compat::register(&ctx);
         
crate::blob_descriptor_functions::register_blob_descriptor_functions(&ctx);
         crate::variant_functions::register_variant_functions(&ctx);
@@ -481,7 +483,7 @@ impl SQLContext {
 
         let alter_comment = parse_alter_column_comment(&rewritten_sql)?;
         let from_alter_comment = alter_comment.is_some();
-        let statements = if let Some(statement) = alter_comment {
+        let mut statements = if let Some(statement) = alter_comment {
             vec![statement]
         } else {
             parse_sql_statements(&rewritten_sql)?
@@ -493,6 +495,15 @@ impl SQLContext {
             ));
         }
 
+        let rewritten;
+        let persistent_definition = matches!(&statements[0], 
Statement::CreateView(view) if !view.temporary && 
self.is_paimon_catalog_ref(&TableReference::from(view.name.to_string().as_str())))
+            || matches!(&statements[0], Statement::CreateFunction(_));
+        let sql = if !persistent_definition && 
crate::binary_cast::rewrite(&mut statements[0])? {
+            rewritten = statements[0].to_string();
+            rewritten.as_str()
+        } else {
+            sql
+        };
         match &statements[0] {
             Statement::Comment {
                 object_type,
@@ -4507,6 +4518,32 @@ mod tests {
         ));
     }
 
+    #[tokio::test]
+    async fn binary_cast_preserves_persistent_view_sql() {
+        let catalog = Arc::new(MockCatalog::new());
+        let ctx = make_sql_context(catalog.clone()).await;
+        ctx.sql("CREATE VIEW bounded_view AS SELECT CAST('ab' AS BINARY(4)) AS 
bytes")
+            .await
+            .unwrap();
+        let view = catalog
+            .get_view(&Identifier::new("default", "bounded_view"))
+            .await
+            .unwrap();
+        assert!(view.query_for("spark").contains("BINARY(4)"));
+        assert!(!view.query_for("spark").contains("__paimon"));
+        let rows = ctx
+            .sql("SELECT to_base64(bytes) = 'YWIAAA==' FROM bounded_view")
+            .await
+            .unwrap()
+            .collect()
+            .await
+            .unwrap();
+        assert_eq!(
+            ScalarValue::try_from_array(rows[0].column(0), 0).unwrap(),
+            ScalarValue::Boolean(Some(true))
+        );
+    }
+
     #[tokio::test]
     async fn persistent_rest_catalog_view_can_be_created_and_read() {
         let catalog = Arc::new(MockCatalog::new());
diff --git a/crates/integrations/datafusion/src/sql_function.rs 
b/crates/integrations/datafusion/src/sql_function.rs
index ad7d643e..22f2a2d8 100644
--- a/crates/integrations/datafusion/src/sql_function.rs
+++ b/crates/integrations/datafusion/src/sql_function.rs
@@ -243,6 +243,7 @@ async fn expand_statement_internal(
             return Err(error);
         }
         if expanded_count == 0 {
+            crate::binary_cast::rewrite(&mut statement)?;
             return Ok(statement);
         }
     }
diff --git a/crates/integrations/datafusion/tests/binary_cast.rs 
b/crates/integrations/datafusion/tests/binary_cast.rs
new file mode 100644
index 00000000..1c1aecac
--- /dev/null
+++ b/crates/integrations/datafusion/tests/binary_cast.rs
@@ -0,0 +1,132 @@
+// 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;
+#[tokio::test]
+async fn binary_casts_preserve_bytes_and_apply_declared_width() {
+    let ctx = SQLContext::new();
+    for expression in [
+        "CAST('汉' AS BINARY) = decode('e6b189','hex')",
+        "CAST('ab' AS BINARY(4)) = decode('61620000','hex')",
+        "CAST('abcd' AS BINARY(2)) = decode('6162','hex')",
+        "CAST('abcd' AS VARBINARY(2)) = decode('6162','hex')",
+        "CAST(decode('00ff','hex') AS BINARY) = decode('00ff','hex')",
+        "CAST(decode('00ff','hex') AS VARBINARY) = decode('00ff','hex')",
+        "CAST(NULL AS BINARY(2)) IS NULL",
+        "TRY_CAST(NULL AS VARBINARY(2)) IS NULL",
+    ] {
+        let batches = ctx
+            .sql(&format!("SELECT {expression}"))
+            .await
+            .unwrap()
+            .collect()
+            .await
+            .unwrap();
+        assert_eq!(
+            ScalarValue::try_from_array(batches[0].column(0), 0).unwrap(),
+            ScalarValue::Boolean(Some(true)),
+            "{expression}"
+        );
+    }
+}
+
+#[tokio::test]
+async fn binary_casts_work_in_native_views_and_column_expressions() {
+    let ctx = SQLContext::new();
+    ctx.sql("CREATE VIEW bytes_view AS SELECT CAST('ab' AS BINARY(4)) AS b")
+        .await
+        .unwrap();
+    for sql in [
+        "SELECT to_base64(b) = 'YWIAAA==' FROM bytes_view",
+        "SELECT to_base64(CAST(CAST('abcd' AS BINARY(6)) AS VARBINARY(2))) = 
'YWI='",
+        "SELECT CAST(s AS BINARY(3)) = decode(expected, 'hex') OR (s IS NULL 
AND CAST(s AS BINARY(3)) IS NULL) FROM (VALUES ('ab','616200'), 
('abcd','616263'), (NULL,NULL)) t(s,expected)",
+    ] {
+        let batches=ctx.sql(sql).await.unwrap().collect().await.unwrap();
+        for batch in batches { for row in 0..batch.num_rows() {
+            
assert_eq!(ScalarValue::try_from_array(batch.column(0),row).unwrap(),ScalarValue::Boolean(Some(true)),"{sql}");
+        }}
+    }
+    for ty in [
+        "BINARY(0)",
+        "VARBINARY(0)",
+        "BINARY(2147483648)",
+        "VARBINARY(18446744073709551615)",
+    ] {
+        assert!(
+            ctx.sql(&format!("SELECT CAST('x' AS {ty})")).await.is_err(),
+            "{ty}"
+        );
+    }
+}
+
+#[tokio::test]
+async fn binary_width_decodes_arrow_binary_views_and_dictionary_value_nulls() {
+    use datafusion::arrow::{
+        array::{
+            Array, ArrayRef, BinaryArray, BinaryViewArray, DictionaryArray, 
Int8Array,
+            LargeBinaryArray, RecordBatch,
+        },
+        datatypes::{Field, Int8Type, Schema},
+    };
+    use std::sync::Arc;
+    let values = Arc::new(BinaryArray::from(vec![Some(&[0, 255][..]), None]));
+    let dictionary =
+        DictionaryArray::<Int8Type>::try_new(Int8Array::from(vec![Some(0), 
Some(1), None]), values)
+            .unwrap();
+    let arrays: Vec<ArrayRef> = vec![
+        Arc::new(BinaryViewArray::from(vec![Some(&[0, 255][..]), None, None])),
+        Arc::new(LargeBinaryArray::from(vec![
+            Some(&[0, 255][..]),
+            None,
+            None,
+        ])),
+        Arc::new(dictionary),
+    ];
+    for input in arrays {
+        let ctx = SQLContext::new();
+        let schema = Arc::new(Schema::new(vec![Field::new(
+            "b",
+            input.data_type().clone(),
+            true,
+        )]));
+        ctx.ctx()
+            .register_batch("bytes", RecordBatch::try_new(schema, 
vec![input]).unwrap())
+            .unwrap();
+        let batches = ctx
+            .sql("SELECT to_base64(CAST(b AS BINARY(4))) FROM bytes")
+            .await
+            .unwrap()
+            .collect()
+            .await
+            .unwrap();
+        let result = batches
+            .iter()
+            .flat_map(|b| {
+                (0..b.num_rows()).map(|r| 
ScalarValue::try_from_array(b.column(0), r).unwrap())
+            })
+            .collect::<Vec<_>>();
+        assert_eq!(
+            result,
+            vec![
+                ScalarValue::Utf8(Some("AP8AAA==".into())),
+                ScalarValue::Utf8(None),
+                ScalarValue::Utf8(None)
+            ]
+        );
+    }
+}
diff --git a/docs/src/sql.md b/docs/src/sql.md
index 25637300..08039d2e 100644
--- a/docs/src/sql.md
+++ b/docs/src/sql.md
@@ -582,6 +582,27 @@ use paimon_datafusion::register_variant_functions;
 register_variant_functions(&ctx);
 ```
 
+### Binary casts in queries
+
+`CAST` and `TRY_CAST` accept `BINARY`, `BINARY(n)`, `VARBINARY`,
+`VARBINARY(n)` and `VARBINARY(MAX)` through SQLContext.
+
+- Without a length, casts preserve the bytes. Strings use their UTF-8 bytes.
+- `BINARY(n)` truncates to at most `n` bytes and right-pads shorter values with
+  zero bytes.
+- `VARBINARY(n)` truncates to at most `n` bytes without padding.
+- Widths are byte counts, including for multibyte text. They must be positive
+  and fit an Arrow binary offset. SQL NULL remains NULL.
+
+```sql
+SELECT to_base64(CAST('ab' AS BINARY(4))); -- YWIAAA==
+SELECT to_base64(CAST('abcd' AS VARBINARY(2))); -- YWI=
+```
+
+The source conversions supported by DataFusion's binary cast remain in effect.
+`TRY_CAST` preserves its native conversion-failure behavior; an invalid type
+length is a planning error.
+
 ## DDL
 
 ### DATABASE

Reply via email to