This is an automated email from the ASF dual-hosted git repository.
SteNicholas 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 ed9df781 feat(datafusion): integrate upstream Spark-compatible
functions (#1308)
ed9df781 is described below
commit ed9df7814a44299948180aee32a37d44b35469ac
Author: Jingsong Lee <[email protected]>
AuthorDate: Mon Nov 2 15:58:13 2026 +0800
feat(datafusion): integrate upstream Spark-compatible functions (#1308)
* feat(datafusion): integrate upstream Spark-compatible functions
* refactor(datafusion): clarify Spark compatibility hook name
* fix(datafusion): preserve binary inputs in Spark adapters
* fix(datafusion): preserve Spark date part result types
---
Cargo.lock | 35 +-
Cargo.toml | 1 +
DEPENDENCIES.rust.tsv | 1 +
benchmarks/tpcds/DEPENDENCIES.rust.tsv | 4 +
bindings/python/DEPENDENCIES.rust.tsv | 1 +
crates/integrations/datafusion/Cargo.toml | 2 +-
.../integrations/datafusion/DEPENDENCIES.rust.tsv | 1 +
crates/integrations/datafusion/README.md | 13 +
.../datafusion/src/compat_functions.rs | 192 ++---------
.../datafusion/src/expression_compat.rs | 27 --
crates/integrations/datafusion/src/lib.rs | 1 +
.../integrations/datafusion/src/scalar_compat.rs | 211 +-----------
crates/integrations/datafusion/src/scalar_extra.rs | 107 +++---
.../integrations/datafusion/src/spark_functions.rs | 357 +++++++++++++++++++++
crates/integrations/datafusion/src/sql_context.rs | 60 ++++
.../datafusion/tests/compat_functions.rs | 131 ++++++--
.../datafusion/tests/feature_combination.rs | 4 +-
.../datafusion/tests/remaining_compat.rs | 11 +-
.../integrations/datafusion/tests/scalar_compat.rs | 13 +-
.../datafusion/tests/spark_functions.rs | 325 +++++++++++++++++++
docs/src/sql.md | 60 +++-
21 files changed, 1072 insertions(+), 485 deletions(-)
diff --git a/Cargo.lock b/Cargo.lock
index 4b036e3c..2f0999cb 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2270,6 +2270,36 @@ dependencies = [
"parking_lot",
]
+[[package]]
+name = "datafusion-spark"
+version = "54.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "390bb0bf37cb2b95ffd65eacd66f60df50793d1f94097799e416f39477a51957"
+dependencies = [
+ "arrow",
+ "bigdecimal",
+ "chrono",
+ "crc32fast",
+ "datafusion",
+ "datafusion-catalog",
+ "datafusion-common",
+ "datafusion-execution",
+ "datafusion-expr",
+ "datafusion-functions",
+ "datafusion-functions-aggregate",
+ "datafusion-functions-aggregate-common",
+ "datafusion-functions-nested",
+ "log",
+ "num-traits",
+ "percent-encoding",
+ "rand 0.9.5",
+ "serde_json",
+ "sha1 0.11.0",
+ "sha2 0.11.0",
+ "twox-hash",
+ "url",
+]
+
[[package]]
name = "datafusion-sql"
version = "54.0.0"
@@ -4776,6 +4806,7 @@ dependencies = [
"chrono",
"constant_time_eq",
"datafusion",
+ "datafusion-spark",
"flate2",
"futures",
"log",
@@ -4786,7 +4817,6 @@ dependencies = [
"regex",
"serde",
"serde_json",
- "sha2 0.10.9",
"tar",
"tempfile",
"tokio",
@@ -7338,6 +7368,9 @@ name = "twox-hash"
version = "2.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "86a801b3cea342a06d468c8710662aa29e5e05e4f5c0d62f00bbb7f2ad7941c2"
+dependencies = [
+ "rand 0.10.2",
+]
[[package]]
name = "typed-builder"
diff --git a/Cargo.toml b/Cargo.toml
index 0c7e6986..665c914a 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -48,6 +48,7 @@ arrow-select = "58.0"
arrow-string = "58.0"
datafusion = "54.0.0"
datafusion-ffi = "54.0.0"
+datafusion-spark = { version = "54.0.0", features = ["core"] }
paimon = { version = "0.6.0", path = "crates/paimon" }
parquet = "58.0"
constant_time_eq = ">=0.4.0, <0.5.0"
diff --git a/DEPENDENCIES.rust.tsv b/DEPENDENCIES.rust.tsv
index 61b87291..810dccae 100644
--- a/DEPENDENCIES.rust.tsv
+++ b/DEPENDENCIES.rust.tsv
@@ -180,6 +180,7 @@ [email protected] X
[email protected] X
[email protected] X
[email protected] X
[email protected] X
[email protected] X
[email protected] X
[email protected] X
X
diff --git a/benchmarks/tpcds/DEPENDENCIES.rust.tsv
b/benchmarks/tpcds/DEPENDENCIES.rust.tsv
index c437e4d2..e1821d26 100644
--- a/benchmarks/tpcds/DEPENDENCIES.rust.tsv
+++ b/benchmarks/tpcds/DEPENDENCIES.rust.tsv
@@ -67,6 +67,7 @@ [email protected] X
X
[email protected] X
[email protected]
X
[email protected] X
X
[email protected] X
X
[email protected] X
X
[email protected] X
X
[email protected] X
X
@@ -135,6 +136,7 @@ [email protected] X
[email protected] X
[email protected] X
[email protected] X
[email protected] X
[email protected] X
[email protected] X
[email protected] X
X
@@ -346,10 +348,12 @@ [email protected]
X
[email protected] X
X
[email protected] X
X X
[email protected] X
X X
[email protected] X
X
[email protected] X
X
[email protected] X
X
[email protected] X
X
[email protected] X
X
[email protected] X
X
[email protected] X
X
[email protected] X
X
[email protected] X
X
diff --git a/bindings/python/DEPENDENCIES.rust.tsv
b/bindings/python/DEPENDENCIES.rust.tsv
index 12bbf159..642f4d3a 100644
--- a/bindings/python/DEPENDENCIES.rust.tsv
+++ b/bindings/python/DEPENDENCIES.rust.tsv
@@ -146,6 +146,7 @@ [email protected] X
[email protected] X
[email protected] X
[email protected] X
[email protected] X
[email protected] X
[email protected] X
[email protected] X
X
diff --git a/crates/integrations/datafusion/Cargo.toml
b/crates/integrations/datafusion/Cargo.toml
index 9e080f30..4dac5fc0 100644
--- a/crates/integrations/datafusion/Cargo.toml
+++ b/crates/integrations/datafusion/Cargo.toml
@@ -39,13 +39,13 @@ bigdecimal = "0.4"
chrono = "0.4"
constant_time_eq = { workspace = true }
datafusion = { workspace = true }
+datafusion-spark = { 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/DEPENDENCIES.rust.tsv
b/crates/integrations/datafusion/DEPENDENCIES.rust.tsv
index 066e6fc0..9e016eab 100644
--- a/crates/integrations/datafusion/DEPENDENCIES.rust.tsv
+++ b/crates/integrations/datafusion/DEPENDENCIES.rust.tsv
@@ -147,6 +147,7 @@ [email protected] X
[email protected] X
[email protected] X
[email protected] X
[email protected] X
[email protected] X
[email protected] X
[email protected] X
X
diff --git a/crates/integrations/datafusion/README.md
b/crates/integrations/datafusion/README.md
index 92e0ba93..f3efefc4 100644
--- a/crates/integrations/datafusion/README.md
+++ b/crates/integrations/datafusion/README.md
@@ -24,6 +24,19 @@
This crate contains the integration of [Apache
DataFusion](https://datafusion.apache.org/) and [Apache
Paimon](https://paimon.apache.org/).
+## Spark-compatible functions
+
+`SQLContext` enables the matching `datafusion-spark` function packages and
Spark
+EXTRACT/SUBSTRING expression planner by default. Spark functions replace native
+functions with the same name; application registrations made afterward take
+priority. Paimon-specific Variant functions, metadata SQL and compatibility
+extensions remain available.
+
+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
+does not provide every Spark SQL syntax or cast mode.
+
## External engine snapshots
Implement `TableEngineResolver::resolve_table_snapshot` to support
diff --git a/crates/integrations/datafusion/src/compat_functions.rs
b/crates/integrations/datafusion/src/compat_functions.rs
index b049c200..05316c68 100644
--- a/crates/integrations/datafusion/src/compat_functions.rs
+++ b/crates/integrations/datafusion/src/compat_functions.rs
@@ -15,27 +15,22 @@
// 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,
+ Array, ArrayRef, Int64Array, ListBuilder, StringArray, StringBuilder,
};
-use datafusion::arrow::compute::{cast, kernels::numeric};
+use datafusion::arrow::compute::cast;
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,
+ ColumnarValue, Expr, ReturnFieldArgs, ScalarFunctionArgs, ScalarUDF,
ScalarUDFImpl, Signature,
+ TypeSignature, Volatility,
};
use datafusion::prelude::SessionContext;
use regex::Regex;
-use sha2::{Digest, Sha224, Sha256, Sha384, Sha512};
+use std::collections::HashMap;
+use std::sync::Arc;
pub(crate) fn register_compat_functions(ctx: &SessionContext) {
for (name, alias) in [
@@ -43,67 +38,24 @@ pub(crate) fn register_compat_functions(ctx:
&SessionContext) {
("to_date", "date"),
("to_timestamp_millis", "timestamp_millis"),
("to_timestamp", "to_timestamp_ltz"),
+ ("base64", "to_base64"),
] {
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(
+ for kind in [Kind::RegexpExtract, Kind::RegexpExtractAll] {
+ ctx.register_udf(ScalarUDF::from(CompatFunction {
+ kind,
+ signature: 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 }));
+ }));
}
}
@@ -123,6 +75,9 @@ impl ScalarUDFImpl for ConfiguredAlias {
fn signature(&self) -> &Signature {
self.inner.signature()
}
+ fn coerce_types(&self, types: &[DataType]) -> Result<Vec<DataType>> {
+ self.inner.inner().coerce_types(types)
+ }
fn return_type(&self, types: &[DataType]) -> Result<DataType> {
self.inner.inner().return_type(types)
}
@@ -147,139 +102,34 @@ impl ScalarUDFImpl for ConfiguredAlias {
#[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 return_type(&self, _: &[DataType]) -> Result<DataType> {
+ Ok(if self.kind == Kind::RegexpExtractAll {
+ DataType::List(Arc::new(Field::new("item", DataType::Utf8, true)))
+ } else {
+ 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())
- }
- };
+ let output = extract_regex(&arrays, self.kind ==
Kind::RegexpExtractAll)?;
if args
.args
.iter()
diff --git a/crates/integrations/datafusion/src/expression_compat.rs
b/crates/integrations/datafusion/src/expression_compat.rs
index 142c82c7..0f19b9f2 100644
--- a/crates/integrations/datafusion/src/expression_compat.rs
+++ b/crates/integrations/datafusion/src/expression_compat.rs
@@ -36,7 +36,6 @@ pub(crate) fn is_aggregate(name: &str) -> bool {
| "max_by"
| "min_by"
| "arg_max"
- | "collect_list"
| "listagg"
)
}
@@ -181,32 +180,6 @@ fn lower_aggregate(call: &Function, name: &str) ->
Result<Expr> {
}
lowered.name =
ObjectName::from(vec![Ident::new(format!("__paimon_{name}"))]);
}
- "collect_list" => {
- lowered.name = ObjectName::from(vec![Ident::new("array_agg")]);
- if call.null_treatment == Some(NullTreatment::RespectNulls)
- || list.clauses.iter().any(|c| {
- matches!(
- c,
-
FunctionArgumentClause::IgnoreOrRespectNulls(NullTreatment::RespectNulls)
- )
- })
- {
- return Err(error("collect_list does not support RESPECT
NULLS"));
- }
- if let FunctionArguments::List(list) = &mut lowered.args {
- list.clauses
- .retain(|c| !matches!(c,
FunctionArgumentClause::IgnoreOrRespectNulls(_)));
- }
- lowered.null_treatment = Some(NullTreatment::IgnoreNulls);
- let Expr::Function(mut coalesce) = expression("coalesce(NULL,
ARRAY[])")? else {
- unreachable!()
- };
- set_args(
- &mut coalesce,
- vec![Expr::Function(lowered), expression("ARRAY[]")?],
- );
- return Ok(Expr::Function(coalesce));
- }
"listagg" => {
lowered.name = ObjectName::from(vec![Ident::new("string_agg")]);
if args.len() == 1 {
diff --git a/crates/integrations/datafusion/src/lib.rs
b/crates/integrations/datafusion/src/lib.rs
index 19e0ec3b..e9ca118f 100644
--- a/crates/integrations/datafusion/src/lib.rs
+++ b/crates/integrations/datafusion/src/lib.rs
@@ -73,6 +73,7 @@ mod scalar_compat;
mod scalar_extra;
mod selection_aggregate;
mod show_metadata;
+mod spark_functions;
mod sql_context;
mod sql_function;
mod system_tables;
diff --git a/crates/integrations/datafusion/src/scalar_compat.rs
b/crates/integrations/datafusion/src/scalar_compat.rs
index cdea053a..fa663102 100644
--- a/crates/integrations/datafusion/src/scalar_compat.rs
+++ b/crates/integrations/datafusion/src/scalar_compat.rs
@@ -16,14 +16,9 @@
// under the License.
use datafusion::arrow::array::{
- Array, ArrayRef, BinaryBuilder, FixedSizeListArray, Int32Array,
Int64Array, LargeListArray,
- ListArray, ListBuilder, MapArray, StringArray, StringBuilder,
+ Array, ArrayRef, Int32Array, Int64Array, ListBuilder, StringArray,
StringBuilder,
};
-use datafusion::arrow::compute::{
- cast,
- kernels::temporal::{date_part, DatePart},
-};
-use datafusion::arrow::datatypes::{DataType, Field, TimeUnit};
+use datafusion::arrow::datatypes::{DataType, Field};
use datafusion::common::{DataFusionError, Result, ScalarValue};
use datafusion::logical_expr::{
ColumnarValue, ScalarFunctionArgs, ScalarUDF, ScalarUDFImpl, Signature,
TypeSignature,
@@ -38,11 +33,7 @@ use std::sync::Arc;
enum Kind {
Split,
Locate,
- Hex,
- Unhex,
Typeof,
- Size,
- Hour,
}
#[derive(Debug, PartialEq, Eq, Hash)]
struct Function {
@@ -50,26 +41,17 @@ struct Function {
signature: Signature,
}
pub(crate) fn register(ctx: &SessionContext) {
- for kind in [
- Kind::Split,
- Kind::Locate,
- Kind::Hex,
- Kind::Unhex,
- Kind::Typeof,
- Kind::Size,
- Kind::Hour,
- ] {
- let signature = match kind {
- Kind::Split | Kind::Locate => Signature::one_of(
+ for kind in [Kind::Split, Kind::Locate, Kind::Typeof] {
+ let signature = if kind == Kind::Typeof {
+ Signature::any(1, Volatility::Immutable)
+ } else {
+ Signature::one_of(
vec![
TypeSignature::Exact(vec![DataType::Utf8, DataType::Utf8]),
TypeSignature::Exact(vec![DataType::Utf8, DataType::Utf8,
DataType::Int64]),
],
Volatility::Immutable,
- ),
- Kind::Unhex => Signature::exact(vec![DataType::Utf8],
Volatility::Immutable),
- Kind::Typeof => Signature::any(1, Volatility::Immutable),
- _ => Signature::user_defined(Volatility::Immutable),
+ )
};
ctx.register_udf(ScalarUDF::from(Function { kind, signature }));
}
@@ -88,79 +70,17 @@ impl ScalarUDFImpl for Function {
match self.kind {
Kind::Split => "split",
Kind::Locate => "locate",
- Kind::Hex => "hex",
- Kind::Unhex => "unhex",
Kind::Typeof => "typeof",
- Kind::Size => "size",
- Kind::Hour => "hour",
}
}
fn signature(&self) -> &Signature {
&self.signature
}
- fn coerce_types(&self, types: &[DataType]) -> Result<Vec<DataType>> {
- let [ty] = types else {
- return Err(error("Expected one argument"));
- };
- let ty = decoded_type(ty);
- let output = match self.kind {
- Kind::Hex
- if matches!(
- ty,
- DataType::Utf8 | DataType::LargeUtf8 | DataType::Utf8View
| DataType::Null
- ) =>
- {
- DataType::Utf8
- }
- Kind::Hex if ty.is_binary() => DataType::Binary,
- Kind::Hex if ty.is_integer() => ty.clone(),
- Kind::Size
- if matches!(
- ty,
- DataType::List(_)
- | DataType::LargeList(_)
- | DataType::FixedSizeList(_, _)
- | DataType::Map(_, _)
- | DataType::Null
- ) =>
- {
- ty.clone()
- }
- Kind::Hour
- if matches!(
- ty,
- DataType::Date32
- | DataType::Date64
- | DataType::Timestamp(_, _)
- | DataType::Time32(_)
- | DataType::Time64(_)
- ) =>
- {
- ty.clone()
- }
- Kind::Hour
- if matches!(
- ty,
- DataType::Utf8 | DataType::LargeUtf8 | DataType::Utf8View
| DataType::Null
- ) =>
- {
- DataType::Timestamp(TimeUnit::Microsecond, None)
- }
- _ => {
- return Err(DataFusionError::Plan(format!(
- "Unsupported {} input type: {ty}",
- self.name()
- )))
- }
- };
- Ok(vec![output])
- }
fn return_type(&self, _: &[DataType]) -> Result<DataType> {
Ok(match self.kind {
Kind::Split => DataType::List(Arc::new(Field::new("item",
DataType::Utf8, true))),
- Kind::Locate | Kind::Size | Kind::Hour => DataType::Int32,
- Kind::Unhex => DataType::Binary,
- _ => DataType::Utf8,
+ Kind::Locate => DataType::Int32,
+ Kind::Typeof => DataType::Utf8,
})
}
fn invoke_with_args(&self, args: ScalarFunctionArgs) ->
Result<ColumnarValue> {
@@ -171,56 +91,6 @@ impl ScalarUDFImpl for Function {
}
let arrays = ColumnarValue::values_to_arrays(&args.args)?;
let output: ArrayRef = match self.kind {
- Kind::Hour => {
- if matches!(arrays[0].data_type(), DataType::Date32 |
DataType::Date64) {
- Arc::new(Int32Array::from_iter(
- (0..arrays[0].len()).map(|i|
(!arrays[0].is_null(i)).then_some(0)),
- ))
- } else {
- Arc::new(date_part(arrays[0].as_ref(), DatePart::Hour)?)
- }
- }
- Kind::Size => {
- let a = &arrays[0];
- let values = (0..a.len())
- .map(|i| {
- if a.is_null(i) {
- return Ok(None);
- }
- let n = match a.data_type() {
- DataType::List(_) => {
- a.as_any()
- .downcast_ref::<ListArray>()
- .unwrap()
- .value_length(i) as i64
- }
- DataType::LargeList(_) => a
- .as_any()
- .downcast_ref::<LargeListArray>()
- .unwrap()
- .value_length(i),
- DataType::FixedSizeList(_, _) => {
- a.as_any()
- .downcast_ref::<FixedSizeListArray>()
- .unwrap()
- .value_length() as i64
- }
- DataType::Map(_, _) => {
- a.as_any()
- .downcast_ref::<MapArray>()
- .unwrap()
- .value_length(i) as i64
- }
- DataType::Null => return Ok(None),
- _ => return Err(error("size expects an array or
map")),
- };
- i32::try_from(n)
- .map(Some)
- .map_err(|_| error("Collection size exceeds INT
range"))
- })
- .collect::<Result<Vec<_>>>()?;
- Arc::new(Int32Array::from(values))
- }
Kind::Split => {
let text =
arrays[0].as_any().downcast_ref::<StringArray>().unwrap();
let patterns =
arrays[1].as_any().downcast_ref::<StringArray>().unwrap();
@@ -312,67 +182,6 @@ impl ScalarUDFImpl for Function {
}
Arc::new(Int32Array::from(values))
}
- Kind::Unhex => {
- let text =
arrays[0].as_any().downcast_ref::<StringArray>().unwrap();
- let mut output = BinaryBuilder::new();
- for value in text.iter() {
- let Some(value) = value else {
- output.append_null();
- continue;
- };
- if !value.bytes().all(|byte| byte.is_ascii_hexdigit()) {
- output.append_null();
- continue;
- }
- let value = if value.len() % 2 == 1 {
- format!("0{value}")
- } else {
- value.to_string()
- };
- let decoded = (0..value.len())
- .step_by(2)
- .map(|i| u8::from_str_radix(&value[i..i + 2], 16))
- .collect::<std::result::Result<Vec<_>, _>>();
- match decoded {
- Ok(bytes) => output.append_value(bytes),
- Err(_) => output.append_null(),
- }
- }
- Arc::new(output.finish())
- }
- Kind::Hex => {
- let mut output = StringBuilder::new();
- for i in 0..arrays[0].len() {
- if arrays[0].is_null(i) {
- output.append_null();
- continue;
- }
- let scalar =
ScalarValue::try_from_array(arrays[0].as_ref(), i)?;
- let text = if let Some(Some(s)) = scalar.try_as_str() {
- s.as_bytes()
- .iter()
- .map(|b| format!("{b:02X}"))
- .collect::<String>()
- } else if let ScalarValue::Binary(Some(bytes)) = scalar {
- bytes.iter().map(|b|
format!("{b:02X}")).collect::<String>()
- } else {
- let value = cast(&arrays[0].slice(i, 1),
&DataType::UInt64)?;
- let unsigned = value
- .as_any()
-
.downcast_ref::<datafusion::arrow::array::UInt64Array>()
- .unwrap();
- if unsigned.is_null(0) {
- let value = cast(&arrays[0].slice(i, 1),
&DataType::Int64)?;
- let signed =
value.as_any().downcast_ref::<Int64Array>().unwrap();
- format!("{:X}", signed.value(0))
- } else {
- format!("{:X}", unsigned.value(0))
- }
- };
- output.append_value(text);
- }
- Arc::new(output.finish())
- }
Kind::Typeof => unreachable!(),
};
if args
diff --git a/crates/integrations/datafusion/src/scalar_extra.rs
b/crates/integrations/datafusion/src/scalar_extra.rs
index 3fc7161f..6807df74 100644
--- a/crates/integrations/datafusion/src/scalar_extra.rs
+++ b/crates/integrations/datafusion/src/scalar_extra.rs
@@ -18,13 +18,16 @@
use chrono::{Datelike, Months, NaiveDate, NaiveDateTime, TimeZone};
use datafusion::arrow::array::timezone::Tz;
use datafusion::arrow::array::{
- Array, ArrayRef, BooleanArray, BooleanBuilder, Date32Array, Int64Array,
Int64Builder,
- NullArray, StringArray, StringBuilder, TimestampMicrosecondArray,
+ Array, ArrayRef, BooleanArray, BooleanBuilder, Int64Array, Int64Builder,
NullArray,
+ StringArray, StringBuilder, TimestampMicrosecondArray,
};
-use datafusion::arrow::datatypes::{DataType, TimeUnit};
+use datafusion::arrow::datatypes::{DataType, Field, FieldRef, TimeUnit};
use datafusion::common::{DataFusionError, Result, ScalarValue};
+use datafusion::logical_expr::simplify::{ExprSimplifyResult, SimplifyContext};
+use datafusion::logical_expr::type_coercion::functions::fields_with_udf;
use datafusion::logical_expr::{
- ColumnarValue, ScalarFunctionArgs, ScalarUDF, ScalarUDFImpl, Signature,
Volatility,
+ ColumnarValue, Expr, ReturnFieldArgs, ScalarFunctionArgs, ScalarUDF,
ScalarUDFImpl, Signature,
+ Volatility,
};
use datafusion::prelude::SessionContext;
use regex::{Regex, RegexBuilder};
@@ -102,7 +105,19 @@ impl ScalarUDFImpl for Extra {
out
}
(Kind::Conv, 3) => vec![DataType::Utf8, DataType::Int64,
DataType::Int64],
- (Kind::DateDiff, 2) => vec![DataType::Date32, DataType::Date32],
+ (Kind::DateDiff, 2) => {
+ let fields = types
+ .iter()
+ .map(|ty| Arc::new(Field::new("arg", ty.clone(), true)))
+ .collect::<Vec<_>>();
+ fields_with_udf(
+ &fields,
+ datafusion_spark::function::datetime::date_diff().as_ref(),
+ )?
+ .iter()
+ .map(|field| field.data_type().clone())
+ .collect()
+ }
(Kind::DateDiff, 3) => vec![
DataType::Utf8,
DataType::Timestamp(TimeUnit::Microsecond, None),
@@ -130,16 +145,46 @@ impl ScalarUDFImpl for Extra {
}
})
}
- fn return_type(&self, _: &[DataType]) -> Result<DataType> {
+ fn return_type(&self, types: &[DataType]) -> Result<DataType> {
Ok(match self.kind {
Kind::Assert => DataType::Null,
Kind::Conv => DataType::Utf8,
+ Kind::DateDiff if types.len() == 2 => DataType::Int32,
Kind::DateDiff => DataType::Int64,
Kind::ConvertTz => DataType::Timestamp(TimeUnit::Microsecond,
None),
Kind::Like => DataType::Boolean,
})
}
+ fn return_field_from_args(&self, args: ReturnFieldArgs) ->
Result<FieldRef> {
+ if self.kind == Kind::DateDiff && args.arg_fields.len() == 2 {
+ return datafusion_spark::function::datetime::date_diff()
+ .inner()
+ .return_field_from_args(args);
+ }
+ let types = args
+ .arg_fields
+ .iter()
+ .map(|field| field.data_type().clone())
+ .collect::<Vec<_>>();
+ Ok(Arc::new(Field::new(
+ self.name(),
+ self.return_type(&types)?,
+ true,
+ )))
+ }
+ fn simplify(&self, args: Vec<Expr>, info: &SimplifyContext) ->
Result<ExprSimplifyResult> {
+ if self.kind == Kind::DateDiff && args.len() == 2 {
+ datafusion_spark::function::datetime::date_diff()
+ .inner()
+ .simplify(args, info)
+ } else {
+ Ok(ExprSimplifyResult::Original(args))
+ }
+ }
fn invoke_with_args(&self, args: ScalarFunctionArgs) ->
Result<ColumnarValue> {
+ if self.kind == Kind::DateDiff && args.args.len() == 2 {
+ return
datafusion_spark::function::datetime::date_diff().invoke_with_args(args);
+ }
let arrays = ColumnarValue::values_to_arrays(&args.args)?;
let len = arrays[0].len();
let out: ArrayRef = match self.kind {
@@ -176,39 +221,25 @@ impl ScalarUDFImpl for Extra {
}
Kind::DateDiff => {
let mut output = Int64Builder::new();
- if arrays.len() == 2 {
- let end =
arrays[0].as_any().downcast_ref::<Date32Array>().unwrap();
- let start =
arrays[1].as_any().downcast_ref::<Date32Array>().unwrap();
- for row in 0..len {
- if end.is_null(row) || start.is_null(row) {
- output.append_null();
- } else {
- output.append_value(
- i64::from(end.value(row)) -
i64::from(start.value(row)),
- );
- }
- }
- } else {
- let unit =
arrays[0].as_any().downcast_ref::<StringArray>().unwrap();
- let start = arrays[1]
- .as_any()
- .downcast_ref::<TimestampMicrosecondArray>()
- .unwrap();
- let end = arrays[2]
- .as_any()
- .downcast_ref::<TimestampMicrosecondArray>()
- .unwrap();
- for row in 0..len {
- if arrays.iter().any(|a| a.is_null(row)) {
- output.append_null();
- continue;
- }
- output.append_value(date_diff(
- unit.value(row),
- start.value(row),
- end.value(row),
- )?);
+ let unit =
arrays[0].as_any().downcast_ref::<StringArray>().unwrap();
+ let start = arrays[1]
+ .as_any()
+ .downcast_ref::<TimestampMicrosecondArray>()
+ .unwrap();
+ let end = arrays[2]
+ .as_any()
+ .downcast_ref::<TimestampMicrosecondArray>()
+ .unwrap();
+ for row in 0..len {
+ if arrays.iter().any(|a| a.is_null(row)) {
+ output.append_null();
+ continue;
}
+ output.append_value(date_diff(
+ unit.value(row),
+ start.value(row),
+ end.value(row),
+ )?);
}
Arc::new(output.finish())
}
diff --git a/crates/integrations/datafusion/src/spark_functions.rs
b/crates/integrations/datafusion/src/spark_functions.rs
new file mode 100644
index 00000000..a553a381
--- /dev/null
+++ b/crates/integrations/datafusion/src/spark_functions.rs
@@ -0,0 +1,357 @@
+// 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::{new_empty_array, ArrayRef, BooleanArray};
+use datafusion::arrow::compute::filter;
+use datafusion::arrow::datatypes::{DataType, Field, FieldRef, TimeUnit};
+use datafusion::common::config::ConfigOptions;
+use datafusion::common::utils::SingleRowListArrayBuilder;
+use datafusion::common::{DataFusionError, Result, ScalarValue};
+use datafusion::logical_expr::expr::ScalarFunction;
+use datafusion::logical_expr::function::{AccumulatorArgs, StateFieldsArgs};
+use datafusion::logical_expr::planner::{ExprPlanner, PlannerResult};
+use datafusion::logical_expr::simplify::{ExprSimplifyResult, SimplifyContext};
+use datafusion::logical_expr::type_coercion::functions::fields_with_udf;
+use datafusion::logical_expr::{
+ Accumulator, AggregateUDF, AggregateUDFImpl, ColumnarValue, EmitTo, Expr,
GroupsAccumulator,
+ ReturnFieldArgs, ScalarFunctionArgs, ScalarUDF, ScalarUDFImpl, Signature,
+};
+use datafusion::prelude::SessionContext;
+use std::sync::Arc;
+
+// Adapt input and return types while retaining upstream evaluation and
simplification.
+pub(crate) fn apply_compatibility_fixes(ctx: &SessionContext) {
+ ctx.register_udf(date_part().as_ref().clone());
+ for name in [
+ "base64",
+ "sha2",
+ "date_add",
+ "date_sub",
+ "factorial",
+ "mod",
+ "pmod",
+ "hex",
+ "unhex",
+ "hour",
+ "size",
+ ] {
+ let inner = Arc::clone(&ctx.state().scalar_functions()[name]);
+ ctx.register_udf(ScalarUDF::from(Inputs::new(inner)));
+ }
+ for name in ["collect_list", "collect_set", "try_sum", "avg"] {
+ let inner = Arc::clone(&ctx.state().aggregate_functions()[name]);
+ ctx.register_udaf(AggregateUDF::from(AggregateInputs { inner }));
+ }
+}
+
+fn date_part() -> Arc<ScalarUDF> {
+ Arc::new(ScalarUDF::from(DatePart {
+ inner: datafusion_spark::function::datetime::date_part(),
+ }))
+}
+
+#[derive(Debug)]
+pub(crate) struct DatePartPlanner;
+
+impl ExprPlanner for DatePartPlanner {
+ fn plan_extract(&self, args: Vec<Expr>) ->
Result<PlannerResult<Vec<Expr>>> {
+ Ok(PlannerResult::Planned(Expr::ScalarFunction(
+ ScalarFunction::new_udf(date_part(), args),
+ )))
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+struct DatePart {
+ inner: Arc<ScalarUDF>,
+}
+
+impl ScalarUDFImpl for DatePart {
+ fn name(&self) -> &str {
+ self.inner.name()
+ }
+ fn aliases(&self) -> &[String] {
+ self.inner.aliases()
+ }
+ 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> {
+ // Spark 54 declares every part as Int32 before delegating to this
native UDF.
+ // Use its actual field so coercion preserves epoch fractions and
nanoseconds.
+ datafusion::functions::datetime::date_part()
+ .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)
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+struct AggregateInputs {
+ inner: Arc<AggregateUDF>,
+}
+impl AggregateUDFImpl for AggregateInputs {
+ fn name(&self) -> &str {
+ self.inner.name()
+ }
+ fn signature(&self) -> &Signature {
+ self.inner.signature()
+ }
+ fn coerce_types(&self, types: &[DataType]) -> Result<Vec<DataType>> {
+ self.inner.inner().coerce_types(types)
+ }
+ fn return_type(&self, types: &[DataType]) -> Result<DataType> {
+ self.inner.inner().return_type(types)
+ }
+ fn return_field(&self, fields: &[FieldRef]) -> Result<FieldRef> {
+ self.inner.return_field(fields)
+ }
+ fn accumulator(&self, args: AccumulatorArgs) -> Result<Box<dyn
Accumulator>> {
+ match self.name() {
+ "collect_list" if !args.order_bys.is_empty() =>
Err(DataFusionError::NotImplemented(
+ "collect_list ORDER BY is not supported by DataFusion Spark
54".into(),
+ )),
+ "collect_list" if args.is_distinct => {
+
datafusion_spark::function::aggregate::collect_set().accumulator(args)
+ }
+ "try_sum" if args.is_distinct =>
Err(DataFusionError::NotImplemented(
+ "try_sum DISTINCT is not supported by DataFusion Spark
54".into(),
+ )),
+ _ => self.inner.accumulator(args),
+ }
+ }
+ fn state_fields(&self, args: StateFieldsArgs) -> Result<Vec<FieldRef>> {
+ if self.name() == "collect_list" && args.is_distinct {
+
datafusion_spark::function::aggregate::collect_set().state_fields(args)
+ } else {
+ self.inner.state_fields(args)
+ }
+ }
+ fn default_value(&self, ty: &DataType) -> Result<ScalarValue> {
+ if matches!(self.name(), "collect_list" | "collect_set") {
+ let DataType::List(field) = ty else {
+ return Err(DataFusionError::Internal(
+ "Spark collection return type must be a list".into(),
+ ));
+ };
+ Ok(
+
SingleRowListArrayBuilder::new(new_empty_array(field.data_type()))
+ .build_list_scalar(),
+ )
+ } else {
+ let value = self.inner.inner().default_value(ty)?;
+ if value == ScalarValue::Null {
+ ScalarValue::try_new_null(ty)
+ } else {
+ Ok(value)
+ }
+ }
+ }
+ fn reverse_expr(&self) -> datafusion::logical_expr::ReversedUDAF {
+ self.inner.inner().reverse_expr()
+ }
+ fn groups_accumulator_supported(&self, args: AccumulatorArgs) -> bool {
+ self.inner.groups_accumulator_supported(args)
+ }
+ fn create_groups_accumulator(
+ &self,
+ args: AccumulatorArgs,
+ ) -> Result<Box<dyn GroupsAccumulator>> {
+ Ok(Box::new(FilteredGroups(
+ self.inner.create_groups_accumulator(args)?,
+ )))
+ }
+}
+
+// Spark 54 AVG ignores its grouped FILTER argument. Pre-filter its
already-evaluated
+// arrays and group indices, keeping the upstream vectorized accumulator and
state.
+struct FilteredGroups(Box<dyn GroupsAccumulator>);
+impl FilteredGroups {
+ fn filter(
+ values: &[ArrayRef],
+ groups: &[usize],
+ predicate: &BooleanArray,
+ ) -> Result<(Vec<ArrayRef>, Vec<usize>)> {
+ let arrays = values
+ .iter()
+ .map(|value| filter(value.as_ref(), predicate).map_err(Into::into))
+ .collect::<Result<Vec<_>>>()?;
+ let groups = groups
+ .iter()
+ .zip(predicate.iter())
+ .filter_map(|(group, pass)| (pass == Some(true)).then_some(*group))
+ .collect();
+ Ok((arrays, groups))
+ }
+}
+impl GroupsAccumulator for FilteredGroups {
+ fn supports_convert_to_state(&self) -> bool {
+ self.0.supports_convert_to_state()
+ }
+ fn convert_to_state(
+ &self,
+ values: &[ArrayRef],
+ predicate: Option<&BooleanArray>,
+ ) -> Result<Vec<ArrayRef>> {
+ self.0.convert_to_state(values, predicate)
+ }
+ fn update_batch(
+ &mut self,
+ values: &[ArrayRef],
+ groups: &[usize],
+ predicate: Option<&BooleanArray>,
+ total: usize,
+ ) -> Result<()> {
+ if let Some(predicate) = predicate {
+ let (values, groups) = Self::filter(values, groups, predicate)?;
+ self.0.update_batch(&values, &groups, None, total)
+ } else {
+ self.0.update_batch(values, groups, None, total)
+ }
+ }
+ fn merge_batch(
+ &mut self,
+ values: &[ArrayRef],
+ groups: &[usize],
+ predicate: Option<&BooleanArray>,
+ total: usize,
+ ) -> Result<()> {
+ if let Some(predicate) = predicate {
+ let (values, groups) = Self::filter(values, groups, predicate)?;
+ self.0.merge_batch(&values, &groups, None, total)
+ } else {
+ self.0.merge_batch(values, groups, None, total)
+ }
+ }
+ fn evaluate(&mut self, emit: EmitTo) -> Result<ArrayRef> {
+ self.0.evaluate(emit)
+ }
+ fn state(&mut self, emit: EmitTo) -> Result<Vec<ArrayRef>> {
+ self.0.state(emit)
+ }
+ fn size(&self) -> usize {
+ self.0.size() + std::mem::size_of::<Self>()
+ }
+}
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+struct Inputs {
+ inner: Arc<ScalarUDF>,
+ signature: Signature,
+}
+impl Inputs {
+ fn new(inner: Arc<ScalarUDF>) -> Self {
+ Self {
+ signature: Signature::user_defined(inner.signature().volatility),
+ inner,
+ }
+ }
+}
+fn decoded(mut ty: &DataType) -> &DataType {
+ while let DataType::Dictionary(_, value) = ty {
+ ty = value;
+ }
+ ty
+}
+impl ScalarUDFImpl for Inputs {
+ fn name(&self) -> &str {
+ self.inner.name()
+ }
+ fn aliases(&self) -> &[String] {
+ self.inner.aliases()
+ }
+ fn signature(&self) -> &Signature {
+ &self.signature
+ }
+ fn coerce_types(&self, types: &[DataType]) -> Result<Vec<DataType>> {
+ let mut types = types
+ .iter()
+ .map(|ty| decoded(ty).clone())
+ .collect::<Vec<_>>();
+ match (self.name(), types.as_mut_slice()) {
+ ("hex", [value]) if *value == DataType::BinaryView => *value =
DataType::Binary,
+ ("sha2", [value, _]) if matches!(value,
DataType::FixedSizeBinary(_)) => {
+ *value = DataType::Binary;
+ }
+ ("hex" | "unhex", [value]) if *value == DataType::Null => *value =
DataType::Utf8,
+ ("hour", [value]) if *value == DataType::Null => {
+ *value = DataType::Timestamp(TimeUnit::Microsecond, None)
+ }
+ ("size", [value]) if *value == DataType::Null => {
+ *value = DataType::List(Arc::new(Field::new("item",
DataType::Null, true)))
+ }
+ ("date_add" | "date_sub", [date, days]) => {
+ if matches!(
+ date,
+ DataType::Utf8 | DataType::Utf8View | DataType::LargeUtf8
| DataType::Null
+ ) {
+ *date = DataType::Date32;
+ }
+ if matches!(days, DataType::Int64 | DataType::Null) {
+ *days = DataType::Int32;
+ }
+ }
+ ("factorial", [value]) if *value == DataType::Int64 => *value =
DataType::Int32,
+ ("mod" | "pmod", [left, right]) => {
+ if *left == DataType::Null {
+ *left = if *right == DataType::Null {
+ DataType::Int64
+ } else {
+ right.clone()
+ };
+ }
+ if *right == DataType::Null {
+ *right = left.clone();
+ }
+ }
+ _ => {}
+ }
+ let fields = types
+ .iter()
+ .map(|ty| Arc::new(Field::new("arg", ty.clone(), true)))
+ .collect::<Vec<_>>();
+ Ok(fields_with_udf(&fields, self.inner.as_ref())?
+ .iter()
+ .map(|field| field.data_type().clone())
+ .collect())
+ }
+ 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::new(Arc::new(inner))))
+ }
+}
diff --git a/crates/integrations/datafusion/src/sql_context.rs
b/crates/integrations/datafusion/src/sql_context.rs
index 979f6aef..e73947bf 100644
--- a/crates/integrations/datafusion/src/sql_context.rs
+++ b/crates/integrations/datafusion/src/sql_context.rs
@@ -76,6 +76,7 @@ use datafusion::sql::sqlparser::dialect::GenericDialect;
use datafusion::sql::sqlparser::keywords::Keyword;
use datafusion::sql::sqlparser::parser::Parser;
use datafusion::sql::sqlparser::tokenizer::{Token, Tokenizer};
+use datafusion_spark::SessionStateBuilderSpark;
use futures::StreamExt;
use paimon::catalog::{parse_object_name, Catalog, Identifier,
ParsedObjectName};
use paimon::spec::{
@@ -157,6 +158,7 @@ impl SQLContextBuilder {
let mut state_builder = SessionStateBuilder::new()
.with_config(crate::lateral_vector_search::session_config())
.with_default_features()
+ .with_spark_features()
.with_type_planner(Arc::new(crate::binary_cast::BinaryTypePlanner))
.with_relation_planners(vec![
Arc::new(crate::lateral_views::ExplodeRelationPlanner),
@@ -169,8 +171,14 @@ 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.
+ state_builder
+ .expr_planners()
+ .get_or_insert_with(Vec::new)
+ .insert(0, Arc::new(crate::spark_functions::DatePartPlanner));
let state = state_builder.build();
let mut ctx = SessionContext::new_with_state(state);
+ crate::spark_functions::apply_compatibility_fixes(&ctx);
crate::compat_functions::register_compat_functions(&ctx);
crate::binary_cast::register(&ctx);
crate::lateral_views::register(&ctx);
@@ -4600,6 +4608,58 @@ mod tests {
));
}
+ #[tokio::test]
+ async fn
spark_functions_resolve_locally_in_persistent_functions_and_views() {
+ use datafusion::common::ScalarValue;
+ let catalog = Arc::new(MockCatalog::new());
+ catalog.denied_functions.lock().unwrap().extend([
+ "pmod".to_string(),
+ "try_sum".to_string(),
+ "collect_set".to_string(),
+ ]);
+ let ctx = make_sql_context(catalog.clone()).await;
+ ctx.sql("CREATE FUNCTION spark_adjust(x BIGINT) RETURNS BIGINT
LANGUAGE SQL IMMUTABLE RETURN x + pmod(x,3)").await.unwrap();
+ let function = catalog
+ .get_function(&Identifier::new("default", "spark_adjust"))
+ .await
+ .unwrap();
+ assert!(function
+ .definition("datafusion")
+ .unwrap()
+ .sql()
+ .unwrap()
+ .contains("pmod"));
+ ctx.sql("CREATE VIEW spark_total AS SELECT try_sum(spark_adjust(v)) AS
answer FROM (VALUES (1),(2),(2)) t(v)").await.unwrap();
+ let view = catalog
+ .get_view(&Identifier::new("default", "spark_total"))
+ .await
+ .unwrap();
+ assert!(view.query_for("datafusion").contains("try_sum"));
+ assert!(view.query_for("datafusion").contains("spark_adjust"));
+ let batches = ctx
+ .sql("SELECT answer FROM spark_total")
+ .await
+ .unwrap()
+ .collect()
+ .await
+ .unwrap();
+ assert_eq!(
+ ScalarValue::try_from_array(batches[0].column(0), 0).unwrap(),
+ ScalarValue::Int64(Some(10))
+ );
+ let batches = ctx
+ .sql("SELECT array_length(collect_set(v)) FROM (VALUES
(1),(1),(2)) t(v)")
+ .await
+ .unwrap()
+ .collect()
+ .await
+ .unwrap();
+ assert_eq!(
+ ScalarValue::try_from_array(batches[0].column(0), 0).unwrap(),
+ ScalarValue::UInt64(Some(2))
+ );
+ }
+
#[tokio::test]
async fn
aggregate_compatibility_preserves_persistent_function_and_view_sql() {
let catalog = Arc::new(MockCatalog::new());
diff --git a/crates/integrations/datafusion/tests/compat_functions.rs
b/crates/integrations/datafusion/tests/compat_functions.rs
index 90c80ea0..825c33d0 100644
--- a/crates/integrations/datafusion/tests/compat_functions.rs
+++ b/crates/integrations/datafusion/tests/compat_functions.rs
@@ -64,49 +64,37 @@ async fn
mod_preserves_numeric_remainder_and_null_semantics() {
],
)
.await;
- assert_error(&ctx, "mod(1, 0)", "zero").await;
+ assert_true(&ctx, &["mod(1, 0) IS NULL"]).await;
}
#[tokio::test]
-async fn mod_matches_native_remainder_decimal_coercion() {
+async fn mod_uses_upstream_spark_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}"
- );
- }
+ let batches = ctx
+ .sql("SELECT mod(CAST(5.55 AS DECIMAL(10,2)),CAST(2.1 AS
DECIMAL(4,1)))")
+ .await
+ .unwrap()
+ .collect()
+ .await
+ .unwrap();
+ assert_eq!(
+ ScalarValue::try_from_array(batches[0].column(0), 0).unwrap(),
+ ScalarValue::Decimal128(Some(135), 10, 2)
+ );
}
#[tokio::test]
-async fn date_sub_null_days_do_not_parse_rejected_strings() {
+async fn date_sub_null_days_propagate_through_date_coercion() {
let ctx = SQLContext::new();
assert_true(
&ctx,
- &["date_sub('not-a-date', CAST(NULL AS BIGINT)) IS NULL"],
+ &["date_sub('2024-03-01', 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)",
+ ('2024-03-01', CAST(NULL AS BIGINT)), ('2024-03-01', CAST(1 AS
BIGINT))) AS t(d, days)",
)
.await
.unwrap()
@@ -193,7 +181,7 @@ async fn
date_sub_handles_leap_days_negative_days_and_overflow() {
assert_error(
&ctx,
"date_sub(DATE '2024-03-01', 9223372036854775807)",
- "overflow",
+ "Int32",
)
.await;
}
@@ -237,6 +225,91 @@ async fn
binary_encoding_preserves_non_utf8_bytes_across_arrow_types() {
]).await;
}
+#[tokio::test]
+async fn hex_preserves_binary_view_bytes_and_nulls() {
+ use datafusion::arrow::datatypes::DataType;
+
+ let ctx = SQLContext::new();
+ assert_true(
+ &ctx,
+ &["hex(arrow_cast(decode('00ff', 'hex'), 'BinaryView')) = '00FF'"],
+ )
+ .await;
+ assert_dictionary_binary_encoding(&ctx, DataType::BinaryView,
"hex(bytes)", "00FF").await;
+}
+
+#[tokio::test]
+async fn sha2_preserves_fixed_size_binary_bytes_and_nulls() {
+ use datafusion::arrow::datatypes::DataType;
+
+ let ctx = SQLContext::new();
+ let expected =
"06eb7d6a69ee19e5fbdf749018d3d2abfa04bcbd1365db312eb86dc7169389b8";
+ assert_true(
+ &ctx,
+ &[&format!(
+ "sha2(arrow_cast(decode('00ff', 'hex'), 'FixedSizeBinary(2)'),
256) = '{expected}'"
+ )],
+ )
+ .await;
+ assert_dictionary_binary_encoding(
+ &ctx,
+ DataType::FixedSizeBinary(2),
+ "sha2(bytes, 256)",
+ expected,
+ )
+ .await;
+}
+
+async fn assert_dictionary_binary_encoding(
+ ctx: &SQLContext,
+ data_type: datafusion::arrow::datatypes::DataType,
+ expression: &str,
+ expected: &str,
+) {
+ use datafusion::arrow::array::{
+ Array, ArrayRef, BinaryArray, DictionaryArray, Int8Array, RecordBatch,
+ };
+ use datafusion::arrow::compute::cast;
+ use datafusion::arrow::datatypes::{Field, Int8Type, Schema};
+ use std::sync::Arc;
+
+ let bytes: ArrayRef = Arc::new(BinaryArray::from(vec![Some(&[0_u8,
255][..]), None]));
+ let values = cast(&bytes, &data_type).unwrap();
+ 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(&format!("SELECT {expression} FROM encoded_bytes"))
+ .await
+ .unwrap()
+ .collect()
+ .await
+ .unwrap();
+ let batch = &batches[0];
+ assert_eq!(batch.num_rows(), 3);
+ assert_eq!(
+ ScalarValue::try_from_array(batch.column(0), 0).unwrap(),
+ ScalarValue::Utf8(Some(expected.into()))
+ );
+ for row in [1, 2] {
+ assert_eq!(
+ ScalarValue::try_from_array(batch.column(0), row).unwrap(),
+ ScalarValue::Utf8(None)
+ );
+ }
+}
+
#[tokio::test]
async fn binary_encoding_preserves_dictionary_bytes_and_value_nulls() {
use datafusion::arrow::array::{Array, BinaryArray, DictionaryArray,
Int8Array, RecordBatch};
diff --git a/crates/integrations/datafusion/tests/feature_combination.rs
b/crates/integrations/datafusion/tests/feature_combination.rs
index 0896e620..994a9b84 100644
--- a/crates/integrations/datafusion/tests/feature_combination.rs
+++ b/crates/integrations/datafusion/tests/feature_combination.rs
@@ -40,7 +40,7 @@ async fn six_sql_extensions_work_together() {
table.tag_manager().get("v1").await.unwrap().unwrap().id(),
1
);
- let batches=ctx.sql("SELECT
id,p.pos,p.val,hex(b),typeof(p.val),size(split(txt,',')),hour(TIME '12:00:00')
FROM default.events LATERAL VIEW posexplode_outer(split(txt,',')) p AS pos,val
WHERE p.val RLIKE '^a$' OR p.val IS NULL ORDER BY
id,p.pos").await.unwrap().collect().await.unwrap();
+ let batches=ctx.sql("SELECT
id,p.pos,p.val,hex(b),typeof(p.val),size(split(txt,',')),hour(TIMESTAMP
'1970-01-01 12:00:00') FROM default.events LATERAL VIEW
posexplode_outer(split(txt,',')) p AS pos,val WHERE p.val RLIKE '^a$' OR p.val
IS NULL ORDER BY id,p.pos").await.unwrap().collect().await.unwrap();
let rows = batches
.iter()
.flat_map(|b| {
@@ -59,7 +59,7 @@ async fn six_sql_extensions_work_together() {
rows,
vec![
vec!["1", "0", "a", "78790000", "string", "2", "12"],
- vec!["2", "NULL", "NULL", "NULL", "string", "NULL", "12"]
+ vec!["2", "NULL", "NULL", "NULL", "string", "-1", "12"]
]
);
}
diff --git a/crates/integrations/datafusion/tests/remaining_compat.rs
b/crates/integrations/datafusion/tests/remaining_compat.rs
index e0318d00..85034601 100644
--- a/crates/integrations/datafusion/tests/remaining_compat.rs
+++ b/crates/integrations/datafusion/tests/remaining_compat.rs
@@ -429,7 +429,16 @@ async fn
compatible_aggregates_preserve_null_filter_and_ordering_contracts() {
assert_eq!(rows(&ctx,"SELECT k,count_if(p) OVER (ORDER BY k ROWS BETWEEN
UNBOUNDED PRECEDING AND CURRENT ROW) FROM (VALUES (1,TRUE),(2,FALSE),(3,TRUE))
t(k,p) ORDER BY k").await,vec![vec!["1","1"],vec!["2","1"],vec!["3","2"]]);
rejects(&ctx, "SELECT approx_count_distinct(1,0.0001)").await;
rejects(&ctx, "SELECT first(1, 7)").await;
- assert_eq!(rows(&ctx,"SELECT to_json(collect_list(v IGNORE
NULLS)),to_json(collect_list(v) IGNORE NULLS) FROM (VALUES (1),(NULL))
t(v)").await,vec![vec!["[1]","[1]"]]);
+ rejects(
+ &ctx,
+ "SELECT collect_list(v IGNORE NULLS) FROM (VALUES (1),(NULL)) t(v)",
+ )
+ .await;
+ rejects(
+ &ctx,
+ "SELECT collect_list(v) IGNORE NULLS FROM (VALUES (1),(NULL)) t(v)",
+ )
+ .await;
rejects(
&ctx,
"SELECT collect_list(v) RESPECT NULLS FROM (VALUES (1),(NULL)) t(v)",
diff --git a/crates/integrations/datafusion/tests/scalar_compat.rs
b/crates/integrations/datafusion/tests/scalar_compat.rs
index 11e5f7a7..1271f07f 100644
--- a/crates/integrations/datafusion/tests/scalar_compat.rs
+++ b/crates/integrations/datafusion/tests/scalar_compat.rs
@@ -31,7 +31,7 @@ async fn common_scalar_names_have_explicit_semantics() {
"unhex('f') = decode('0f','hex')",
"unhex('zz') IS NULL",
"size(ARRAY[1,NULL,3]) = 3",
- "size(CAST(NULL AS INT[])) IS NULL",
+ "size(CAST(NULL AS INT[])) = -1",
"hour(TIMESTAMP '2026-10-29 12:34:56') = 12",
] {
let batches = ctx
@@ -75,9 +75,8 @@ async fn
scalar_boundaries_cover_nulls_encoding_and_temporal_types() {
"typeof(CAST(NULL AS DECIMAL(10,2))) = 'decimal(10,2)'",
"size(map(ARRAY[1,2], ARRAY['a',NULL])) = 2",
"size(ARRAY[]) = 0",
- "size(NULL) IS NULL",
- "hour(TIME '12:34:56') = 12",
- "hour(DATE '2026-10-29') = 0",
+ "size(CAST(NULL AS INT[])) = -1",
+ "hour(CAST(DATE '2026-10-29' AS TIMESTAMP)) = 0",
"hour(NULL) IS NULL",
] {
let batches = ctx
@@ -119,7 +118,7 @@ async fn scalar_functions_evaluate_row_inputs() {
}
#[tokio::test]
-async fn
hour_uses_timestamp_timezone_metadata_and_hex_preserves_unsigned_values() {
+async fn
hour_uses_timestamp_timezone_metadata_and_hex_accepts_unsigned_bigint_range() {
use datafusion::arrow::{
array::{Array, ArrayRef, RecordBatch, TimestampMillisecondArray,
UInt64Array},
datatypes::{Field, Schema},
@@ -128,7 +127,7 @@ async fn
hour_uses_timestamp_timezone_metadata_and_hex_preserves_unsigned_values
let ts = Arc::new(
TimestampMillisecondArray::from(vec![Some(0),
None]).with_timezone("Asia/Shanghai"),
) as ArrayRef;
- let nums = Arc::new(UInt64Array::from(vec![Some(u64::MAX), None])) as
ArrayRef;
+ let nums = Arc::new(UInt64Array::from(vec![Some(i64::MAX as u64), None]))
as ArrayRef;
let batch = RecordBatch::try_new(
Arc::new(Schema::new(vec![
Field::new("ts", ts.data_type().clone(), true),
@@ -152,7 +151,7 @@ async fn
hour_uses_timestamp_timezone_metadata_and_hex_preserves_unsigned_values
);
assert_eq!(
ScalarValue::try_from_array(batches[0].column(1), 0).unwrap(),
- ScalarValue::Utf8(Some("FFFFFFFFFFFFFFFF".into()))
+ ScalarValue::Utf8(Some("7FFFFFFFFFFFFFFF".into()))
);
assert!(batches[0].column(0).is_null(1));
assert!(batches[0].column(1).is_null(1));
diff --git a/crates/integrations/datafusion/tests/spark_functions.rs
b/crates/integrations/datafusion/tests/spark_functions.rs
new file mode 100644
index 00000000..7553ae19
--- /dev/null
+++ b/crates/integrations/datafusion/tests/spark_functions.rs
@@ -0,0 +1,325 @@
+// 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, sql: &str) {
+ let batches = ctx
+ .sql(sql)
+ .await
+ .unwrap_or_else(|e| panic!("{sql}: {e}"))
+ .collect()
+ .await
+ .unwrap_or_else(|e| panic!("{sql}: {e}"));
+ let mut seen = 0;
+ for batch in batches {
+ for row in 0..batch.num_rows() {
+ seen += 1;
+ for col in 0..batch.num_columns() {
+ assert_eq!(
+ ScalarValue::try_from_array(batch.column(col),
row).unwrap(),
+ ScalarValue::Boolean(Some(true)),
+ "{sql}, row {row}, column {col}"
+ );
+ }
+ }
+ }
+ assert_eq!(seen, 1, "{sql}");
+}
+
+#[tokio::test]
+async fn spark_function_families_are_available_without_a_catalog() {
+ let ctx = SQLContext::new();
+ assert_true(&ctx, "SELECT pmod(-5,3)=1, factorial(5)=120,
soundex('Robert')='R163', last_day(DATE '2024-02-01')=DATE '2024-02-29',
unix_date(DATE '1970-01-02')=1, crc32('abc')=891568578,
sha1('abc')='a9993e364706816aba3e25717850c26c9cd0d89d',
base64('f')='Zg=='").await;
+ assert_true(
+ &ctx,
+ "SELECT array_length(collect_set(v))=2,try_sum(v)=4 FROM (VALUES
(1),(1),(2),(NULL)) t(v)",
+ )
+ .await;
+}
+
+#[tokio::test]
+async fn spark_date_part_preserves_epoch_types_and_fractional_arithmetic() {
+ use datafusion::arrow::datatypes::DataType;
+
+ let ctx = SQLContext::new();
+ assert_true(
+ &ctx,
+ "SELECT EXTRACT(EPOCH FROM TIMESTAMP '1970-01-01 00:00:01.500') / 2 =
0.75",
+ )
+ .await;
+ for expression in [
+ "date_part('epoch', ts)",
+ "datepart('EpOcH', ts)",
+ "EXTRACT(EPOCH FROM ts)",
+ ] {
+ let sql = format!(
+ "SELECT {expression} / 2 AS half FROM (VALUES \
+ (TIMESTAMP '1970-01-01 00:00:01.500'), \
+ (TIMESTAMP '1969-12-31 23:59:59.500'), \
+ (CAST(NULL AS TIMESTAMP))) t(ts)"
+ );
+ let frame = ctx.sql(&sql).await.unwrap();
+ assert_eq!(
+ frame.schema().field(0).data_type(),
+ &DataType::Float64,
+ "{sql}"
+ );
+ let batches = frame.collect().await.unwrap();
+ let batch = &batches[0];
+ assert_eq!(batch.num_rows(), 3);
+ for (row, expected) in [Some(0.75), Some(-0.25),
None].into_iter().enumerate() {
+ assert_eq!(
+ ScalarValue::try_from_array(batch.column(0), row).unwrap(),
+ ScalarValue::Float64(expected),
+ "{sql}, row {row}"
+ );
+ }
+ }
+}
+
+#[tokio::test]
+async fn spark_date_part_preserves_nanosecond_types_and_arithmetic() {
+ use datafusion::arrow::datatypes::DataType;
+
+ let ctx = SQLContext::new();
+ for expression in [
+ "date_part('nanosecond', ts)",
+ "datepart('NaNoSeCoNdS', ts)",
+ "EXTRACT(NANOSECOND FROM ts)",
+ ] {
+ let sql = format!(
+ "SELECT {expression} + CAST(1 AS INT) AS adjusted FROM (VALUES \
+ (TIMESTAMP '1970-01-01 00:00:10.500'), \
+ (CAST(NULL AS TIMESTAMP))) t(ts)"
+ );
+ let frame = ctx.sql(&sql).await.unwrap();
+ assert_eq!(
+ frame.schema().field(0).data_type(),
+ &DataType::Int64,
+ "{sql}"
+ );
+ let batches = frame.collect().await.unwrap();
+ let batch = &batches[0];
+ assert_eq!(batch.num_rows(), 2);
+ for (row, expected) in [Some(10_500_000_001),
None].into_iter().enumerate() {
+ assert_eq!(
+ ScalarValue::try_from_array(batch.column(0), row).unwrap(),
+ ScalarValue::Int64(expected),
+ "{sql}, row {row}"
+ );
+ }
+ }
+}
+
+#[tokio::test]
+async fn spark_date_part_keeps_weekday_and_year_aliases() {
+ let ctx = SQLContext::new();
+ assert_true(
+ &ctx,
+ "SELECT date_part('dayofweek', DATE '1970-01-01') = 5, \
+ EXTRACT(DOW FROM DATE '1970-01-01') = 5, \
+ datepart('dayofweek_iso', DATE '1970-01-01') = 4, \
+ date_part('yearofweek', DATE '2021-01-01') = 2020, \
+ EXTRACT(YEAR FROM DATE '2021-01-01') = 2021",
+ )
+ .await;
+}
+
+#[tokio::test]
+async fn upstream_aggregates_keep_distinct_null_empty_and_overflow_contracts()
{
+ let ctx = SQLContext::new();
+ assert_true(&ctx,"SELECT array_length(collect_list(DISTINCT
v))=2,array_length(collect_set(v))=2,try_sum(v)=4,avg(v)=CAST(4 AS DOUBLE)/3
FROM (VALUES (1),(1),(2),(NULL)) t(v)").await;
+ assert_true(&ctx,"SELECT array_length(collect_list(v))=0,try_sum(v) IS
NULL,avg(v) IS NULL FROM (VALUES (CAST(NULL AS BIGINT))) t(v) WHERE
FALSE").await;
+ assert_true(
+ &ctx,
+ "SELECT try_sum(v) IS NULL FROM (VALUES (9223372036854775807),(CAST(1
AS BIGINT))) t(v)",
+ )
+ .await;
+ assert_true(
+ &ctx,
+ "SELECT try_sum(DISTINCT v)=3 FROM (VALUES (1),(1),(2)) t(v)",
+ )
+ .await;
+ for sql in [
+ "SELECT try_sum(DISTINCT v),try_sum(DISTINCT w) FROM (VALUES
(1,10),(1,20),(2,20)) t(v,w)",
+ "SELECT collect_list(v ORDER BY v DESC) FROM (VALUES (1),(2)) t(v)",
+ ] {
+ let result = ctx.sql(sql).await;
+ let error = match result {
+ Err(e) => e,
+ Ok(df) => df.collect().await.unwrap_err(),
+ };
+ assert!(
+ error.to_string().contains("not supported"),
+ "{sql}: {error}"
+ );
+ }
+}
+
+#[tokio::test]
+async fn spark_avg_honors_grouped_filters_including_null_predicates() {
+ let ctx = SQLContext::new();
+ assert_true(&ctx,"SELECT bool_and(result IS NOT DISTINCT FROM CASE g WHEN
1 THEN CAST(10 AS DOUBLE) ELSE CAST(50 AS DOUBLE) END) FROM (SELECT g,avg(v)
FILTER(WHERE p) AS result FROM (VALUES
(1,10,TRUE),(1,30,FALSE),(2,50,TRUE),(2,70,NULL)) t(g,v,p) GROUP BY g)
a").await;
+}
+
+#[tokio::test]
+async fn spark_aggregates_merge_filtered_batches_and_partial_bypass_states() {
+ use datafusion::arrow::{
+ array::{BooleanArray, Int64Array, RecordBatch},
+ datatypes::{DataType, Field, Schema},
+ };
+ use datafusion::datasource::MemTable;
+ use std::sync::Arc;
+ let schema = Arc::new(Schema::new(vec![
+ Field::new("g", DataType::Int64, false),
+ Field::new("v", DataType::Int64, true),
+ Field::new("p", DataType::Boolean, true),
+ ]));
+ let batch = |g: Vec<i64>, v: Vec<Option<i64>>, p: Vec<Option<bool>>| {
+ RecordBatch::try_new(
+ Arc::clone(&schema),
+ vec![
+ Arc::new(Int64Array::from(g)),
+ Arc::new(Int64Array::from(v)),
+ Arc::new(BooleanArray::from(p)),
+ ],
+ )
+ .unwrap()
+ };
+ let partitions = vec![
+ vec![
+ batch(
+ vec![1, 2],
+ vec![Some(10), None],
+ vec![Some(true), Some(true)],
+ ),
+ batch(
+ vec![1, 3],
+ vec![Some(30), Some(20)],
+ vec![Some(false), Some(true)],
+ ),
+ ],
+ vec![
+ batch(
+ vec![1, 2],
+ vec![Some(14), Some(50)],
+ vec![Some(true), Some(false)],
+ ),
+ batch(vec![3, 3], vec![Some(40), None], vec![Some(true), None]),
+ ],
+ ];
+ let table = Arc::new(MemTable::try_new(schema, partitions).unwrap());
+ for bypass in [false, true] {
+ let ctx = SQLContext::new();
+ ctx.ctx()
+ .register_table("spark_inputs", table.clone())
+ .unwrap();
+ ctx.sql("SET datafusion.execution.target_partitions = 2")
+ .await
+ .unwrap();
+ if bypass {
+ ctx.sql(
+ "SET
datafusion.execution.skip_partial_aggregation_probe_ratio_threshold = 0.0",
+ )
+ .await
+ .unwrap();
+ ctx.sql("SET
datafusion.execution.skip_partial_aggregation_probe_rows_threshold = 0")
+ .await
+ .unwrap();
+ }
+ assert_true(&ctx,"SELECT count(*)=3,bool_and(mean IS NOT DISTINCT FROM
CASE g WHEN 1 THEN CAST(12 AS DOUBLE) WHEN 3 THEN CAST(30 AS DOUBLE) ELSE
CAST(NULL AS DOUBLE) END) FROM (SELECT g,avg(v) FILTER(WHERE p) AS mean FROM
spark_inputs GROUP BY g) a").await;
+ assert_true(&ctx,"SELECT avg(v) FILTER(WHERE p)=21,try_sum(v)
FILTER(WHERE p)=84,array_length(collect_list(v) FILTER(WHERE p))=4 FROM
spark_inputs").await;
+ }
+}
+
+#[tokio::test]
+async fn unsupported_avg_suffix_frames_follow_upstream_limits() {
+ use datafusion::execution::SessionStateBuilder;
+ use datafusion::prelude::SessionContext;
+ use datafusion_spark::SessionStateBuilderSpark;
+ let native = SessionContext::new_with_state(
+ SessionStateBuilder::new()
+ .with_default_features()
+ .with_spark_features()
+ .build(),
+ );
+ let ctx = SQLContext::new();
+ let sql="SELECT v,avg(v) OVER(ORDER BY v ROWS BETWEEN CURRENT ROW AND
UNBOUNDED FOLLOWING) AS mean FROM (SELECT v FROM (VALUES (1),(2)) t(v) ORDER BY
v DESC) s";
+ let native_error =
native.sql(sql).await.unwrap().collect().await.unwrap_err();
+ assert!(
+ native_error.to_string().contains("retract_batch"),
+ "{native_error}"
+ );
+ let error = ctx.sql(sql).await.unwrap().collect().await.unwrap_err();
+ assert!(error.to_string().contains("retract_batch"), "{error}");
+}
+
+#[tokio::test]
+async fn spark_collections_return_empty_arrays_for_empty_window_frames() {
+ let ctx = SQLContext::new();
+ assert_true(&ctx,"SELECT bool_and((items IS NOT DISTINCT FROM CASE v WHEN
1 THEN '[]' ELSE '[1]' END) AND (unique_items IS NOT DISTINCT FROM CASE v WHEN
1 THEN '[]' ELSE '[1]' END)) FROM (SELECT v,to_json(collect_list(v) OVER(ORDER
BY v ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING)) AS
items,to_json(collect_set(v) OVER(ORDER BY v ROWS BETWEEN UNBOUNDED PRECEDING
AND 1 PRECEDING)) AS unique_items FROM (VALUES (1),(2)) t(v)) w").await;
+}
+
+#[tokio::test]
+async fn spark_sum_window_defaults_keep_the_result_type() {
+ let ctx = SQLContext::new();
+ assert_true(&ctx,"SELECT bool_and(result IS NOT DISTINCT FROM CASE v WHEN
1 THEN CAST(NULL AS BIGINT) ELSE CAST(1 AS BIGINT) END) FROM (SELECT
v,try_sum(v) OVER(ORDER BY v ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING)
AS result FROM (VALUES (1),(2)) t(v)) w").await;
+}
+
+#[tokio::test]
+async fn spark_date_overloads_and_session_overrides_remain_distinct() {
+ use datafusion::arrow::datatypes::DataType;
+ use datafusion::logical_expr::{create_udf, ColumnarValue, Volatility};
+ use std::sync::Arc;
+ let ctx = SQLContext::new();
+ assert_true(&ctx,"SELECT date_add('2024-02-28',1)=DATE
'2024-02-29',dateadd('2024-02-28',1)=DATE
'2024-02-29',date_sub('2024-03-01',1)=DATE '2024-02-29',date_diff(DATE
'2024-03-01',DATE '2024-02-28')=2,datediff(DATE '2024-03-01',DATE
'2024-02-28')=2,date_diff('hour',TIMESTAMP '2024-03-01 00:00:00',TIMESTAMP
'2024-03-01 03:30:00')=3").await;
+ ctx.ctx().register_udf(create_udf(
+ "pmod",
+ vec![DataType::Int64, DataType::Int64],
+ DataType::Int64,
+ Volatility::Immutable,
+ Arc::new(|_| Ok(ColumnarValue::Scalar(ScalarValue::Int64(Some(99))))),
+ ));
+ assert_true(&ctx, "SELECT pmod(-5,3)=99").await;
+}
+
+#[tokio::test]
+async fn spark_semantics_replace_conflicting_native_defaults() {
+ let ctx = SQLContext::new();
+ assert_true(&ctx, "SELECT concat('a',CAST(NULL AS STRING)) IS NULL,
mod(1,0) IS NULL, size(CAST(NULL AS INT[]))=-1 AS typed_size,size(NULL)=-1 AS
bare_size, arrow_typeof(date_diff(DATE '2024-03-01',DATE
'2024-02-28'))='Int32'").await;
+ ctx.sql("SET datafusion.execution.enable_ansi_mode=true")
+ .await
+ .unwrap();
+ let result = ctx.sql("SELECT mod(1,0)").await;
+ let error = match result {
+ Err(e) => e,
+ Ok(df) => df.collect().await.unwrap_err(),
+ };
+ assert!(error.to_string().to_lowercase().contains("zero"), "{error}");
+}
+
+#[tokio::test]
+async fn spark_substring_syntax_preserves_binary_values() {
+ let ctx = SQLContext::new();
+ assert_true(
+ &ctx,
+ "SELECT substring(decode('00ff01','hex') FROM 2 FOR
2)=decode('ff01','hex')",
+ )
+ .await;
+}
diff --git a/docs/src/sql.md b/docs/src/sql.md
index 0e872d05..aa1f382e 100644
--- a/docs/src/sql.md
+++ b/docs/src/sql.md
@@ -1965,6 +1965,50 @@ SELECT
FROM paimon.my_db.user_events;
```
+### Spark-compatible functions
+
+`SQLContext::new()` and its builder enable the matching `datafusion-spark`
+function packages and Spark expression planner by default. This includes
+numeric, string, date/time, hash, array/map and aggregate functions such as
+`pmod`, `factorial`, `soundex`, `last_day`, `unix_date`, `crc32`, `sha1`,
+`collect_set` and `try_sum`. EXTRACT and SQL SUBSTRING syntax use the Spark
+expression planner. See the upstream
+[Spark function
package](https://github.com/apache/datafusion/tree/54.0.0/datafusion/spark)
+for the versioned function inventory and signatures.
+
+Spark functions take precedence over DataFusion defaults with the same name.
+Functions registered by the application after constructing SQLContext take
+priority. Registered functions resolve locally without REST function lookups;
+qualified catalog calls retain catalog resolution.
+
+The upstream package's behavior applies, including these migration differences:
+
+- `concat` propagates NULL inputs.
+- `mod` and `pmod` return NULL for a zero divisor by default. Set
+ `datafusion.execution.enable_ansi_mode = true` to report division by zero.
+ Their numeric coercion and decimal result types follow the Spark package.
+- `size` returns INT and uses the package's legacy NULL-to-minus-one behavior.
+- Two-argument `date_diff`/`datediff` return INT. The three-argument Paimon
+ `date_diff(unit, start, end)` extension still returns BIGINT.
+- `hour` takes timestamps; cast dates or strings to TIMESTAMP explicitly.
+ `hex` numeric inputs use upstream BIGINT coercion.
+- The upstream 54 AVG implementation returns DOUBLE. DISTINCT plans that
+ DataFusion can lower to a deduplication step are supported; remaining AVG and
+ TRY_SUM DISTINCT plans report an unsupported error. COLLECT_LIST ORDER BY is
+ unsupported. COLLECT_LIST DISTINCT delegates to upstream COLLECT_SET.
+ Collection aggregates return empty arrays for empty growing window frames.
+ Window frames requiring retraction follow the upstream version's limits,
+ including unsupported AVG suffix frames.
+
+SQLContext normalizes dictionary-encoded inputs for the migrated scalar
+functions, types bare NULL arguments, and bridges ordinary SQL integer
+arguments to the INT signatures of date arithmetic and factorial. Values
outside
+that integer range fail during conversion. These adapters delegate computation
+to upstream functions. Paimon Variant handling, metadata SQL, selection
+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.
+
### Aggregate compatibility
SQLContext accepts the following aggregates in queries and view definitions.
@@ -1989,7 +2033,8 @@ aggregates reject DISTINCT, OVER, additional ordering and
NULL modifiers. Tied
keys may choose any eligible value. LISTAGG overflow and top-k selection forms
are unsupported. Approximate counts use native HLL estimates rather than
Spark's
serialized HLL++ state.
-COLLECT_LIST always ignores NULLs and rejects RESPECT NULLS. Aggregate values
and
+COLLECT_LIST always ignores NULLs and rejects explicit IGNORE/RESPECT NULLS
clauses.
+Aggregate values and
selection keys are evaluated once, including volatile expressions.
### JSON output and Variant string casts
@@ -2015,7 +2060,7 @@ representation uses this conversion; ordinary casts
retain native behavior.
| --- | --- |
| `assert_true(condition[, message])` | Returns NULL for TRUE; FALSE or NULL
raises an execution error with the optional message |
| `conv(text, from_base, to_base)` | Source base 2 through 36 conversion of a
64-bit value; a negative destination base formats a signed result; invalid
bases, including negative source bases, return NULL |
-| `date_diff(end, start)` | BIGINT calendar days after native DATE coercion |
+| `date_diff(end, start)` | Upstream Spark INT calendar days after DATE
coercion |
| `date_diff(unit, start, end)` | Signed whole-unit difference at microsecond
precision, from microsecond through week and calendar month/quarter/year;
calendar fields use UTC and month-end clamping |
| `convert_tz(datetime, from_zone, to_zone)` | Interprets a timezone-less
datetime in the source zone, returning a timezone-less microsecond timestamp in
the destination zone |
@@ -2044,12 +2089,12 @@ with a custom escape is unsupported.
| Function | Behavior |
| --- | --- |
-| `mod(value, divisor)` | Numeric remainder with DataFusion `%` coercion,
null, sign, and division-by-zero behavior |
+| `mod(value, divisor)` | Upstream Spark numeric remainder, with NULL on zero
by default and errors in ANSI mode |
| `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 |
+| `sha2(text_or_binary, bits)` | Lowercase SHA-2 hex with upstream INT
coercion for bits; 224/256/384/512 are supported, 0 means 256, and other INT
values return NULL |
+| `to_base64(text_or_binary)` | Alias of upstream Spark `base64`, with
standard `=` padding; strings use 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 |
@@ -2077,9 +2122,10 @@ are epoch seconds. The Flink `(number, precision)`
overload is not implemented.
| `hex(value)` | Uppercase hexadecimal UTF-8/string or raw binary bytes;
integer inputs use hexadecimal digits, with negative signed values represented
as 64-bit two's complement. |
| `unhex(text)` | Decodes case-insensitive hex. An odd number of digits is
left-padded with zero; invalid hex returns NULL. |
| `size(collection)` | Counts array elements or map entries, including NULL
values, and returns INT. |
-| `hour(value)` | Extracts an INT hour from timestamps, times or timestamp
strings. Dates produce zero; timestamp timezone metadata is honored. |
+| `hour(timestamp)` | Upstream Spark INT hour extraction; timestamp timezone
metadata is honored. |
-Except for `typeof`, NULL inputs produce NULL. Empty collections have size
zero.
+Except for `typeof` and `size`, NULL inputs produce NULL. SIZE returns -1 for
+NULL collections. Empty collections have size zero.
These functions are registered locally and do not require REST function
metadata.
Split patterns follow the same Rust regex restrictions as the other regex
compatibility functions. SQLContext's `date` alias follows native DataFusion