use std::fmt::{self, Debug, Formatter};
use std::hash::{Hash, Hasher};
use std::sync::Arc;
use crate::PhysicalExpr;
use crate::expressions::Literal;
use arrow::array::{Array, RecordBatch};
use arrow::datatypes::{DataType, FieldRef, Schema};
use datafusion_common::config::{ConfigEntry, ConfigOptions};
use datafusion_common::{Result, ScalarValue, internal_err};
use datafusion_expr::interval_arithmetic::Interval;
use datafusion_expr::sort_properties::ExprProperties;
use datafusion_expr::type_coercion::functions::fields_with_udf;
use datafusion_expr::{
ColumnarValue, ExpressionPlacement, ReturnFieldArgs, ScalarFunctionArgs, ScalarUDF,
ScalarUDFImpl, Volatility, expr_vec_fmt,
};
pub struct ScalarFunctionExpr {
fun: Arc<ScalarUDF>,
name: String,
args: Vec<Arc<dyn PhysicalExpr>>,
return_field: FieldRef,
config_options: Arc<ConfigOptions>,
}
impl Debug for ScalarFunctionExpr {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.debug_struct("ScalarFunctionExpr")
.field("fun", &"<FUNC>")
.field("name", &self.name)
.field("args", &self.args)
.field("return_field", &self.return_field)
.finish()
}
}
impl ScalarFunctionExpr {
pub fn new(
name: &str,
fun: Arc<ScalarUDF>,
args: Vec<Arc<dyn PhysicalExpr>>,
return_field: FieldRef,
config_options: Arc<ConfigOptions>,
) -> Self {
Self {
fun,
name: name.to_owned(),
args,
return_field,
config_options,
}
}
pub fn try_new(
fun: Arc<ScalarUDF>,
args: Vec<Arc<dyn PhysicalExpr>>,
schema: &Schema,
config_options: Arc<ConfigOptions>,
) -> Result<Self> {
let name = fun.name().to_string();
let arg_fields = args
.iter()
.map(|e| e.return_field(schema))
.collect::<Result<Vec<_>>>()?;
fields_with_udf(&arg_fields, fun.as_ref())?;
let arguments = args
.iter()
.map(|e| e.downcast_ref::<Literal>().map(|literal| literal.value()))
.collect::<Vec<_>>();
let ret_args = ReturnFieldArgs {
arg_fields: &arg_fields,
scalar_arguments: &arguments,
};
let return_field = fun.return_field_from_args(ret_args)?;
Ok(Self {
fun,
name,
args,
return_field,
config_options,
})
}
pub fn fun(&self) -> &ScalarUDF {
&self.fun
}
pub fn name(&self) -> &str {
&self.name
}
pub fn args(&self) -> &[Arc<dyn PhysicalExpr>] {
&self.args
}
pub fn return_type(&self) -> &DataType {
self.return_field.data_type()
}
pub fn with_nullable(mut self, nullable: bool) -> Self {
self.return_field = self
.return_field
.as_ref()
.clone()
.with_nullable(nullable)
.into();
self
}
pub fn nullable(&self) -> bool {
self.return_field.is_nullable()
}
pub fn config_options(&self) -> &ConfigOptions {
&self.config_options
}
pub(crate) fn supports_range_key_locality_analysis(
&self,
input_schema: &Schema,
) -> Result<bool> {
let argument_types = self
.args
.iter()
.map(|argument| argument.data_type(input_schema))
.collect::<Result<Vec<_>>>()?;
let literal_arguments = self
.args
.iter()
.map(|argument| argument.downcast_ref::<Literal>().map(Literal::value))
.collect::<Vec<_>>();
Ok(self
.fun
.supports_range_key_locality_analysis(&argument_types, &literal_arguments))
}
pub fn try_downcast_func<T>(expr: &dyn PhysicalExpr) -> Option<&ScalarFunctionExpr>
where
T: ScalarUDFImpl,
{
match expr.downcast_ref::<ScalarFunctionExpr>() {
Some(scalar_expr) if scalar_expr.fun().inner().is::<T>() => Some(scalar_expr),
_ => None,
}
}
}
impl fmt::Display for ScalarFunctionExpr {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{}({})", self.name, expr_vec_fmt!(self.args))
}
}
impl PartialEq for ScalarFunctionExpr {
fn eq(&self, o: &Self) -> bool {
if std::ptr::eq(self, o) {
return true;
}
let Self {
fun,
name,
args,
return_field,
config_options,
} = self;
fun.eq(&o.fun)
&& name.eq(&o.name)
&& args.eq(&o.args)
&& return_field.eq(&o.return_field)
&& (Arc::ptr_eq(config_options, &o.config_options)
|| sorted_config_entries(config_options)
== sorted_config_entries(&o.config_options))
}
}
impl Eq for ScalarFunctionExpr {}
impl Hash for ScalarFunctionExpr {
fn hash<H: Hasher>(&self, state: &mut H) {
let Self {
fun,
name,
args,
return_field,
config_options: _, } = self;
fun.hash(state);
name.hash(state);
args.hash(state);
return_field.hash(state);
}
}
fn sorted_config_entries(config_options: &ConfigOptions) -> Vec<ConfigEntry> {
let mut entries = config_options.entries();
entries.sort_by(|l, r| l.key.cmp(&r.key));
entries
}
impl PhysicalExpr for ScalarFunctionExpr {
fn data_type(&self, _input_schema: &Schema) -> Result<DataType> {
Ok(self.return_field.data_type().clone())
}
fn nullable(&self, _input_schema: &Schema) -> Result<bool> {
Ok(self.return_field.is_nullable())
}
fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> {
let args = self
.args
.iter()
.map(|e| e.evaluate(batch))
.collect::<Result<Vec<_>>>()?;
let arg_fields = self
.args
.iter()
.map(|e| e.return_field(batch.schema_ref()))
.collect::<Result<Vec<_>>>()?;
let input_empty = args.is_empty();
let input_all_scalar = args
.iter()
.all(|arg| matches!(arg, ColumnarValue::Scalar(_)));
let output = self.fun.invoke_with_args(ScalarFunctionArgs {
args,
arg_fields,
number_rows: batch.num_rows(),
return_field: Arc::clone(&self.return_field),
config_options: Arc::clone(&self.config_options),
})?;
if let ColumnarValue::Array(array) = &output
&& array.len() != batch.num_rows()
{
let preserve_scalar = array.len() == 1 && !input_empty && input_all_scalar;
return if preserve_scalar {
ScalarValue::try_from_array(array, 0).map(ColumnarValue::Scalar)
} else {
internal_err!(
"UDF {} returned a different number of rows than expected. Expected: {}, Got: {}",
self.name,
batch.num_rows(),
array.len()
)
};
}
Ok(output)
}
fn return_field(&self, _input_schema: &Schema) -> Result<FieldRef> {
Ok(Arc::clone(&self.return_field))
}
fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
self.args.iter().collect()
}
fn with_new_children(
self: Arc<Self>,
children: Vec<Arc<dyn PhysicalExpr>>,
) -> Result<Arc<dyn PhysicalExpr>> {
Ok(Arc::new(ScalarFunctionExpr::new(
&self.name,
Arc::clone(&self.fun),
children,
Arc::clone(&self.return_field),
Arc::clone(&self.config_options),
)))
}
fn evaluate_bounds(&self, children: &[&Interval]) -> Result<Interval> {
self.fun.evaluate_bounds(children)
}
fn propagate_constraints(
&self,
interval: &Interval,
children: &[&Interval],
) -> Result<Option<Vec<Interval>>> {
self.fun.propagate_constraints(interval, children)
}
fn get_properties(&self, children: &[ExprProperties]) -> Result<ExprProperties> {
let sort_properties = self.fun.output_ordering(children)?;
let preserves_lex_ordering = self.fun.preserves_lex_ordering(children)?;
let strictly_order_preserving = self.fun.strictly_order_preserving(children)?;
let children_range = children
.iter()
.map(|props| &props.range)
.collect::<Vec<_>>();
let range = self.fun().evaluate_bounds(&children_range)?;
let range = if range.data_type() == DataType::Null && range.is_unbounded() {
Interval::make_unbounded(self.return_type()).unwrap_or(range)
} else {
range
};
Ok(ExprProperties {
sort_properties,
range,
preserves_lex_ordering,
strictly_order_preserving,
})
}
fn fmt_sql(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "{}(", self.name)?;
for (i, expr) in self.args.iter().enumerate() {
if i > 0 {
write!(f, ", ")?;
}
expr.fmt_sql(f)?;
}
write!(f, ")")
}
fn is_volatile_node(&self) -> bool {
self.fun.signature().volatility == Volatility::Volatile
}
fn placement(&self) -> ExpressionPlacement {
let arg_placements: Vec<_> =
self.args.iter().map(|arg| arg.placement()).collect();
self.fun.placement(&arg_placements)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::expressions::Column;
use arrow::datatypes::{Field, IntervalUnit, TimeUnit};
use datafusion_expr::sort_properties::SortProperties;
use datafusion_expr::{ScalarUDFImpl, Signature};
use datafusion_physical_expr_common::physical_expr::is_volatile;
#[derive(Debug, PartialEq, Eq, Hash)]
struct MockScalarUDF {
signature: Signature,
return_type: DataType,
}
impl ScalarUDFImpl for MockScalarUDF {
fn name(&self) -> &str {
"mock_function"
}
fn signature(&self) -> &Signature {
&self.signature
}
fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
Ok(self.return_type.clone())
}
fn invoke_with_args(&self, _args: ScalarFunctionArgs) -> Result<ColumnarValue> {
Ok(ColumnarValue::Scalar(ScalarValue::try_from(
&self.return_type,
)?))
}
}
fn date_bin_supports_locality_with_stride(
function: Arc<ScalarUDF>,
stride: Arc<dyn PhysicalExpr>,
) -> Result<bool> {
let schema = Schema::new(vec![
Field::new(
"stride",
DataType::Interval(IntervalUnit::MonthDayNano),
true,
),
Field::new("ts", DataType::Timestamp(TimeUnit::Nanosecond, None), true),
]);
let expr = ScalarFunctionExpr::try_new(
function,
vec![stride, Arc::new(Column::new("ts", 1))],
&schema,
Arc::new(ConfigOptions::default()),
)?;
expr.supports_range_key_locality_analysis(&schema)
}
#[test]
fn range_key_locality_analysis_receives_literal_values() -> Result<()> {
let function = datafusion_functions::datetime::date_bin();
let hour = Arc::new(Literal::new(ScalarValue::new_interval_mdn(
0,
0,
3_600_000_000_000,
)));
let month = Arc::new(Literal::new(ScalarValue::new_interval_mdn(1, 0, 0)));
assert!(date_bin_supports_locality_with_stride(
Arc::clone(&function),
hour
)?);
assert!(!date_bin_supports_locality_with_stride(function, month)?);
Ok(())
}
#[test]
fn range_key_locality_analysis_preserves_aliases() -> Result<()> {
let date_bin = datafusion_functions::datetime::date_bin();
let function =
Arc::new(date_bin.as_ref().clone().with_aliases(["date_bin_alias"]));
let hour = Arc::new(Literal::new(ScalarValue::new_interval_mdn(
0,
0,
3_600_000_000_000,
)));
let month = Arc::new(Literal::new(ScalarValue::new_interval_mdn(1, 0, 0)));
assert!(date_bin_supports_locality_with_stride(
Arc::clone(&function),
hour
)?);
assert!(!date_bin_supports_locality_with_stride(function, month)?);
Ok(())
}
#[test]
fn range_key_locality_analysis_rejects_non_literal_parameters() -> Result<()> {
use crate::expressions::CastExpr;
let function = datafusion_functions::datetime::date_bin();
let column = Arc::new(Column::new("stride", 0));
let hour = Arc::new(Literal::new(ScalarValue::new_interval_mdn(
0,
0,
3_600_000_000_000,
)));
let cast = Arc::new(CastExpr::new(
hour,
DataType::Interval(IntervalUnit::MonthDayNano),
None,
));
assert!(!date_bin_supports_locality_with_stride(
Arc::clone(&function),
column
)?);
assert!(!date_bin_supports_locality_with_stride(function, cast)?);
Ok(())
}
#[test]
fn range_key_locality_analysis_accepts_date_trunc() -> Result<()> {
let schema = Schema::new(vec![Field::new(
"ts",
DataType::Timestamp(TimeUnit::Nanosecond, None),
true,
)]);
let expr = ScalarFunctionExpr::try_new(
datafusion_functions::datetime::date_trunc(),
vec![
Arc::new(Literal::new(ScalarValue::from("hour"))),
Arc::new(Column::new("ts", 0)),
],
&schema,
Arc::new(ConfigOptions::default()),
)?;
assert!(expr.supports_range_key_locality_analysis(&schema)?);
Ok(())
}
fn default_bounds_expr(return_type: DataType) -> ScalarFunctionExpr {
ScalarFunctionExpr::try_new(
Arc::new(ScalarUDF::from(MockScalarUDF {
signature: Signature::exact(vec![], Volatility::Immutable),
return_type,
})),
vec![],
&Schema::empty(),
Arc::new(ConfigOptions::default()),
)
.unwrap()
}
#[test]
fn properties_recover_return_type_without_changing_bounds_evaluation() {
for data_type in [
DataType::Null,
DataType::Boolean,
DataType::Int32,
DataType::UInt64,
DataType::Float64,
DataType::Utf8,
DataType::Timestamp(TimeUnit::Second, None),
DataType::Timestamp(TimeUnit::Nanosecond, Some("America/Goose_Bay".into())),
DataType::Time32(TimeUnit::Millisecond),
DataType::Time64(TimeUnit::Microsecond),
DataType::List(Arc::new(Field::new("item", DataType::Int32, true))),
] {
let expr = default_bounds_expr(data_type.clone());
let properties = expr.get_properties(&[]).unwrap();
assert_eq!(
properties.range,
Interval::make_unbounded(&data_type).unwrap()
);
assert_eq!(properties.sort_properties, SortProperties::Unordered);
assert!(!properties.preserves_lex_ordering);
assert!(!properties.strictly_order_preserving);
assert_eq!(
expr.evaluate_bounds(&[]).unwrap(),
Interval::make_unbounded(&DataType::Null).unwrap()
);
}
}
#[test]
fn properties_keep_unknown_bounds_for_unsupported_return_type() {
let data_type = DataType::Time32(TimeUnit::Nanosecond);
assert!(Interval::make_unbounded(&data_type).is_err());
let properties = default_bounds_expr(data_type).get_properties(&[]).unwrap();
assert_eq!(
properties.range,
Interval::make_unbounded(&DataType::Null).unwrap()
);
}
#[test]
fn datetime_properties_use_resolved_return_types() {
use datafusion_functions::datetime::date_bin::DateBinFunc;
use datafusion_functions::datetime::from_unixtime::FromUnixtimeFunc;
for source_type in [
DataType::Timestamp(TimeUnit::Second, None),
DataType::Timestamp(TimeUnit::Nanosecond, Some("UTC".into())),
DataType::Time32(TimeUnit::Millisecond),
DataType::Time64(TimeUnit::Microsecond),
] {
let expr = ScalarFunctionExpr::try_new(
Arc::new(ScalarUDF::from(DateBinFunc::new())),
vec![
Arc::new(Literal::new(ScalarValue::new_interval_mdn(
0,
0,
60_000_000_000,
))),
Arc::new(Column::new("ts", 0)),
],
&Schema::new(vec![Field::new("ts", source_type.clone(), true)]),
Arc::new(ConfigOptions::default()),
)
.unwrap();
let properties = expr
.get_properties(&[
ExprProperties::new_unknown().with_order(SortProperties::Singleton),
ExprProperties::new_unknown()
.with_range(Interval::make_unbounded(&source_type).unwrap()),
])
.unwrap();
assert_eq!(
properties.range,
Interval::make_unbounded(&source_type).unwrap()
);
}
for (session_tz, explicit_tz, expected_tz) in [
(None, None, None),
(Some("America/Denver"), None, Some("America/Denver")),
(
Some("America/Denver"),
Some("America/Goose_Bay"),
Some("America/Goose_Bay"),
),
] {
let mut config = ConfigOptions::default();
config.execution.time_zone = session_tz.map(|tz| tz.parse().unwrap());
let udf = FromUnixtimeFunc::new_with_config(&config);
let mut args: Vec<Arc<dyn PhysicalExpr>> =
vec![Arc::new(Column::new("c", 0))];
if let Some(tz) = explicit_tz {
args.push(Arc::new(Literal::new(ScalarValue::from(tz))));
}
let children = vec![ExprProperties::new_unknown(); args.len()];
let expr = ScalarFunctionExpr::try_new(
Arc::new(ScalarUDF::from(udf)),
args,
&Schema::new(vec![Field::new("c", DataType::Int64, true)]),
Arc::new(config),
)
.unwrap();
let expected =
DataType::Timestamp(TimeUnit::Second, expected_tz.map(Into::into));
assert_eq!(
expr.get_properties(&children).unwrap().range,
Interval::make_unbounded(&expected).unwrap()
);
}
}
#[test]
fn checked_time_arithmetic_uses_recovered_function_type() -> Result<()> {
use crate::expressions::BinaryExpr;
use arrow::compute::SortOptions;
use datafusion_expr::Operator;
use datafusion_functions::datetime::date_trunc::DateTruncFunc;
let time_type = DataType::Time64(TimeUnit::Nanosecond);
let precision = Arc::new(Literal::new(ScalarValue::from("hour")));
let precision_properties = precision.get_properties(&[])?;
let date_trunc = ScalarFunctionExpr::try_new(
Arc::new(ScalarUDF::from(DateTruncFunc::new())),
vec![precision, Arc::new(Column::new("t", 0))],
&Schema::new(vec![Field::new("t", time_type.clone(), true)]),
Arc::new(ConfigOptions::default()),
)?;
let time_properties = ExprProperties::new_unknown()
.with_order(SortProperties::Ordered(SortOptions::default()))
.with_range(Interval::make_unbounded(&time_type)?);
let truncated_properties =
date_trunc.get_properties(&[precision_properties, time_properties])?;
assert_eq!(
truncated_properties.range,
Interval::make_unbounded(&time_type)?
);
assert_eq!(
truncated_properties.sort_properties,
SortProperties::Ordered(SortOptions::default())
);
let interval = Arc::new(Literal::new(ScalarValue::new_interval_mdn(
0,
0,
7_200_000_000_000,
)));
let interval_properties = interval.get_properties(&[])?;
let shifted = BinaryExpr::new(Arc::new(date_trunc), Operator::Plus, interval)
.with_fail_on_overflow(true);
assert_eq!(
shifted
.get_properties(&[truncated_properties, interval_properties])?
.sort_properties,
SortProperties::Unordered
);
Ok(())
}
#[derive(Debug, PartialEq, Eq, Hash)]
struct BoundsUDF {
inner: MockScalarUDF,
fail: bool,
}
impl ScalarUDFImpl for BoundsUDF {
fn name(&self) -> &str {
"bounds_function"
}
fn signature(&self) -> &Signature {
self.inner.signature()
}
fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
self.inner.return_type(arg_types)
}
fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
self.inner.invoke_with_args(args)
}
fn evaluate_bounds(&self, inputs: &[&Interval]) -> Result<Interval> {
if self.fail {
return internal_err!("bounds evaluation failed");
}
Ok(inputs[0].clone())
}
}
fn bounds_expr(fail: bool) -> ScalarFunctionExpr {
ScalarFunctionExpr::try_new(
Arc::new(ScalarUDF::from(BoundsUDF {
inner: MockScalarUDF {
signature: Signature::exact(
vec![DataType::Int32],
Volatility::Immutable,
),
return_type: DataType::Int32,
},
fail,
})),
vec![Arc::new(Column::new("a", 0))],
&Schema::new(vec![Field::new("a", DataType::Int32, true)]),
Arc::new(ConfigOptions::default()),
)
.unwrap()
}
#[test]
fn properties_preserve_udf_bounds() {
let expr = bounds_expr(false);
for (lower, upper) in [
(Some(0), Some(100)),
(Some(1), Some(1)),
(None, Some(100)),
(Some(0), None),
(None, None),
] {
let bounds = Interval::make::<i32>(lower, upper).unwrap();
let child = ExprProperties::new_unknown().with_range(bounds.clone());
assert_eq!(expr.get_properties(&[child]).unwrap().range, bounds);
assert_eq!(expr.evaluate_bounds(&[&bounds]).unwrap(), bounds);
}
}
#[test]
fn properties_recover_type_from_explicit_unknown_bounds() {
let expr = bounds_expr(false);
let bounds = Interval::make_unbounded(&DataType::Null).unwrap();
let child = ExprProperties::new_unknown().with_range(bounds.clone());
assert_eq!(
expr.get_properties(&[child]).unwrap().range,
Interval::make_unbounded(&DataType::Int32).unwrap()
);
assert_eq!(expr.evaluate_bounds(&[&bounds]).unwrap(), bounds);
}
#[test]
fn properties_propagate_udf_bounds_errors() {
let expr = bounds_expr(true);
let bounds = Interval::make::<i32>(Some(0), Some(100)).unwrap();
let child = ExprProperties::new_unknown().with_range(bounds.clone());
assert!(
expr.get_properties(&[child])
.unwrap_err()
.to_string()
.contains("bounds evaluation failed")
);
assert!(
expr.evaluate_bounds(&[&bounds])
.unwrap_err()
.to_string()
.contains("bounds evaluation failed")
);
}
#[test]
fn test_scalar_function_volatile_node() {
let volatile_udf = Arc::new(ScalarUDF::from(MockScalarUDF {
return_type: DataType::Int32,
signature: Signature::uniform(
1,
vec![DataType::Float32],
Volatility::Volatile,
),
}));
let stable_udf = Arc::new(ScalarUDF::from(MockScalarUDF {
return_type: DataType::Int32,
signature: Signature::uniform(1, vec![DataType::Float32], Volatility::Stable),
}));
let schema = Schema::new(vec![Field::new("a", DataType::Float32, false)]);
let args = vec![Arc::new(Column::new("a", 0)) as Arc<dyn PhysicalExpr>];
let config_options = Arc::new(ConfigOptions::new());
let volatile_expr = ScalarFunctionExpr::try_new(
volatile_udf,
args.clone(),
&schema,
Arc::clone(&config_options),
)
.unwrap();
assert!(volatile_expr.is_volatile_node());
let volatile_arc: Arc<dyn PhysicalExpr> = Arc::new(volatile_expr);
assert!(is_volatile(&volatile_arc));
let stable_expr =
ScalarFunctionExpr::try_new(stable_udf, args, &schema, config_options)
.unwrap();
assert!(!stable_expr.is_volatile_node());
let stable_arc: Arc<dyn PhysicalExpr> = Arc::new(stable_expr);
assert!(!is_volatile(&stable_arc));
}
}