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 a939bf70 feat(datafusion): add common SQL compatibility functions
(#1280)
a939bf70 is described below
commit a939bf70e9e2d81de010eded75701bbb13b984c1
Author: Jingsong Lee <[email protected]>
AuthorDate: Sun Nov 1 23:49:56 2026 +0800
feat(datafusion): add common SQL compatibility functions (#1280)
---
Cargo.lock | 3 +
crates/integrations/datafusion/Cargo.toml | 3 +
.../datafusion/src/compat_functions.rs | 356 +++++++++++++++++++++
crates/integrations/datafusion/src/lib.rs | 1 +
crates/integrations/datafusion/src/sql_context.rs | 1 +
.../datafusion/tests/compat_functions.rs | 320 ++++++++++++++++++
docs/src/sql.md | 28 ++
7 files changed, 712 insertions(+)
diff --git a/Cargo.lock b/Cargo.lock
index 41ea5cf2..de2e0063 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4764,6 +4764,7 @@ dependencies = [
"arrow-select",
"async-trait",
"axum",
+ "base64 0.22.1",
"bigdecimal",
"bytes",
"chrono",
@@ -4776,8 +4777,10 @@ dependencies = [
"paimon",
"paimon-ftindex-core",
"parquet",
+ "regex",
"serde",
"serde_json",
+ "sha2 0.10.9",
"tar",
"tempfile",
"tokio",
diff --git a/crates/integrations/datafusion/Cargo.toml
b/crates/integrations/datafusion/Cargo.toml
index 9d41f8ba..88838d41 100644
--- a/crates/integrations/datafusion/Cargo.toml
+++ b/crates/integrations/datafusion/Cargo.toml
@@ -34,6 +34,7 @@ vortex = ["paimon/vortex"]
[dependencies]
arrow-select = { workspace = true }
async-trait = "0.1"
+base64 = "0.22"
bigdecimal = "0.4"
chrono = "0.4"
constant_time_eq = { workspace = true }
@@ -41,8 +42,10 @@ datafusion = { workspace = true }
log = "0.4"
paimon = { workspace = true }
futures = "0.3"
+regex = "1"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
+sha2 = "0.10"
tokio = { workspace = true, features = ["rt", "rt-multi-thread", "time", "fs"]
}
uuid = { version = "1", features = ["v4"] }
diff --git a/crates/integrations/datafusion/src/compat_functions.rs
b/crates/integrations/datafusion/src/compat_functions.rs
new file mode 100644
index 00000000..3e9f5365
--- /dev/null
+++ b/crates/integrations/datafusion/src/compat_functions.rs
@@ -0,0 +1,356 @@
+// 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::collections::HashMap;
+use std::sync::Arc;
+
+use base64::Engine;
+use datafusion::arrow::array::{
+ Array, ArrayRef, BinaryArray, Date32Array, Int64Array, ListBuilder,
StringArray, StringBuilder,
+};
+use datafusion::arrow::compute::{cast, kernels::numeric};
+use datafusion::arrow::datatypes::{DataType, Field, FieldRef};
+use datafusion::common::config::ConfigOptions;
+use datafusion::common::types::{logical_int64, logical_string, NativeType};
+use datafusion::common::{DataFusionError, Result, ScalarValue};
+use datafusion::logical_expr::simplify::{ExprSimplifyResult, SimplifyContext};
+use datafusion::logical_expr::type_coercion::binary::BinaryTypeCoercer;
+use datafusion::logical_expr::{
+ Coercion, ColumnarValue, Expr, Operator, ReturnFieldArgs,
ScalarFunctionArgs, ScalarUDF,
+ ScalarUDFImpl, Signature, TypeSignature, TypeSignatureClass, Volatility,
+};
+use datafusion::prelude::SessionContext;
+use regex::Regex;
+use sha2::{Digest, Sha224, Sha256, Sha384, Sha512};
+
+pub(crate) fn register_compat_functions(ctx: &SessionContext) {
+ for (name, alias) in [
+ ("current_date", "curdate"),
+ ("to_timestamp_millis", "timestamp_millis"),
+ ("to_timestamp", "to_timestamp_ltz"),
+ ] {
+ ctx.register_udf(ScalarUDF::from(ConfiguredAlias {
+ name: alias,
+ inner: Arc::clone(&ctx.state().scalar_functions()[name]),
+ }));
+ }
+ for kind in [
+ Kind::Mod,
+ Kind::DateSub,
+ Kind::RegexpExtract,
+ Kind::RegexpExtractAll,
+ Kind::Sha2,
+ Kind::ToBase64,
+ ] {
+ let signature = match kind {
+ Kind::Mod => Signature::user_defined(Volatility::Immutable),
+ Kind::DateSub => Signature::one_of(
+ vec![
+ TypeSignature::Exact(vec![DataType::Date32,
DataType::Int64]),
+ TypeSignature::Exact(vec![DataType::Utf8,
DataType::Int64]),
+ ],
+ Volatility::Immutable,
+ ),
+ Kind::RegexpExtract | Kind::RegexpExtractAll => Signature::one_of(
+ vec![
+ TypeSignature::Exact(vec![DataType::Utf8, DataType::Utf8]),
+ TypeSignature::Exact(vec![DataType::Utf8, DataType::Utf8,
DataType::Int64]),
+ ],
+ Volatility::Immutable,
+ ),
+ Kind::Sha2 => Signature::one_of(
+ [
+ TypeSignatureClass::Native(logical_string()),
+ TypeSignatureClass::Binary,
+ ]
+ .into_iter()
+ .map(|input| {
+ TypeSignature::Coercible(vec![
+ Coercion::new_exact(input),
+ Coercion::new_implicit(
+ TypeSignatureClass::Native(logical_int64()),
+ vec![TypeSignatureClass::Integer],
+ NativeType::Int64,
+ ),
+ ])
+ })
+ .collect(),
+ Volatility::Immutable,
+ ),
+ Kind::ToBase64 => Signature::one_of(
+ [
+ TypeSignatureClass::Native(logical_string()),
+ TypeSignatureClass::Binary,
+ ]
+ .into_iter()
+ .map(|input|
TypeSignature::Coercible(vec![Coercion::new_exact(input)]))
+ .collect(),
+ Volatility::Immutable,
+ ),
+ };
+ ctx.register_udf(ScalarUDF::from(CompatFunction { kind, signature }));
+ }
+}
+
+// DataFusion 54's with_aliases wrapper does not forward configuration updates.
+// Keep the native function registered separately and forward timezone changes
+// and simplification to the alias's own native implementation.
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+struct ConfiguredAlias {
+ name: &'static str,
+ inner: Arc<ScalarUDF>,
+}
+
+impl ScalarUDFImpl for ConfiguredAlias {
+ fn name(&self) -> &str {
+ self.name
+ }
+ fn signature(&self) -> &Signature {
+ self.inner.signature()
+ }
+ fn return_type(&self, types: &[DataType]) -> Result<DataType> {
+ self.inner.inner().return_type(types)
+ }
+ fn return_field_from_args(&self, args: ReturnFieldArgs) ->
Result<FieldRef> {
+ self.inner.inner().return_field_from_args(args)
+ }
+ fn invoke_with_args(&self, args: ScalarFunctionArgs) ->
Result<ColumnarValue> {
+ self.inner.invoke_with_args(args)
+ }
+ fn simplify(&self, args: Vec<Expr>, info: &SimplifyContext) ->
Result<ExprSimplifyResult> {
+ self.inner.inner().simplify(args, info)
+ }
+ fn with_updated_config(&self, config: &ConfigOptions) -> Option<ScalarUDF>
{
+ self.inner.inner().with_updated_config(config).map(|inner| {
+ ScalarUDF::from(Self {
+ name: self.name,
+ inner: Arc::new(inner),
+ })
+ })
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+enum Kind {
+ Mod,
+ DateSub,
+ RegexpExtract,
+ RegexpExtractAll,
+ Sha2,
+ ToBase64,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+struct CompatFunction {
+ kind: Kind,
+ signature: Signature,
+}
+
+impl ScalarUDFImpl for CompatFunction {
+ fn name(&self) -> &str {
+ match self.kind {
+ Kind::Mod => "mod",
+ Kind::DateSub => "date_sub",
+ Kind::RegexpExtract => "regexp_extract",
+ Kind::RegexpExtractAll => "regexp_extract_all",
+ Kind::Sha2 => "sha2",
+ Kind::ToBase64 => "to_base64",
+ }
+ }
+ fn signature(&self) -> &Signature {
+ &self.signature
+ }
+ fn coerce_types(&self, types: &[DataType]) -> Result<Vec<DataType>> {
+ let [left, right] = types else {
+ return Err(DataFusionError::Plan("mod expects two
arguments".into()));
+ };
+ let (left, right) =
+ BinaryTypeCoercer::new(left, &Operator::Modulo,
right).get_input_types()?;
+ Ok(vec![left, right])
+ }
+ fn return_type(&self, types: &[DataType]) -> Result<DataType> {
+ if self.kind == Kind::Mod {
+ return BinaryTypeCoercer::new(&types[0], &Operator::Modulo,
&types[1])
+ .get_result_type();
+ }
+ Ok(match self.kind {
+ Kind::Mod => unreachable!("handled above"),
+ Kind::DateSub => DataType::Date32,
+ Kind::RegexpExtractAll => {
+ DataType::List(Arc::new(Field::new("item", DataType::Utf8,
true)))
+ }
+ _ => DataType::Utf8,
+ })
+ }
+ fn invoke_with_args(&self, args: ScalarFunctionArgs) ->
Result<ColumnarValue> {
+ let arrays = ColumnarValue::values_to_arrays(&args.args)?;
+ let output: ArrayRef = match self.kind {
+ Kind::Mod => numeric::rem(&arrays[0].as_ref(),
&arrays[1].as_ref())?,
+ Kind::DateSub => {
+ let dates = cast(&arrays[0], &DataType::Date32)?;
+ let dates = dates
+ .as_any()
+ .downcast_ref::<Date32Array>()
+ .ok_or_else(|| error("date_sub expects dates"))?;
+ let days = arrays[1]
+ .as_any()
+ .downcast_ref::<Int64Array>()
+ .ok_or_else(|| error("date_sub expects integer days"))?;
+ let values = dates
+ .iter()
+ .zip(days.iter())
+ .map(|(date, days)| match (date, days) {
+ (Some(date), Some(days)) => i64::from(date)
+ .checked_sub(days)
+ .and_then(|value| i32::try_from(value).ok())
+ .map(Some)
+ .ok_or_else(|| error("date_sub date overflow")),
+ _ => Ok(None),
+ })
+ .collect::<Result<Vec<_>>>()?;
+ Arc::new(Date32Array::from(values))
+ }
+ Kind::RegexpExtract | Kind::RegexpExtractAll => {
+ extract_regex(&arrays, self.kind == Kind::RegexpExtractAll)?
+ }
+ Kind::Sha2 | Kind::ToBase64 => {
+ // Preserve the byte family during planning, then normalize its
+ // Arrow representation without decoding binary data as UTF-8.
+ let input_type = if
NativeType::from(arrays[0].data_type()).is_binary() {
+ DataType::Binary
+ } else {
+ DataType::Utf8
+ };
+ let input = cast(&arrays[0], &input_type)?;
+ let mut result = StringBuilder::new();
+ for row in 0..arrays[0].len() {
+ if input.is_null(row)
+ || arrays
+ .iter()
+ .skip(1)
+ .any(|array| array.data_type() == &DataType::Null
|| array.is_null(row))
+ {
+ result.append_null();
+ continue;
+ }
+ let bytes = if let Some(array) =
input.as_any().downcast_ref::<BinaryArray>() {
+ array.value(row)
+ } else {
+ input
+ .as_any()
+ .downcast_ref::<StringArray>()
+ .ok_or_else(|| error("expected string or binary"))?
+ .value(row)
+ .as_bytes()
+ };
+ if self.kind == Kind::ToBase64 {
+ result
+
.append_value(base64::engine::general_purpose::STANDARD.encode(bytes));
+ } else {
+ let bits = arrays[1]
+ .as_any()
+ .downcast_ref::<Int64Array>()
+ .ok_or_else(|| error("sha2 expects integer bit
length"))?
+ .value(row);
+ let digest = match bits {
+ 0 | 256 => Some(format!("{:x}",
Sha256::digest(bytes))),
+ 224 => Some(format!("{:x}",
Sha224::digest(bytes))),
+ 384 => Some(format!("{:x}",
Sha384::digest(bytes))),
+ 512 => Some(format!("{:x}",
Sha512::digest(bytes))),
+ _ => None,
+ };
+ result.append_option(digest);
+ }
+ }
+ Arc::new(result.finish())
+ }
+ };
+ if args
+ .args
+ .iter()
+ .all(|arg| matches!(arg, ColumnarValue::Scalar(_)))
+ {
+ Ok(ColumnarValue::Scalar(ScalarValue::try_from_array(
+ &output, 0,
+ )?))
+ } else {
+ Ok(ColumnarValue::Array(output))
+ }
+ }
+}
+
+fn extract_regex(arrays: &[ArrayRef], all: bool) -> Result<ArrayRef> {
+ let text = cast(&arrays[0], &DataType::Utf8)?;
+ let pattern = cast(&arrays[1], &DataType::Utf8)?;
+ let text = text.as_any().downcast_ref::<StringArray>().unwrap();
+ let pattern = pattern.as_any().downcast_ref::<StringArray>().unwrap();
+ let index = arrays
+ .get(2)
+ .map(|array| array.as_any().downcast_ref::<Int64Array>().unwrap());
+ let mut cache = HashMap::<&str, Regex>::new();
+ let mut strings = StringBuilder::new();
+ let mut lists = ListBuilder::new(StringBuilder::new());
+ for row in 0..text.len() {
+ if arrays.iter().any(|array| array.is_null(row)) {
+ strings.append_null();
+ lists.append(false);
+ continue;
+ }
+ let group = usize::try_from(index.map(|index|
index.value(row)).unwrap_or(1))
+ .map_err(|_| error("regexp_extract group index must be
non-negative"))?;
+ let regex = match cache.entry(pattern.value(row)) {
+ std::collections::hash_map::Entry::Occupied(entry) =>
entry.into_mut(),
+ std::collections::hash_map::Entry::Vacant(entry) => {
+ let regex = Regex::new(entry.key())
+ .map_err(|e| error(format!("Invalid regular expression:
{e}")))?;
+ entry.insert(regex)
+ }
+ };
+ if group >= regex.captures_len() {
+ return Err(error(format!(
+ "regexp_extract group index {group} exceeds {}",
+ regex.captures_len() - 1
+ )));
+ }
+ if all {
+ for capture in regex.captures_iter(text.value(row)) {
+ lists
+ .values()
+ .append_value(capture.get(group).map(|m|
m.as_str()).unwrap_or(""));
+ }
+ lists.append(true);
+ } else {
+ let capture = regex.captures(text.value(row));
+ strings.append_value(
+ capture
+ .as_ref()
+ .and_then(|capture| capture.get(group))
+ .map(|m| m.as_str())
+ .unwrap_or(""),
+ );
+ }
+ }
+ Ok(if all {
+ Arc::new(lists.finish())
+ } else {
+ Arc::new(strings.finish())
+ })
+}
+
+fn error(message: impl Into<String>) -> DataFusionError {
+ DataFusionError::Execution(message.into())
+}
diff --git a/crates/integrations/datafusion/src/lib.rs
b/crates/integrations/datafusion/src/lib.rs
index ecc39411..6718045d 100644
--- a/crates/integrations/datafusion/src/lib.rs
+++ b/crates/integrations/datafusion/src/lib.rs
@@ -40,6 +40,7 @@ mod blob_descriptor_functions;
mod blob_reader;
mod blob_view;
mod catalog;
+mod compat_functions;
mod delete;
mod error;
mod filter_pushdown;
diff --git a/crates/integrations/datafusion/src/sql_context.rs
b/crates/integrations/datafusion/src/sql_context.rs
index 1432da55..da0906bc 100644
--- a/crates/integrations/datafusion/src/sql_context.rs
+++ b/crates/integrations/datafusion/src/sql_context.rs
@@ -168,6 +168,7 @@ impl SQLContextBuilder {
}
let state = state_builder.build();
let ctx = SessionContext::new_with_state(state);
+ crate::compat_functions::register_compat_functions(&ctx);
crate::blob_descriptor_functions::register_blob_descriptor_functions(&ctx);
crate::variant_functions::register_variant_functions(&ctx);
crate::json_functions::register_json_functions(&ctx);
diff --git a/crates/integrations/datafusion/tests/compat_functions.rs
b/crates/integrations/datafusion/tests/compat_functions.rs
new file mode 100644
index 00000000..90c80ea0
--- /dev/null
+++ b/crates/integrations/datafusion/tests/compat_functions.rs
@@ -0,0 +1,320 @@
+// 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 assert_true(ctx: &SQLContext, expressions: &[&str]) {
+ for expression in expressions {
+ 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}"
+ );
+ }
+}
+
+async fn assert_error(ctx: &SQLContext, expression: &str, expected: &str) {
+ let result = ctx.sql(&format!("SELECT {expression}")).await;
+ let error = match result {
+ Err(error) => error,
+ Ok(frame) => frame.collect().await.unwrap_err(),
+ };
+ assert!(
+ error.to_string().contains(expected),
+ "{expression}: {error}"
+ );
+}
+
+#[tokio::test]
+async fn mod_preserves_numeric_remainder_and_null_semantics() {
+ let ctx = SQLContext::new();
+ assert_true(
+ &ctx,
+ &[
+ "mod(5, 2) = 1",
+ "mod(-5, 2) = -1",
+ "mod(5, -2) = 1",
+ "mod(5.5, 2.0) = 5.5 % 2.0",
+ "mod(CAST(7 AS BIGINT), 3) = 1",
+ "mod(CAST(NULL AS BIGINT), 2) IS NULL",
+ "mod(NULL, 2) IS NULL",
+ "mod(2, NULL) IS NULL",
+ ],
+ )
+ .await;
+ assert_error(&ctx, "mod(1, 0)", "zero").await;
+}
+
+#[tokio::test]
+async fn mod_matches_native_remainder_decimal_coercion() {
+ let ctx = SQLContext::new();
+ for (left, right) in [
+ ("CAST(5.55 AS DECIMAL(10,2))", "CAST(2.1 AS DECIMAL(4,1))"),
+ (
+ "CAST('12345678901234567890123456789012345678' AS DECIMAL(38,0))",
+ "CAST('0.1' AS DECIMAL(38,1))",
+ ),
+ ("CAST(5.55 AS DECIMAL(10,2))", "CAST(2.1 AS DOUBLE)"),
+ ("CAST(5.55 AS DECIMAL(10,2))", "CAST(2 AS BIGINT)"),
+ ] {
+ let sql = format!("SELECT mod({left}, {right}) AS actual, {left} %
{right} AS expected");
+ let batches = ctx.sql(&sql).await.unwrap().collect().await.unwrap();
+ let batch = &batches[0];
+ assert_eq!(
+ batch.column(0).data_type(),
+ batch.column(1).data_type(),
+ "{sql}"
+ );
+ assert_eq!(
+ ScalarValue::try_from_array(batch.column(0), 0).unwrap(),
+ ScalarValue::try_from_array(batch.column(1), 0).unwrap(),
+ "{sql}"
+ );
+ }
+}
+
+#[tokio::test]
+async fn date_sub_null_days_do_not_parse_rejected_strings() {
+ let ctx = SQLContext::new();
+ assert_true(
+ &ctx,
+ &["date_sub('not-a-date', CAST(NULL AS BIGINT)) IS NULL"],
+ )
+ .await;
+ let batches = ctx
+ .sql(
+ "SELECT date_sub(d, days) FROM (VALUES \
+ ('not-a-date', CAST(NULL AS BIGINT)), ('2024-03-01', CAST(1 AS
BIGINT))) AS t(d, days)",
+ )
+ .await
+ .unwrap()
+ .collect()
+ .await
+ .unwrap();
+ assert_eq!(
+ ScalarValue::try_from_array(batches[0].column(0), 0).unwrap(),
+ ScalarValue::Date32(None)
+ );
+ assert_eq!(
+ ScalarValue::try_from_array(batches[0].column(0), 1).unwrap(),
+ ScalarValue::Date32(Some(19782))
+ );
+}
+
+#[tokio::test]
+async fn regexp_extraction_handles_groups_no_match_unicode_and_nulls() {
+ let ctx = SQLContext::new();
+ assert_true(
+ &ctx,
+ &[
+ "regexp_extract('a12b', '([0-9]+)') = '12'",
+ "regexp_extract('a12b', '([0-9]+)', 0) = '12'",
+ "regexp_extract('no match', '([0-9]+)') = ''",
+ "regexp_extract('b', '(a)?b') = ''",
+ "regexp_extract('你好42', '(你好)([0-9]+)', 1) = '你好'",
+ "regexp_extract_all('a1 b2', '([a-z])([0-9])', 2) = ['1', '2']",
+ "cardinality(regexp_extract_all('no match', '([0-9]+)')) = 0",
+ "regexp_extract(NULL, '(x)') IS NULL",
+ "regexp_extract_all('x', NULL) IS NULL",
+ "regexp_extract('x', '(x)', NULL) IS NULL",
+ ],
+ )
+ .await;
+ assert_error(
+ &ctx,
+ "regexp_extract('x', '[')",
+ "Invalid regular expression",
+ )
+ .await;
+ assert_error(&ctx, "regexp_extract('x', '(x)', -1)", "non-negative").await;
+ assert_error(&ctx, "regexp_extract_all('x', '(x)', 2)", "group
index").await;
+}
+
+#[tokio::test]
+async fn regexp_extraction_evaluates_dynamic_patterns_and_indices() {
+ let ctx = SQLContext::new();
+ let batches = ctx
+ .sql(
+ "SELECT regexp_extract(s, p, i) FROM (VALUES \
+ ('a12', '([0-9]+)', 1), ('b34', '(b)(34)', 2), ('c56', '(c)', 0), \
+ (NULL, '(x)', 1)) AS t(s, p, i)",
+ )
+ .await
+ .unwrap()
+ .collect()
+ .await
+ .unwrap();
+ for (row, expected) in [Some("12"), Some("34"), Some("c"), None]
+ .into_iter()
+ .enumerate()
+ {
+ assert_eq!(
+ ScalarValue::try_from_array(batches[0].column(0), row).unwrap(),
+ ScalarValue::Utf8(expected.map(str::to_string))
+ );
+ }
+}
+
+#[tokio::test]
+async fn date_sub_handles_leap_days_negative_days_and_overflow() {
+ let ctx = SQLContext::new();
+ assert_true(
+ &ctx,
+ &[
+ "date_sub(DATE '2024-03-01', 1) = DATE '2024-02-29'",
+ "date_sub('2024-03-01', -1) = DATE '2024-03-02'",
+ "date_sub(DATE '2024-03-01', 0) = DATE '2024-03-01'",
+ "date_sub(CAST(NULL AS DATE), 1) IS NULL",
+ ],
+ )
+ .await;
+ assert_error(
+ &ctx,
+ "date_sub(DATE '2024-03-01', 9223372036854775807)",
+ "overflow",
+ )
+ .await;
+}
+
+#[tokio::test]
+async fn sha2_and_base64_preserve_padding_binary_and_null_contracts() {
+ let ctx = SQLContext::new();
+ assert_true(
+ &ctx,
+ &[
+ "sha2('abc', 256) =
'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad'",
+ "sha2('abc', 0) = sha2('abc', 256)",
+ "length(sha2('abc', 224)) = 56",
+ "length(sha2('abc', 384)) = 96",
+ "length(sha2('abc', 512)) = 128",
+ "sha2('abc', 123) IS NULL",
+ "sha2(NULL, 256) IS NULL",
+ "sha2('abc', NULL) IS NULL",
+ "sha2(decode('616263', 'hex'), 256) = sha2('abc', 256)",
+ "to_base64('f') = 'Zg=='",
+ "to_base64('fo') = 'Zm8='",
+ "to_base64('foo') = 'Zm9v'",
+ "to_base64('') = ''",
+ "to_base64(NULL) IS NULL",
+ "to_base64(decode('00ff', 'hex')) = 'AP8='",
+ ],
+ )
+ .await;
+}
+
+#[tokio::test]
+async fn binary_encoding_preserves_non_utf8_bytes_across_arrow_types() {
+ let ctx = SQLContext::new();
+ assert_true(&ctx, &[
+ "sha2(decode('00ff', 'hex'), CAST(256 AS INT)) = sha2(decode('00ff',
'hex'), 256)",
+ "to_base64(arrow_cast(decode('00ff', 'hex'), 'LargeBinary')) = 'AP8='",
+ "to_base64(arrow_cast(decode('00ff', 'hex'), 'BinaryView')) = 'AP8='",
+ "to_base64(arrow_cast(decode('00ff', 'hex'), 'FixedSizeBinary(2)')) =
'AP8='",
+ "sha2(arrow_cast(decode('00ff', 'hex'), 'LargeBinary'), 256) =
sha2(decode('00ff', 'hex'), 256)",
+ "sha2(arrow_cast(decode('00ff', 'hex'), 'BinaryView'), 256) =
sha2(decode('00ff', 'hex'), 256)",
+ ]).await;
+}
+
+#[tokio::test]
+async fn binary_encoding_preserves_dictionary_bytes_and_value_nulls() {
+ use datafusion::arrow::array::{Array, BinaryArray, DictionaryArray,
Int8Array, RecordBatch};
+ use datafusion::arrow::datatypes::{Field, Int8Type, Schema};
+ use std::sync::Arc;
+ let ctx = SQLContext::new();
+ let values = Arc::new(BinaryArray::from(vec![Some(&[0_u8, 255][..]),
None]));
+ let encoded =
+ DictionaryArray::<Int8Type>::try_new(Int8Array::from(vec![Some(0),
Some(1), None]), values)
+ .unwrap();
+ let schema = Arc::new(Schema::new(vec![Field::new(
+ "bytes",
+ encoded.data_type().clone(),
+ true,
+ )]));
+ ctx.ctx()
+ .register_batch(
+ "encoded_bytes",
+ RecordBatch::try_new(schema, vec![Arc::new(encoded)]).unwrap(),
+ )
+ .unwrap();
+ let batches = ctx.sql("SELECT to_base64(bytes), sha2(bytes, 256),
sha2(decode('00ff', 'hex'), 256) FROM encoded_bytes")
+ .await.unwrap().collect().await.unwrap();
+ let batch = &batches[0];
+ assert_eq!(
+ ScalarValue::try_from_array(batch.column(0), 0).unwrap(),
+ ScalarValue::Utf8(Some("AP8=".into()))
+ );
+ assert_eq!(
+ ScalarValue::try_from_array(batch.column(1), 0).unwrap(),
+ ScalarValue::try_from_array(batch.column(2), 0).unwrap()
+ );
+ for row in [1, 2] {
+ for column in [0, 1] {
+ assert_eq!(
+ ScalarValue::try_from_array(batch.column(column),
row).unwrap(),
+ ScalarValue::Utf8(None)
+ );
+ }
+ }
+}
+
+#[tokio::test]
+async fn date_and_timestamp_aliases_follow_session_timezone_and_epoch_units() {
+ let ctx = SQLContext::new();
+ for timezone in ["+00:00", "Asia/Shanghai"] {
+ ctx.sql(&format!("SET TIME ZONE = '{timezone}'"))
+ .await
+ .unwrap();
+ assert_true(
+ &ctx,
+ &[
+ "curdate() = current_date()",
+ "timestamp_millis(1000) = to_timestamp_millis(1000)",
+ "to_timestamp_ltz('2024-01-01 00:00:00') =
to_timestamp('2024-01-01 00:00:00')",
+ "to_timestamp_ltz(NULL) IS NULL",
+ ],
+ )
+ .await;
+ let batches = ctx
+ .sql("SELECT to_timestamp_ltz('2024-01-01 00:00:00'),
to_timestamp('2024-01-01 00:00:00')")
+ .await
+ .unwrap()
+ .collect()
+ .await
+ .unwrap();
+ for column in batches[0].columns() {
+ assert_eq!(
+ ScalarValue::try_from_array(column, 0).unwrap(),
+ ScalarValue::TimestampNanosecond(
+ Some(if timezone == "+00:00" {
+ 1704067200000000000
+ } else {
+ 1704038400000000000
+ }),
+ Some(timezone.into())
+ )
+ );
+ }
+ }
+}
diff --git a/docs/src/sql.md b/docs/src/sql.md
index 956bcd30..422a7218 100644
--- a/docs/src/sql.md
+++ b/docs/src/sql.md
@@ -1888,6 +1888,34 @@ SELECT
FROM paimon.my_db.user_events;
```
+### Compatibility Functions
+
+`SQLContext` registers the following functions without requiring a catalog:
+
+| Function | Behavior |
+| --- | --- |
+| `mod(value, divisor)` | Numeric remainder with DataFusion `%` coercion,
null, sign, and division-by-zero behavior |
+| `regexp_extract(text, pattern[, index])` | The first matched group; default
index 1; index 0 selects the complete match |
+| `regexp_extract_all(text, pattern[, index])` | A list of matched groups, in
occurrence order |
+| `date_sub(date, days)` | Subtracts integral calendar days and returns
`DATE`; negative days add days |
+| `sha2(text_or_binary, bits)` | Lowercase SHA-2 hex for 224, 256, 384, or 512
bits; 0 means 256; other lengths return null |
+| `to_base64(text_or_binary)` | Standard Base64 with `=` padding; strings are
encoded as UTF-8 |
+| `curdate()` | Alias of `current_date()` |
+| `timestamp_millis(value)` | Alias of `to_timestamp_millis(value)`,
preserving millisecond epoch units |
+| `to_timestamp_ltz(value[, format...])` | Alias of `to_timestamp`, preserving
its session time zone and nanosecond result |
+
+Regular expressions use Rust regex syntax, like DataFusion's existing regex
+functions, rather than the full Java regex dialect. No match or an unmatched
+optional group produces an empty string; no matches for `regexp_extract_all`
+produce an empty list. Null arguments produce null. Invalid patterns, negative
+or out-of-range group indices, and date arithmetic overflow produce errors.
+SHA-2 and Base64 preserve raw bytes across Arrow binary representations,
+including dictionary encodings and null dictionary values.
+
+The timestamp aliases retain DataFusion semantics: optional formats are Chrono
+strftime strings, not Spark/Java patterns; numeric `to_timestamp_ltz` inputs
+are epoch seconds. The Flink `(number, precision)` overload is not implemented.
+
### Column Projection
Only the required columns are read, reducing I/O: