From 7fceb7d79a728ff0ba63a6b2e3d868e9df21eb89 Mon Sep 17 00:00:00 2001 From: Daniel King Date: Mon, 16 Nov 2026 16:55:45 -0500 Subject: [PATCH] refactor(datafusion): group node conversion logic by expression Expose per-expression Convertible implementations with typed DataFusion matching, fixed-arity construction, and caller-owned recursion. Use MustConvert and MayConvert to distinguish unsupported expressions from conversion errors, with shared schema, session, and scope supplied through ConvertibleCtx. Return Scoped::Same and Scoped::With inputs to the recursion callback and convert array_transform through the same protocol. Provide both concrete and boxed construction paths while preserving the established ExpressionConverter interface. Signed-off-by: Daniel King --- .../src/convert/exprs/convertible/impls.rs | 1295 +++++++++++++++++ .../src/convert/exprs/convertible/mod.rs | 365 +++++ vortex-datafusion/src/convert/exprs/mod.rs | 1161 +-------------- vortex-datafusion/src/convert/exprs/tests.rs | 450 +++++- vortex-datafusion/src/convert/mod.rs | 4 +- 5 files changed, 2092 insertions(+), 1183 deletions(-) create mode 100644 vortex-datafusion/src/convert/exprs/convertible/impls.rs create mode 100644 vortex-datafusion/src/convert/exprs/convertible/mod.rs diff --git a/vortex-datafusion/src/convert/exprs/convertible/impls.rs b/vortex-datafusion/src/convert/exprs/convertible/impls.rs new file mode 100644 index 00000000000..24c6643cb1a --- /dev/null +++ b/vortex-datafusion/src/convert/exprs/convertible/impls.rs @@ -0,0 +1,1295 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Recognition and construction of each supported expression. + +use std::sync::Arc; + +use arrow_schema::DataType; +use arrow_schema::Field; +use arrow_schema::FieldRef; +use arrow_schema::Schema; +use datafusion_common::Result as DFResult; +use datafusion_common::ScalarValue; +use datafusion_common::exec_datafusion_err; +use datafusion_common::format::DEFAULT_FORMAT_OPTIONS; +use datafusion_expr::Operator as DFOperator; +use datafusion_functions::core::getfield::GetFieldFunc; +use datafusion_functions::string::contains::ContainsFunc; +use datafusion_functions::string::ends_with::EndsWithFunc; +use datafusion_functions::string::lower::LowerFunc; +use datafusion_functions::string::octet_length::OctetLengthFunc; +use datafusion_functions::string::starts_with::StartsWithFunc; +use datafusion_functions::unicode::strpos::StrposFunc; +use datafusion_functions_nested::array_sum::ArraySum; +use datafusion_functions_nested::array_transform::ArrayTransform; +use datafusion_functions_nested::length::ArrayLength; +use datafusion_physical_expr::HigherOrderFunctionExpr; +use datafusion_physical_expr::PhysicalExpr; +use datafusion_physical_expr::PhysicalExprRef; +use datafusion_physical_expr::ScalarFunctionExpr; +use datafusion_physical_plan::expressions as df_expr; +use itertools::Itertools; +use vortex::aggregate_fn::NumericalAggregateOpts; +use vortex::dtype::DType; +use vortex::dtype::Nullability; +use vortex::dtype::PType; +use vortex::dtype::StructFields; +use vortex::error::VortexExpect; +use vortex::expr::Expression; +use vortex::expr::Lambda; +use vortex::expr::byte_length; +use vortex::expr::cast; +use vortex::expr::ext_storage; +use vortex::expr::get_item; +use vortex::expr::in_list_of; +use vortex::expr::is_not_null; +use vortex::expr::is_null; +use vortex::expr::list_length; +use vortex::expr::list_sum_opts; +use vortex::expr::list_transform; +use vortex::expr::lit; +use vortex::expr::lower; +use vortex::expr::nested_case_when; +use vortex::expr::not; +use vortex::expr::root; +use vortex::expr::strpos; +use vortex::expr::traversal::NodeExt; +use vortex::expr::traversal::Transformed; +use vortex::expr::var; +use vortex::functions::like::Like; +use vortex::functions::like::LikeOptions; +use vortex::layout::layouts::row_idx; +use vortex::scalar::Scalar; +use vortex::scalar_fn::ScalarFnVTableExt; +use vortex::scalar_fn::builtin::binary::Binary; +use vortex::scalar_fn::builtin::get_item::GetItem; +use vortex::scalar_fn::builtin::literal::Literal; +use vortex::scalar_fn::builtin::operators::Operator; +use vortex_arrow::ArrowSessionExt; + +use super::Constructible; +use super::Convertible; +use super::ConvertibleCtx; +use super::ConvertibleFixedArity; +use super::MayConvert; +use super::MustConvert; +use super::Scoped; +use super::Unsupported; +use super::may; +use crate::convert::exprs::is_infallible; +use crate::row_index::RowIndex; + +type Ctx<'a> = ConvertibleCtx<'a>; + +/// Select the first supported converter, borrowing its inputs and boxing its construction state. +pub fn default_convert<'a>( + expr: &'a PhysicalExprRef, + ctx: &Ctx<'_>, +) -> MayConvert<(Vec>, Box)> { + ConvertRowIndex::recognize_boxed(expr, ctx)?; + ConvertBinary::recognize_boxed(expr, ctx)?; + ConvertColumn::recognize_boxed(expr, ctx)?; + ConvertLambdaVariable::recognize_boxed(expr, ctx)?; + ConvertLiteral::recognize_boxed(expr, ctx)?; + ConvertCast::recognize_boxed(expr, ctx)?; + ConvertNot::recognize_boxed(expr, ctx)?; + ConvertIsNull::recognize_boxed(expr, ctx)?; + ConvertIsNotNull::recognize_boxed(expr, ctx)?; + ConvertLike::recognize_boxed(expr, ctx)?; + ConvertInList::recognize_boxed(expr, ctx)?; + ConvertGetField::recognize_boxed(expr, ctx)?; + ConvertOctetLength::recognize_boxed(expr, ctx)?; + ConvertArrayLength::recognize_boxed(expr, ctx)?; + ConvertLower::recognize_boxed(expr, ctx)?; + ConvertStrpos::recognize_boxed(expr, ctx)?; + ConvertContains::recognize_boxed(expr, ctx)?; + ConvertStartsWith::recognize_boxed(expr, ctx)?; + ConvertEndsWith::recognize_boxed(expr, ctx)?; + ConvertArraySum::recognize_boxed(expr, ctx)?; + ConvertArrayTransform::recognize_boxed(expr, ctx)?; + ConvertCase::recognize_boxed(expr, ctx)?; + Ok(Unsupported) +} + +/// Convert a supported node using the caller's recursion for its selected children. +/// +/// Inputs borrow from `expr`; converters remain on the stack and are consumed after recursion. +pub fn default_convert_recursive<'a>( + expr: &'a PhysicalExprRef, + ctx: &Ctx<'_>, + mut recur: impl FnMut(Scoped<'a>) -> MustConvert, +) -> MayConvert { + may(ConvertRowIndex::convert_recursive(expr, ctx, &mut recur))?; + may(ConvertBinary::convert_recursive(expr, ctx, &mut recur))?; + may(ConvertColumn::convert_recursive(expr, ctx, &mut recur))?; + may(ConvertLambdaVariable::convert_recursive( + expr, ctx, &mut recur, + ))?; + may(ConvertLiteral::convert_recursive(expr, ctx, &mut recur))?; + may(ConvertCast::convert_recursive(expr, ctx, &mut recur))?; + may(ConvertNot::convert_recursive(expr, ctx, &mut recur))?; + may(ConvertIsNull::convert_recursive(expr, ctx, &mut recur))?; + may(ConvertIsNotNull::convert_recursive(expr, ctx, &mut recur))?; + may(ConvertLike::convert_recursive(expr, ctx, &mut recur))?; + may(ConvertInList::convert_recursive(expr, ctx, &mut recur))?; + may(ConvertGetField::convert_recursive(expr, ctx, &mut recur))?; + may(ConvertOctetLength::convert_recursive(expr, ctx, &mut recur))?; + may(ConvertArrayLength::convert_recursive(expr, ctx, &mut recur))?; + may(ConvertLower::convert_recursive(expr, ctx, &mut recur))?; + may(ConvertStrpos::convert_recursive(expr, ctx, &mut recur))?; + may(ConvertContains::convert_recursive(expr, ctx, &mut recur))?; + may(ConvertStartsWith::convert_recursive(expr, ctx, &mut recur))?; + may(ConvertEndsWith::convert_recursive(expr, ctx, &mut recur))?; + may(ConvertArraySum::convert_recursive(expr, ctx, &mut recur))?; + may(ConvertArrayTransform::convert_recursive( + expr, ctx, &mut recur, + ))?; + may(ConvertCase::convert_recursive(expr, ctx, &mut recur))?; + Ok(Unsupported) +} + +struct ConvertRowIndex; + +impl<'a> ConvertibleFixedArity<'a> for ConvertRowIndex { + type DF = RowIndex; + type Children = [Expression; 0]; + + fn convert_fixed(_expr: &'a Self::DF, _ctx: &Ctx) -> MustConvert<(Vec>, Self)> { + Ok((Vec::new(), Self)) + } + + fn construct_fixed(self, []: [Expression; 0], _ctx: &Ctx) -> MustConvert { + Ok(row_idx::row_idx()) + } +} + +/// Matching and construction state used by [`ConvertBinary`]. +pub struct ConvertBinary { + operator: Operator, + left: Option<(df_expr::Literal, FieldRef)>, + right: Option<(df_expr::Literal, FieldRef)>, +} + +impl<'a> Convertible<'a> for ConvertBinary { + type DF = df_expr::BinaryExpr; + + fn convert(expr: &'a Self::DF, ctx: &Ctx) -> MustConvert<(Vec>, Self)> { + let operator = try_operator_from_df(expr.op())?; + let left_type = expr.left().data_type(ctx.schema).map_err(Err)?; + let right_type = expr.right().data_type(ctx.schema).map_err(Err)?; + + if matches!(operator, Operator::And | Operator::Or) + && !(left_type == DataType::Boolean && right_type == DataType::Boolean) + { + return Err(Err(exec_datafusion_err!( + "Boolean operator requires Boolean operands: {expr}" + ))); + } + + if !supported_data_types(&left_type) || !supported_data_types(&right_type) { + return Err(Ok(Unsupported)); + } + + if !operator.is_comparison() { + let children = vec![Scoped::Same(expr.left()), Scoped::Same(expr.right())]; + let convertible = ConvertBinary { + operator, + left: None, + right: None, + }; + return Ok((children, convertible)); + } + + let left_lit = recognize_literal(expr.left(), expr.right(), ctx.schema).map_err(Err)?; + let right_lit = recognize_literal(expr.right(), expr.left(), ctx.schema).map_err(Err)?; + let (children, left, right) = match (left_lit, right_lit) { + (Some(left), Some(right)) => (Vec::new(), Some(left), Some(right)), + (Some(left), None) => (vec![Scoped::Same(expr.right())], Some(left), None), + (None, Some(right)) => (vec![Scoped::Same(expr.left())], None, Some(right)), + (None, None) => ( + vec![Scoped::Same(expr.left()), Scoped::Same(expr.right())], + None, + None, + ), + }; + + let convertible = ConvertBinary { + operator, + left, + right, + }; + Ok((children, convertible)) + } + + fn construct(self, children: Vec, ctx: &Ctx) -> MustConvert { + let Self { + operator, + left, + right, + } = self; + + let n = children.len(); + let (left, right) = match (left, right) { + (None, None) => { + let Ok([left, right]) = <[_; 2]>::try_from(children) else { + return Err(Err(exec_datafusion_err!( + "Wrong number of converted binary operands: {n}" + ))); + }; + (left, right) + } + (None, Some(right)) => { + let Ok([left]) = <[_; 1]>::try_from(children) else { + return Err(Err(exec_datafusion_err!( + "Wrong number of converted binary operands: {n}" + ))); + }; + let right = lit(ctx.import_literal_for_operand(&right.0, &right.1)?); + (left, right) + } + (Some(left), None) => { + let Ok([right]) = <[_; 1]>::try_from(children) else { + return Err(Err(exec_datafusion_err!( + "Wrong number of converted binary operands: {n}" + ))); + }; + let left = lit(ctx.import_literal_for_operand(&left.0, &left.1)?); + (left, right) + } + (Some(left), Some(right)) => { + let Ok([]) = <[_; 0]>::try_from(children) else { + return Err(Err(exec_datafusion_err!( + "Wrong number of converted binary operands: {n}" + ))); + }; + let left = lit(ctx.import_literal_for_operand(&left.0, &left.1)?); + let right = lit(ctx.import_literal_for_operand(&right.0, &right.1)?); + (left, right) + } + }; + + // DataFusion may evaluate the RHS only on rows selected by the LHS. + if matches!(operator, Operator::And | Operator::Or) + && !(is_infallible(&left) && is_infallible(&right)) + { + return Err(Ok(Unsupported)); + } + if !ctx + .node_dtype(&left)? + .eq_ignore_nullability(&ctx.node_dtype(&right)?) + { + return Err(Ok(Unsupported)); + } + + Ok(Binary.new_expr(operator, [left, right])) + } +} + +fn recognize_literal( + expr: &PhysicalExprRef, + other: &PhysicalExprRef, + schema: &Schema, +) -> DFResult> { + if let Some(literal) = expr.downcast_ref::() + && literal + .return_field(schema)? + .extension_type_name() + .is_none() + { + let field = other.return_field(schema)?; + if field.extension_type_name().is_some() { + return Ok(Some((literal.clone(), field))); + } + } + + Ok(None) +} + +/// Convert a DataFusion column reference. +pub struct ConvertColumn<'a> { + name: &'a str, +} + +impl<'a> ConvertibleFixedArity<'a> for ConvertColumn<'a> { + type DF = df_expr::Column; + type Children = [Expression; 0]; + + fn convert_fixed(expr: &'a df_expr::Column, ctx: &Ctx) -> MustConvert<(Vec>, Self)> { + if ctx.scope.is_some() { + return Err(Ok(Unsupported)); + } + // FIXME(DK): this should resolve by index into the schema + let name = expr.name(); + Ok((Vec::new(), Self { name })) + } + + fn construct_fixed(self, []: [Expression; 0], _ctx: &Ctx) -> MustConvert { + let Self { name } = self; + Ok(get_item(name, root())) + } +} + +/// Convert a lambda parameter reference within the supplied scope. +pub struct ConvertLambdaVariable<'a> { + name: &'a str, +} + +impl<'a> ConvertibleFixedArity<'a> for ConvertLambdaVariable<'a> { + type DF = df_expr::LambdaVariable; + type Children = [Expression; 0]; + + fn convert_fixed(expr: &'a Self::DF, ctx: &Ctx) -> MustConvert<(Vec>, Self)> { + let Some(params) = ctx.scope else { + return Err(Ok(Unsupported)); + }; + if params.find(expr.name()).is_none() { + return Err(Ok(Unsupported)); + } + let name = expr.name(); + Ok((Vec::new(), Self { name })) + } + + fn construct_fixed(self, []: [Expression; 0], _ctx: &Ctx) -> MustConvert { + let Self { name } = self; + Ok(get_item(name, root())) + } +} + +/// Import a DataFusion literal through the session's Arrow plugins. +pub struct ConvertLiteral { + scalar: Scalar, +} + +impl<'a> ConvertibleFixedArity<'a> for ConvertLiteral { + type DF = df_expr::Literal; + type Children = [Expression; 0]; + + fn convert_fixed(expr: &'a Self::DF, ctx: &Ctx) -> MustConvert<(Vec>, Self)> { + let field = expr.return_field(ctx.schema).map_err(Err)?; + let scalar = ctx.import_literal(expr, &field)?; + Ok((Vec::new(), Self { scalar })) + } + + fn construct_fixed(self, []: [Expression; 0], _ctx: &Ctx) -> MustConvert { + let Self { scalar } = self; + Ok(lit(scalar)) + } +} + +/// Convert a supported DataFusion cast. +pub struct ConvertCast { + pushdown: CastPushdown, + dtype: DType, +} + +/// How a supported DataFusion cast is converted. +enum CastPushdown { + /// The Arrow cast cannot fail and keeps the Vortex dtype, so the converter omits it. + Drop, + /// The cast becomes a Vortex `cast`. + Keep, +} + +impl<'a> ConvertibleFixedArity<'a> for ConvertCast { + type DF = df_expr::CastExpr; + type Children = [Expression; 1]; + + fn convert_fixed( + expr: &'a df_expr::CastExpr, + ctx: &Ctx, + ) -> MustConvert<(Vec>, Self)> { + let pushdown = classify_cast(expr, ctx.schema)?; + let dtype = ctx + .arrow_dtype(expr.target_field())? + .with_nullability(Nullability::from(expr.nullable(ctx.schema).map_err(Err)?)); + Ok((vec![Scoped::Same(expr.expr())], Self { pushdown, dtype })) + } + + fn construct_fixed(self, [child]: [Expression; 1], ctx: &Ctx) -> MustConvert { + let Self { pushdown, dtype } = self; + let child_dtype = ctx.node_dtype(&child)?; + let dtype_already_matches = child_dtype.eq_ignore_nullability(&dtype); + match pushdown { + // TODO(DK): why are we able to ignore nullability? + CastPushdown::Drop if dtype_already_matches => Ok(child), + CastPushdown::Drop => Err(Ok(Unsupported)), + CastPushdown::Keep => { + let either_is_extension = child_dtype.is_extension() || dtype.is_extension(); + // Matching storage types do not imply matching extension semantics. + if either_is_extension && !dtype_already_matches { + return Err(Ok(Unsupported)); + } + Ok(cast(child, dtype)) + } + } + } +} + +/// Classifies a cast for pushdown; unsupported casts stay in DataFusion. +fn classify_cast(cast: &df_expr::CastExpr, schema: &Schema) -> MustConvert { + let options = cast.cast_options(); + if options.safe || options.format_options != DEFAULT_FORMAT_OPTIONS { + return Err(Ok(Unsupported)); + } + let source = cast.expr().data_type(schema).map_err(Err)?; + classify_cast_types(&source, cast.cast_type()) +} + +fn classify_cast_types(source: &DataType, target: &DataType) -> MustConvert { + use DataType::*; + Ok(match (source, target) { + _ if source == target => CastPushdown::Drop, + // Views preserve narrow-offset strings without concatenating their values. + (Utf8, Utf8View) => CastPushdown::Drop, + // Decoding to views does not concatenate dictionary values into a narrow offset buffer. + (Dictionary(_, values), Utf8View) if matches!(values.as_ref(), Utf8 | Utf8View) => { + CastPushdown::Drop + } + // Run expansion gathers dictionary keys, then decodes them directly to views. + (RunEndEncoded(run_ends, values), Utf8View) + if matches!(run_ends.data_type(), Int16 | Int32) + && matches!(values.data_type(), Dictionary(_, strings) if matches!(strings.as_ref(), Utf8 | Utf8View)) => + { + CastPushdown::Drop + } + // Arrow expands runs by gathering with `Int32` indices, which fit Int16/Int32 run ends. + // Gathering a dictionary only moves keys and reuses the values, so nothing can overflow. + (RunEndEncoded(run_ends, values), Dictionary(..)) + if matches!(run_ends.data_type(), Int16 | Int32) && values.data_type() == target => + { + CastPushdown::Drop + } + (Int8, Int16 | Int32 | Int64) + | (Int16, Int32 | Int64) + | (Int32, Int64) + | (UInt8, UInt16 | UInt32 | UInt64 | Int16 | Int32 | Int64) + | (UInt16, UInt32 | UInt64 | Int32 | Int64) + | (UInt32, UInt64 | Int64) + | (Float32, Float64) => CastPushdown::Keep, + // Arrow and Vortex both convert with `as f64`: integers round to nearest and never fail, + // booleans become 1.0 or 0.0. + (Boolean | Int8 | Int16 | Int32 | Int64 | UInt8 | UInt16 | UInt32 | UInt64, Float64) => { + CastPushdown::Keep + } + // A list cast casts each element. Vortex has no `FixedSizeList` to `List` cast. + (List(from) | LargeList(from), List(to) | LargeList(to)) + if to.is_nullable() || !from.is_nullable() => + { + classify_cast_types(from.data_type(), to.data_type())? + } + _ => return Err(Ok(Unsupported)), + }) +} + +/// Convert a Boolean negation. +pub struct ConvertNot; + +impl<'a> ConvertibleFixedArity<'a> for ConvertNot { + type DF = df_expr::NotExpr; + type Children = [Expression; 1]; + + fn convert_fixed(expr: &'a Self::DF, ctx: &Ctx) -> MustConvert<(Vec>, Self)> { + if expr.arg().data_type(ctx.schema).map_err(Err)? != DataType::Boolean { + return Err(Err(exec_datafusion_err!( + "NOT requires a Boolean operand: {expr}" + ))); + } + Ok((vec![Scoped::Same(expr.arg())], Self)) + } + + fn construct_fixed(self, [arg]: [Expression; 1], _ctx: &Ctx) -> MustConvert { + Ok(not(arg)) + } +} + +/// Convert an IS NULL predicate. +pub struct ConvertIsNull; + +impl<'a> ConvertibleFixedArity<'a> for ConvertIsNull { + type DF = df_expr::IsNullExpr; + type Children = [Expression; 1]; + + fn convert_fixed(expr: &'a Self::DF, _ctx: &Ctx) -> MustConvert<(Vec>, Self)> { + Ok((vec![Scoped::Same(expr.arg())], Self)) + } + + fn construct_fixed(self, [arg]: [Expression; 1], _ctx: &Ctx) -> MustConvert { + Ok(is_null(arg)) + } +} + +/// Convert an IS NOT NULL predicate. +pub struct ConvertIsNotNull; + +impl<'a> ConvertibleFixedArity<'a> for ConvertIsNotNull { + type DF = df_expr::IsNotNullExpr; + type Children = [Expression; 1]; + + fn convert_fixed(expr: &'a Self::DF, _ctx: &Ctx) -> MustConvert<(Vec>, Self)> { + Ok((vec![Scoped::Same(expr.arg())], Self)) + } + + fn construct_fixed(self, [arg]: [Expression; 1], _ctx: &Ctx) -> MustConvert { + Ok(is_not_null(arg)) + } +} + +/// Convert LIKE and ILIKE expressions. +pub struct ConvertLike { + options: LikeOptions, +} + +impl<'a> ConvertibleFixedArity<'a> for ConvertLike { + type DF = df_expr::LikeExpr; + type Children = [Expression; 2]; + + fn convert_fixed(expr: &'a Self::DF, _ctx: &Ctx) -> MustConvert<(Vec>, Self)> { + let options = LikeOptions { + negated: expr.negated(), + case_insensitive: expr.case_insensitive(), + }; + Ok(( + vec![Scoped::Same(expr.expr()), Scoped::Same(expr.pattern())], + Self { options }, + )) + } + + fn construct_fixed( + self, + [child, pattern]: [Expression; 2], + ctx: &Ctx, + ) -> MustConvert { + let Self { options } = self; + ensure_string(&child, ctx)?; + ensure_string(&pattern, ctx)?; + Ok(Like.new_expr(options, [child, pattern])) + } +} + +/// Matching and construction state used by [`ConvertInList`]. +pub struct ConvertInList { + negated: bool, + elements: Option>, + n_children: usize, +} + +impl<'a> Convertible<'a> for ConvertInList { + type DF = df_expr::InListExpr; + + fn convert(expr: &'a Self::DF, ctx: &Ctx) -> MustConvert<(Vec>, Self)> { + let value_type = expr.expr().data_type(ctx.schema).map_err(Err)?; + if expr.is_empty() + || !expr.list().iter().all(|expr| expr.is::()) + || !supported_data_types(&value_type) + { + return Err(Ok(Unsupported)); + } + // DataFusion reads the nulls of a run-end encoded list from its physical validity, which + // is always empty, so it ignores a NULL element that SQL, and Vortex, do not. + if matches!(value_type, DataType::RunEndEncoded(..)) + && expr.list().iter().any(|element| { + element + .downcast_ref::() + .is_some_and(|literal| literal.value().is_null()) + }) + { + return Err(Ok(Unsupported)); + } + let field = expr.expr().return_field(ctx.schema).map_err(Err)?; + + // Some Arrow types, like FixedSizeBinary, cannot be represented in Vortex; however, a + // FixedSizeBinary with Arrow metadata indicating it is a "UUID" array, _can_ be represented + // in Vortex as a UUID array. + // + // At `convert` time, we have the needle's FieldRef and therefore know its Arrow + // metadata. DF frequently loses metadata, so we make a best effort to propagate that UUID + // information from the needle to the elements. + // + // When our caller recursively converts the children, they lack this context, so we do it + // for them. + let literals = expr + .list() + .iter() + .map(|element| element.downcast_ref::()) + .map(|maybe_literal| match maybe_literal { + None => Err(Ok(Unsupported)), + Some(literal) => ctx.import_literal_for_operand(literal, &field), + }) + .collect::>>(); + + let mut children = vec![Scoped::Same(expr.expr())]; + let elements = match literals { + Ok(literals) => Some(literals), + Err(Ok(Unsupported)) => { + children.extend(expr.list().iter().map(Scoped::Same)); + None + } + Err(Err(err)) => return Err(Err(err)), + }; + let convertible = Self { + negated: expr.negated(), + elements, + n_children: children.len(), + }; + Ok((children, convertible)) + } + + fn construct(self, children: Vec, ctx: &Ctx) -> MustConvert { + let Self { + negated, + elements, + n_children, + } = self; + + let n = children.len(); + if n_children != n { + return Err(Err(exec_datafusion_err!( + "Expected {n_children} converted children, found {n}" + ))); + } + + let mut children = children.into_iter(); + let value = children.next().vortex_expect("checked length above"); + if !is_infallible(&value) { + return Err(Ok(Unsupported)); + } + let value_dtype = ctx.node_dtype(&value)?; + + let elements = if let Some(literals) = elements { + literals + } else { + let literals = children + .map(|expr| expr.as_opt::().cloned()) + .collect::>>(); + let Some(literals) = literals else { + return Err(Ok(Unsupported)); + }; + literals + }; + + let membership = in_list_of(value, value_dtype, elements).map_err(|_| Ok(Unsupported))?; + Ok(if negated { not(membership) } else { membership }) + } +} + +/// Convert field access, capturing literal field names as configuration. +pub struct ConvertGetField<'a> { + steps: Vec<(FieldRef, &'a str)>, + field: FieldRef, +} + +impl<'a> ConvertibleFixedArity<'a> for ConvertGetField<'a> { + type DF = ScalarFunctionExpr; + type Children = [Expression; 1]; + + fn convert_fixed( + expr: &'a ScalarFunctionExpr, + ctx: &Ctx, + ) -> MustConvert<(Vec>, Self)> { + if !expr.fun().inner().is::() { + return Err(Ok(Unsupported)); + } + let [source, paths @ ..] = expr.args() else { + return Err(Err(exec_datafusion_err!( + "get_field requires a source and field path" + ))); + }; + if paths.is_empty() { + return Err(Err(exec_datafusion_err!("get_field requires a field path"))); + } + // Keep the Arrow field of each step, because its metadata decides how Vortex exports it. + let mut field = source.return_field(ctx.schema).map_err(Err)?; + let mut steps = Vec::with_capacity(paths.len()); + for path in paths { + let Some(name) = path + .downcast_ref::() + .and_then(|literal| literal.value().try_as_str().flatten()) + else { + return Err(Err(exec_datafusion_err!( + "get_field path must be a non-null string literal" + ))); + }; + let DataType::Struct(fields) = field.data_type() else { + return Err(Ok(Unsupported)); + }; + let Some((_, child_field)) = fields.find(name) else { + return Err(Err(exec_datafusion_err!( + "get_field references missing field {name}" + ))); + }; + let child_field = Arc::clone(child_field); + steps.push((field, name)); + field = child_field; + } + Ok((vec![Scoped::Same(source)], Self { steps, field })) + } + + fn construct_fixed(self, [mut source]: [Expression; 1], ctx: &Ctx) -> MustConvert { + let Self { steps, field } = self; + let mut reads_extension_storage = false; + for (parent_field, name) in steps { + // Check the Vortex dtype instead of the Arrow extension name, because the session + // imports an unknown extension name as a plain struct that `get_item` reads directly. + if let DType::Extension(ext_dtype) = ctx.node_dtype(&source)? { + if !ctx + .session + .arrow() + .exports_extension_storage(&ext_dtype, &parent_field) + { + return Err(Ok(Unsupported)); + } + source = ext_storage(source); + reads_extension_storage = true; + } + source = get_item(name, source); + } + + // A plugin exporter decides which Arrow data DataFusion sees for the selected field, so + // Vortex and DataFusion agree on that field only if the export keeps values. Columns and + // plain struct fields already assume this, and the check skips them so that their pushdown + // stays the same. + // TODO(connor): Drop this check once the Arrow plugin contract requires exports to keep + // values. + if reads_extension_storage && !ctx.session.arrow().exports_without_plugins(&field) { + return Err(Ok(Unsupported)); + } + Ok(source) + } +} + +/// Convert octet_length to the native byte length expression. +pub struct ConvertOctetLength { + dtype: DType, +} + +impl<'a> ConvertibleFixedArity<'a> for ConvertOctetLength { + type DF = ScalarFunctionExpr; + type Children = [Expression; 1]; + + fn convert_fixed( + expr: &'a ScalarFunctionExpr, + ctx: &Ctx, + ) -> MustConvert<(Vec>, Self)> { + if !expr.fun().inner().is::() { + return Err(Ok(Unsupported)); + } + let [input] = expr.args() else { + return Err(Err(exec_datafusion_err!( + "octet_length requires exactly one argument" + ))); + }; + let data_type = input.data_type(ctx.schema).map_err(Err)?; + let data_type = match &data_type { + DataType::Dictionary(_, value) => value.as_ref(), + data_type => data_type, + }; + if !data_type.is_binary() && !data_type.is_string() { + return Err(Ok(Unsupported)); + } + let dtype = + ctx.arrow_dtype(&Field::new("", expr.return_type().clone(), expr.nullable()))?; + Ok((vec![Scoped::Same(input)], Self { dtype })) + } + + fn construct_fixed(self, [input]: [Expression; 1], _ctx: &Ctx) -> MustConvert { + let Self { dtype } = self; + Ok(cast(byte_length(input), dtype)) + } +} + +/// Convert supported array_length calls to native list length. +pub struct ConvertArrayLength { + dtype: DType, +} + +impl<'a> ConvertibleFixedArity<'a> for ConvertArrayLength { + type DF = ScalarFunctionExpr; + type Children = [Expression; 1]; + + fn convert_fixed( + expr: &'a ScalarFunctionExpr, + ctx: &Ctx, + ) -> MustConvert<(Vec>, Self)> { + if !expr.fun().inner().is::() { + return Err(Ok(Unsupported)); + } + let input = array_length_input(expr)?; + let input_dtype = input.data_type(ctx.schema).map_err(Err)?; + if !matches!( + input_dtype, + DataType::List(_) | DataType::LargeList(_) | DataType::FixedSizeList(_, _) + ) { + return Err(Ok(Unsupported)); + } + let dtype = + ctx.arrow_dtype(&Field::new("", expr.return_type().clone(), expr.nullable()))?; + Ok((vec![Scoped::Same(input)], Self { dtype })) + } + + fn construct_fixed(self, [input]: [Expression; 1], _ctx: &Ctx) -> MustConvert { + let Self { dtype } = self; + Ok(cast(list_length(input), dtype)) + } +} + +/// Convert lower on string expressions. +pub struct ConvertLower; + +impl<'a> ConvertibleFixedArity<'a> for ConvertLower { + type DF = ScalarFunctionExpr; + type Children = [Expression; 1]; + + fn convert_fixed( + expr: &'a ScalarFunctionExpr, + _ctx: &Ctx, + ) -> MustConvert<(Vec>, Self)> { + if !expr.fun().inner().is::() { + return Err(Ok(Unsupported)); + } + let [input] = expr.args() else { + return Err(Err(exec_datafusion_err!( + "lower requires exactly one argument" + ))); + }; + Ok((vec![Scoped::Same(input)], Self)) + } + + fn construct_fixed(self, [input]: [Expression; 1], ctx: &Ctx) -> MustConvert { + ensure_string(&input, ctx)?; + Ok(lower(input)) + } +} + +/// Convert strpos, preserving the DataFusion return width. +pub struct ConvertStrpos { + narrow: bool, +} + +impl<'a> ConvertibleFixedArity<'a> for ConvertStrpos { + type DF = ScalarFunctionExpr; + type Children = [Expression; 2]; + + fn convert_fixed( + expr: &'a ScalarFunctionExpr, + _ctx: &Ctx, + ) -> MustConvert<(Vec>, Self)> { + if !expr.fun().inner().is::() { + return Err(Ok(Unsupported)); + } + let [input, search] = expr.args() else { + return Err(Err(exec_datafusion_err!( + "strpos requires exactly two arguments" + ))); + }; + let narrow = match expr.return_type() { + DataType::Int32 => true, + DataType::Int64 => false, + _ => return Err(Ok(Unsupported)), + }; + Ok(( + vec![Scoped::Same(input), Scoped::Same(search)], + Self { narrow }, + )) + } + + fn construct_fixed( + self, + [input, search]: [Expression; 2], + ctx: &Ctx, + ) -> MustConvert { + let Self { narrow } = self; + ensure_string(&input, ctx)?; + ensure_string(&search, ctx)?; + let position = strpos(input, search); + if narrow { + let nullable = ctx.node_dtype(&position)?.nullability(); + Ok(cast(position, DType::Primitive(PType::I32, nullable))) + } else { + Ok(position) + } + } +} + +/// Convert contains with a literal needle to a native LIKE expression. +pub struct ConvertContains { + pattern: String, +} + +impl<'a> ConvertibleFixedArity<'a> for ConvertContains { + type DF = ScalarFunctionExpr; + type Children = [Expression; 1]; + + fn convert_fixed( + expr: &'a ScalarFunctionExpr, + _ctx: &Ctx, + ) -> MustConvert<(Vec>, Self)> { + if !expr.fun().inner().is::() { + return Err(Ok(Unsupported)); + } + let [input, needle] = expr.args() else { + return Err(Err(exec_datafusion_err!( + "{} requires exactly two arguments", + expr.name() + ))); + }; + let Some(Some(needle)) = needle + .downcast_ref::() + .and_then(|literal| literal.value().try_as_str()) + else { + return Err(Ok(Unsupported)); + }; + let needle = escape_like(needle); + let pattern = format!("%{needle}%"); + Ok((vec![Scoped::Same(input)], Self { pattern })) + } + + fn construct_fixed(self, [input]: [Expression; 1], ctx: &Ctx) -> MustConvert { + let Self { pattern } = self; + ensure_string(&input, ctx)?; + Ok(Like.new_expr(LikeOptions::default(), [input, lit(pattern)])) + } +} + +/// Convert starts_with with a literal needle to a native LIKE expression. +pub struct ConvertStartsWith { + pattern: String, +} + +impl<'a> ConvertibleFixedArity<'a> for ConvertStartsWith { + type DF = ScalarFunctionExpr; + type Children = [Expression; 1]; + + fn convert_fixed( + expr: &'a ScalarFunctionExpr, + _ctx: &Ctx, + ) -> MustConvert<(Vec>, Self)> { + if !expr.fun().inner().is::() { + return Err(Ok(Unsupported)); + } + let [input, needle] = expr.args() else { + return Err(Err(exec_datafusion_err!( + "{} requires exactly two arguments", + expr.name() + ))); + }; + let Some(Some(needle)) = needle + .downcast_ref::() + .and_then(|literal| literal.value().try_as_str()) + else { + return Err(Ok(Unsupported)); + }; + let needle = escape_like(needle); + let pattern = format!("{needle}%"); + Ok((vec![Scoped::Same(input)], Self { pattern })) + } + + fn construct_fixed(self, [input]: [Expression; 1], ctx: &Ctx) -> MustConvert { + let Self { pattern } = self; + ensure_string(&input, ctx)?; + Ok(Like.new_expr(LikeOptions::default(), [input, lit(pattern)])) + } +} + +/// Convert ends_with with a literal needle to a native LIKE expression. +pub struct ConvertEndsWith { + pattern: String, +} + +impl<'a> ConvertibleFixedArity<'a> for ConvertEndsWith { + type DF = ScalarFunctionExpr; + type Children = [Expression; 1]; + + fn convert_fixed( + expr: &'a ScalarFunctionExpr, + _ctx: &Ctx, + ) -> MustConvert<(Vec>, Self)> { + if !expr.fun().inner().is::() { + return Err(Ok(Unsupported)); + } + let [input, needle] = expr.args() else { + return Err(Err(exec_datafusion_err!( + "{} requires exactly two arguments", + expr.name() + ))); + }; + let Some(Some(needle)) = needle + .downcast_ref::() + .and_then(|literal| literal.value().try_as_str()) + else { + return Err(Ok(Unsupported)); + }; + let needle = escape_like(needle); + let pattern = format!("%{needle}"); + Ok((vec![Scoped::Same(input)], Self { pattern })) + } + + fn construct_fixed(self, [input]: [Expression; 1], ctx: &Ctx) -> MustConvert { + let Self { pattern } = self; + ensure_string(&input, ctx)?; + Ok(Like.new_expr(LikeOptions::default(), [input, lit(pattern)])) + } +} + +/// Convert array_sum with matching null and NaN handling. +pub struct ConvertArraySum; + +impl<'a> ConvertibleFixedArity<'a> for ConvertArraySum { + type DF = ScalarFunctionExpr; + type Children = [Expression; 1]; + + fn convert_fixed( + expr: &'a ScalarFunctionExpr, + _ctx: &Ctx, + ) -> MustConvert<(Vec>, Self)> { + if !expr.fun().inner().is::() { + return Err(Ok(Unsupported)); + } + let [input] = expr.args() else { + return Err(Err(exec_datafusion_err!( + "array_sum requires exactly one argument" + ))); + }; + Ok((vec![Scoped::Same(input)], Self)) + } + + fn construct_fixed(self, [input]: [Expression; 1], _ctx: &Ctx) -> MustConvert { + Ok(list_sum_opts(input, NumericalAggregateOpts::include_nans())) + } +} + +/// Convert an array transform, selecting its lambda body in a separate parameter scope. +pub struct ConvertArrayTransform<'a> { + param: &'a str, + element_dtype: DType, +} + +impl<'a> ConvertibleFixedArity<'a> for ConvertArrayTransform<'a> { + type DF = HigherOrderFunctionExpr; + type Children = [Expression; 2]; + + fn convert_fixed(expr: &'a Self::DF, ctx: &Ctx) -> MustConvert<(Vec>, Self)> { + let function_impl: &dyn std::any::Any = expr.fun().inner().as_ref(); + if !function_impl.is::() { + return Err(Ok(Unsupported)); + } + let [list, lambda] = expr.args() else { + return Err(Err(exec_datafusion_err!( + "array_transform requires a list and a lambda" + ))); + }; + let Some(lambda) = lambda.downcast_ref::() else { + return Err(Ok(Unsupported)); + }; + let [param] = lambda.params() else { + return Err(Ok(Unsupported)); + }; + let field = list.return_field(ctx.schema).map_err(Err)?; + let DType::List(element, _) = ctx.arrow_dtype(&field)? else { + return Err(Ok(Unsupported)); + }; + let element_dtype = element.as_ref().clone(); + let scope = StructFields::from_iter([(param.as_str(), element_dtype.clone())]); + Ok(( + vec![Scoped::Same(list), Scoped::With(lambda.body(), scope)], + Self { + param, + element_dtype, + }, + )) + } + + fn construct_fixed(self, [list, body]: [Expression; 2], ctx: &Ctx) -> MustConvert { + let DType::List(element, _) = ctx.node_dtype(&list)? else { + return Err(Ok(Unsupported)); + }; + // The caller may substitute the list, but the body was converted in the selected scope. + if !element.eq_ignore_nullability(&self.element_dtype) { + return Err(Ok(Unsupported)); + } + // Within a lambda, `$.x` names its parameter; the native lambda reads it as `@x`. + let body = body + .transform_down(|node| { + if let Some(name) = node.as_opt::() + && node.child(0).is_root() + { + return Ok(Transformed::yes(var(name.clone()))); + } + Ok(Transformed::no(node)) + }) + .map(Transformed::into_inner) + .map_err(|_| Ok(Unsupported))?; + let lambda = Lambda::new([self.param], body).map_err(|_| Ok(Unsupported))?; + Ok(list_transform(list, lambda)) + } +} + +/// Matching and construction state used by [`ConvertCase`]. +pub struct ConvertCase { + num_pairs: usize, + n_children: usize, +} + +impl<'a> Convertible<'a> for ConvertCase { + type DF = df_expr::CaseExpr; + + fn convert(expr: &'a Self::DF, ctx: &Ctx) -> MustConvert<(Vec>, Self)> { + if expr.expr().is_some() { + return Err(Ok(Unsupported)); + } + let num_pairs = expr.when_then_expr().len(); + let mut children = Vec::with_capacity(num_pairs * 2 + 1); + for (condition, value) in expr.when_then_expr() { + if condition.data_type(ctx.schema).map_err(Err)? != DataType::Boolean { + return Err(Err(exec_datafusion_err!("CASE WHEN must be Boolean"))); + } + children.extend([Scoped::Same(condition), Scoped::Same(value)]); + } + children.extend(expr.else_expr().into_iter().map(Scoped::Same)); + let n_children = children.len(); + Ok(( + children, + Self { + num_pairs, + n_children, + }, + )) + } + + fn construct(self, children: Vec, _ctx: &Ctx) -> MustConvert { + let Self { + num_pairs, + n_children, + } = self; + let n = children.len(); + if n != n_children { + return Err(Err(exec_datafusion_err!( + "Expected {n_children} converted children, found {n}" + ))); + } + let mut children = children.into_iter(); + let pairs = children.by_ref().take(num_pairs * 2).tuples().collect_vec(); + let otherwise = children.next(); + Ok(nested_case_when(pairs, otherwise)) + } +} + +/// Escapes the LIKE wildcards and escape character in `literal`. +fn escape_like(literal: &str) -> String { + let mut escaped = String::with_capacity(literal.len()); + for c in literal.chars() { + if matches!(c, '%' | '_' | '\\') { + escaped.push('\\'); + } + escaped.push(c); + } + escaped +} + +fn ensure_string(expr: &Expression, ctx: &Ctx) -> MustConvert<()> { + if !ctx.node_dtype(expr)?.is_utf8() { + return Err(Ok(Unsupported)); + } + Ok(()) +} + +pub(crate) fn try_operator_from_df(value: &DFOperator) -> MustConvert { + match value { + DFOperator::Eq => Ok(Operator::Eq), + DFOperator::NotEq => Ok(Operator::NotEq), + DFOperator::Lt => Ok(Operator::Lt), + DFOperator::LtEq => Ok(Operator::Lte), + DFOperator::Gt => Ok(Operator::Gt), + DFOperator::GtEq => Ok(Operator::Gte), + DFOperator::And => Ok(Operator::And), + DFOperator::Or => Ok(Operator::Or), + DFOperator::Plus => Ok(Operator::Add), + DFOperator::Minus => Ok(Operator::Sub), + DFOperator::Multiply => Ok(Operator::Mul), + DFOperator::Divide => Ok(Operator::Div), + DFOperator::IsDistinctFrom + | DFOperator::IsNotDistinctFrom + | DFOperator::RegexMatch + | DFOperator::RegexIMatch + | DFOperator::RegexNotMatch + | DFOperator::RegexNotIMatch + | DFOperator::LikeMatch + | DFOperator::ILikeMatch + | DFOperator::NotLikeMatch + | DFOperator::NotILikeMatch + | DFOperator::BitwiseAnd + | DFOperator::BitwiseOr + | DFOperator::BitwiseXor + | DFOperator::BitwiseShiftRight + | DFOperator::BitwiseShiftLeft + | DFOperator::StringConcat + | DFOperator::AtArrow + | DFOperator::ArrowAt + | DFOperator::Modulo + | DFOperator::Arrow + | DFOperator::LongArrow + | DFOperator::HashArrow + | DFOperator::HashLongArrow + | DFOperator::AtAt + | DFOperator::IntegerDivide + | DFOperator::HashMinus + | DFOperator::AtQuestion + | DFOperator::Question + | DFOperator::QuestionAnd + | DFOperator::QuestionPipe + | DFOperator::Colon => Err(Ok(Unsupported)), + } +} + +pub(crate) fn supported_data_types(dt: &DataType) -> bool { + use DataType::*; + + // For dictionary and run-end encoded types, check if the value type is supported. Arrow's + // comparison kernels only unwrap run-end encoding as the outermost layer. + match dt { + Dictionary(_, value_type) => { + return !matches!(value_type.as_ref(), RunEndEncoded(..)) + && supported_data_types(value_type.as_ref()); + } + RunEndEncoded(_, values) => { + return !matches!(values.data_type(), RunEndEncoded(..)) + && supported_data_types(values.data_type()); + } + _ => {} + } + + let is_supported = dt.is_null() + || dt.is_numeric() + || dt.is_binary() + || dt.is_string() + || matches!( + dt, + Boolean | Date32 | Date64 | Timestamp(_, _) | Time32(_) | Time64(_) + ); + + if !is_supported { + tracing::debug!("DataFusion data type {dt:?} is not supported"); + } + + is_supported +} + +/// Returns the list argument of an `array_length` call that can be rewritten to `list_length`: +/// the single-argument form `array_length(arr)` or the equivalent explicit first dimension +/// `array_length(arr, 1)`. Other dimensions are unsupported (`None`); other arities are errors. +fn array_length_input(scalar_fn: &ScalarFunctionExpr) -> MustConvert<&PhysicalExprRef> { + match scalar_fn.args() { + [input] => Ok(input), + [input, dimension] + if dimension + .downcast_ref::() + .is_some_and(|literal| matches!(literal.value(), ScalarValue::Int64(Some(1)))) => + { + Ok(input) + } + [_, _] => Err(Ok(Unsupported)), + _ => Err(Err(exec_datafusion_err!( + "array_length requires one or two arguments" + ))), + } +} diff --git a/vortex-datafusion/src/convert/exprs/convertible/mod.rs b/vortex-datafusion/src/convert/exprs/convertible/mod.rs new file mode 100644 index 00000000000..fca1d3882e1 --- /dev/null +++ b/vortex-datafusion/src/convert/exprs/convertible/mod.rs @@ -0,0 +1,365 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright the Vortex contributors + +//! Protocols and context for converting one DataFusion expression at a time. + +use arrow_schema::Field; +use arrow_schema::Schema; +use arrow_schema::extension::EXTENSION_TYPE_METADATA_KEY; +use arrow_schema::extension::EXTENSION_TYPE_NAME_KEY; +use datafusion_common::DataFusionError; +use datafusion_common::exec_datafusion_err; +use datafusion_physical_expr::PhysicalExpr; +use datafusion_physical_expr::PhysicalExprRef; +use datafusion_physical_plan::expressions as df_expr; +use vortex::array::VortexSessionExecute as _; +use vortex::dtype::DType; +use vortex::dtype::Nullability; +use vortex::dtype::StructFields; +use vortex::expr::Expression; +use vortex::scalar::Scalar; +use vortex::scalar_fn::builtin::get_item::GetItem; +use vortex::session::VortexSession; +use vortex_arrow::ArrowSessionExt; + +mod impls; + +pub use impls::ConvertArrayLength; +pub use impls::ConvertArraySum; +pub use impls::ConvertArrayTransform; +pub use impls::ConvertBinary; +pub use impls::ConvertCase; +pub use impls::ConvertCast; +pub use impls::ConvertColumn; +pub use impls::ConvertContains; +pub use impls::ConvertEndsWith; +pub use impls::ConvertGetField; +pub use impls::ConvertInList; +pub use impls::ConvertIsNotNull; +pub use impls::ConvertIsNull; +pub use impls::ConvertLambdaVariable; +pub use impls::ConvertLike; +pub use impls::ConvertLiteral; +pub use impls::ConvertLower; +pub use impls::ConvertNot; +pub use impls::ConvertOctetLength; +pub use impls::ConvertStartsWith; +pub use impls::ConvertStrpos; +pub use impls::default_convert; +pub use impls::default_convert_recursive; +#[cfg(test)] +pub(super) use impls::supported_data_types; +#[cfg(test)] +pub(super) use impls::try_operator_from_df; + +/// A valid expression that this converter does not support. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Unsupported; + +/// A successful conversion, an unsupported expression (`Err(Ok(Unsupported))`), or an error. +pub type MustConvert = Result>; + +/// A converter that did not match (`Ok(Unsupported)`), or a conversion or error to return. +/// +/// Using `?` tries another converter only when this one did not match. +pub type MayConvert = Result>; + +/// Adapt a converter-chain result so `?` propagates unsupported conversions and errors. +/// +/// A converted value becomes `Ok(value)`; unsupported conversions become `Err(Ok(Unsupported))`. +/// Conversion errors are preserved. +pub fn must(x: MayConvert) -> MustConvert { + match x { + Ok(Unsupported) => Err(Ok(Unsupported)), + Err(Ok(value)) => Ok(value), + Err(Err(err)) => Err(Err(err)), + } +} + +/// Adapt a required conversion so `?` continues a converter chain only when it is unsupported. +/// +/// Unsupported conversions become `Ok(Unsupported)`; converted values and errors short-circuit +/// the chain through `Err`. +pub fn may(x: MustConvert) -> MayConvert { + match x { + Ok(value) => Err(Ok(value)), + Err(Ok(Unsupported)) => Ok(Unsupported), + Err(Err(err)) => Err(Err(err)), + } +} + +/// A selected expression child and the scope in which it should be converted. +#[derive(Debug)] +pub enum Scoped<'a> { + /// Convert in the parent's scope. + Same(&'a PhysicalExprRef), + /// Convert with these lambda parameters as the native root, replacing the enclosing scope. + With(&'a PhysicalExprRef, StructFields), +} + +/// Shared inputs for matching and constructing a native expression. +#[derive(Clone, Copy)] +pub struct ConvertibleCtx<'a> { + /// The DataFusion input schema. + pub schema: &'a Schema, + /// Session used to resolve Arrow types and import literals. + pub session: &'a VortexSession, + /// Lambda parameters read by the native root, or `None` for scan input columns. + pub scope: Option<&'a StructFields>, +} + +impl<'a> ConvertibleCtx<'a> { + /// Create a context for expressions over scan input columns. + pub fn new(schema: &'a Schema, session: &'a VortexSession) -> Self { + Self { + schema, + session, + scope: None, + } + } + + /// Resolve an Arrow field through the session registry; unknown types are unsupported. + pub fn arrow_dtype(&self, field: &Field) -> MustConvert { + self.session + .arrow() + .from_arrow_field(field) + .map_err(|_| Ok(Unsupported)) + } + + /// Resolve only the input fields read by the converted expression. Resolving a whole Arrow + /// schema here would reject otherwise supported expressions because of unrelated fields. + pub(super) fn node_dtype(&self, expr: &Expression) -> MustConvert { + let ConvertibleCtx { + schema, + session, + scope, + } = *self; + if let Some(name) = expr.as_opt::() + && expr.child(0).is_root() + { + if let Some(params) = scope { + return params.field(name).ok_or(Ok(Unsupported)); + } + let field = schema + .field_with_name(name.as_ref()) + .map_err(|_| Ok(Unsupported))?; + return self.arrow_dtype(field); + } + match expr { + Expression::Root => match scope { + Some(params) => Ok(DType::Struct(params.clone(), Nullability::NonNullable)), + None => session + .arrow() + .from_arrow_schema(schema) + .map_err(|_| Ok(Unsupported)), + }, + Expression::Variable(_) => Err(Ok(Unsupported)), + Expression::Scalar { + scalar_fn, + children, + } => { + let dtypes = children + .iter() + .map(|child| self.node_dtype(child)) + .collect::>>()?; + scalar_fn.return_dtype(&dtypes).map_err(|_| Ok(Unsupported)) + } + } + } + + /// Imports a literal, using `operand_field` only when the literal has no extension metadata. + /// + /// The literal keeps its Arrow dtype, so different storage types or timestamp units still fail + /// the comparison's dtype check. Explicit metadata, including an unknown extension, is preserved. + /// The inherited extension name and payload both come from `operand_field`, including an absent + /// payload, so the import cannot combine metadata from two different types. + fn import_literal_for_operand( + &self, + literal: &df_expr::Literal, + operand_field: &Field, + ) -> MustConvert { + let field = literal.return_field(self.schema).map_err(Err)?; + if field.extension_type_name().is_some() || operand_field.extension_type_name().is_none() { + return self.import_literal(literal, &field); + } + + let mut field = field.as_ref().clone(); + for key in [EXTENSION_TYPE_NAME_KEY, EXTENSION_TYPE_METADATA_KEY] { + field.metadata_mut().remove(key); + if let Some(value) = operand_field.metadata().get(key) { + field.metadata_mut().insert(key.into(), value.clone()); + } + } + + self.import_literal(literal, &field) + } + + /// Imports one scalar through the session's Arrow plugins, preserving `field`'s metadata. + /// + /// A literal that the plugins reject stays in DataFusion, including when a plugin accepts the + /// field but rejects the value. + fn import_literal(&self, literal: &df_expr::Literal, field: &Field) -> MustConvert { + let array = literal.value().to_array().map_err(Err)?; + if array.len() != 1 { + return Err(Err(exec_datafusion_err!( + "Literal must contain exactly one value, got {}", + array.len() + ))); + } + + self.arrow_dtype(field)?; + + self.session + .arrow() + .from_arrow_array(array, field) + .map_err(|_| Ok(Unsupported))? + .execute_scalar(0, &mut self.session.create_execution_ctx()) + .map_err(|error| { + Err(DataFusionError::External(Box::new(error.with_context( + format!("Failed to convert literal {literal}"), + )))) + }) + } +} + +/// Convert a specific DataFusion expression type to a Vortex expression. +/// +/// This API is "single step". The implementor merely defines how to recognize one-level of a +/// DataFusion expression. The caller is responsible for orchestrating a recursive tree walk. +/// +/// Implementors must define: +/// +/// 1. The type of DataFusion expression which they convert. +/// +/// 2. The DataFusion children which they need converted and any state they need for later +/// conversion. +/// +/// 3. How to construct the converted Vortex expression given children which the caller has +/// converted to Vortex. +pub trait Convertible<'a>: Sized + 'a { + /// The DataFusion expression matched by this converter. + type DF: PhysicalExpr; + + /// Recognize (or not) an expression which we can convert to a Vortex expression. + fn recognize( + expr: &'a PhysicalExprRef, + ctx: &ConvertibleCtx<'_>, + ) -> MayConvert<(Vec>, Self)> { + let Some(expr) = expr.downcast_ref::() else { + return Ok(Unsupported); + }; + may(Self::convert(expr, ctx)) + } + + /// Recognize (or not) an expression which we can convert to a Vortex expression. + fn recognize_boxed( + expr: &'a PhysicalExprRef, + ctx: &ConvertibleCtx<'_>, + ) -> MayConvert<(Vec>, Box)> { + may( + must(Self::recognize(expr, ctx)).map(|(children, convertible)| { + ( + children, + Box::new(convertible) as Box, + ) + }), + ) + } + + /// Try this converter, using the caller's recursion to convert its selected inputs. + /// + /// The callback receives each child and is responsible for handling its scope. + /// + /// Returns `Err(Ok(Unsupported))` for an unsupported node, child, or constructed expression. + fn convert_recursive( + expr: &'a PhysicalExprRef, + ctx: &ConvertibleCtx<'_>, + recur: impl FnMut(Scoped<'a>) -> MustConvert, + ) -> MustConvert { + let (children, convertible) = must(Self::recognize(expr, ctx))?; + let children = children + .into_iter() + .map(recur) + .collect::>>()?; + convertible.construct(children, ctx) + } + + /// Convert a specific DataFusion expression to a Vortex expression. + fn convert( + expr: &'a Self::DF, + ctx: &ConvertibleCtx<'_>, + ) -> MustConvert<(Vec>, Self)>; + + /// Given Vortex expressions for our children, construct a Vortex expression for ourselves. + fn construct( + self, + children: Vec, + ctx: &ConvertibleCtx<'_>, + ) -> MustConvert; +} + +/// A converter whose concrete type has been erased for deferred construction. +pub trait Constructible { + /// Given Vortex expressions for our children, construct a Vortex expression for ourselves. + fn construct( + self: Box, + children: Vec, + ctx: &ConvertibleCtx<'_>, + ) -> MustConvert; +} + +impl<'a, T: Convertible<'a>> Constructible for T { + fn construct( + self: Box, + children: Vec, + ctx: &ConvertibleCtx<'_>, + ) -> MustConvert { + >::construct(*self, children, ctx) + } +} + +/// Typed construction for fixed-arity converters, adapted to [`Convertible`] below. +pub trait ConvertibleFixedArity<'a>: Sized { + /// The DataFusion expression matched by this converter. + type DF: PhysicalExpr; + /// The converted children, represented by an `[Expression; N]` array. + type Children: TryFrom>; + + /// Select inputs and capture the configuration of a typed DataFusion node. + fn convert_fixed( + expr: &'a Self::DF, + ctx: &ConvertibleCtx<'_>, + ) -> MustConvert<(Vec>, Self)>; + + /// Construct from the fixed-size array, using the supplied context. + fn construct_fixed( + self, + children: Self::Children, + ctx: &ConvertibleCtx<'_>, + ) -> MustConvert; +} + +impl<'a, T: ConvertibleFixedArity<'a> + 'a> Convertible<'a> for T { + type DF = >::DF; + + fn convert( + expr: &'a >::DF, + ctx: &ConvertibleCtx<'_>, + ) -> MustConvert<(Vec>, Self)> { + >::convert_fixed(expr, ctx) + } + + fn construct( + self, + children: Vec, + ctx: &ConvertibleCtx<'_>, + ) -> MustConvert { + let count = children.len(); + let children = T::Children::try_from(children).map_err(|_| { + Err(exec_datafusion_err!( + "Cannot construct expression from {count} converted children" + )) + })?; + >::construct_fixed(self, children, ctx) + } +} diff --git a/vortex-datafusion/src/convert/exprs/mod.rs b/vortex-datafusion/src/convert/exprs/mod.rs index 5b3c383f78d..eb2098a5489 100644 --- a/vortex-datafusion/src/convert/exprs/mod.rs +++ b/vortex-datafusion/src/convert/exprs/mod.rs @@ -11,79 +11,39 @@ use std::sync::Arc; use arrow_schema::DataType; use arrow_schema::Field; -use arrow_schema::FieldRef; use arrow_schema::Schema; -use arrow_schema::extension::EXTENSION_TYPE_METADATA_KEY; -use arrow_schema::extension::EXTENSION_TYPE_NAME_KEY; use datafusion_common::DataFusionError; use datafusion_common::Result as DFResult; -use datafusion_common::ScalarValue; use datafusion_common::exec_datafusion_err; -use datafusion_common::format::DEFAULT_FORMAT_OPTIONS; use datafusion_common::tree_node::Transformed as DFTransformed; use datafusion_common::tree_node::TreeNode; -use datafusion_expr::Operator as DFOperator; -use datafusion_functions::core::getfield::GetFieldFunc; -use datafusion_functions::string::contains::ContainsFunc; -use datafusion_functions::string::ends_with::EndsWithFunc; -use datafusion_functions::string::lower::LowerFunc; -use datafusion_functions::string::octet_length::OctetLengthFunc; -use datafusion_functions::string::starts_with::StartsWithFunc; -use datafusion_functions::unicode::strpos::StrposFunc; -use datafusion_functions_nested::array_sum::ArraySum; -use datafusion_functions_nested::array_transform::ArrayTransform; -use datafusion_functions_nested::length::ArrayLength; use datafusion_physical_expr::DynamicFilterTracking; -use datafusion_physical_expr::HigherOrderFunctionExpr; use datafusion_physical_expr::PhysicalExpr; -use datafusion_physical_expr::ScalarFunctionExpr; use datafusion_physical_expr::projection::ProjectionExprs; use datafusion_physical_expr::utils::collect_columns; use datafusion_physical_plan::expressions as df_expr; use itertools::Itertools; use vortex::VortexSessionDefault; -use vortex::aggregate_fn::NumericalAggregateOpts; -use vortex::array::VortexSessionExecute; use vortex::dtype::DType; use vortex::dtype::Nullability; -use vortex::dtype::PType; -use vortex::dtype::StructFields; use vortex::expr::Expression; -use vortex::expr::Lambda; -use vortex::expr::byte_length; -use vortex::expr::cast; -use vortex::expr::ext_storage; use vortex::expr::get_item; -use vortex::expr::in_list_of; -use vortex::expr::is_not_null; -use vortex::expr::is_null; -use vortex::expr::list_length; -use vortex::expr::list_sum_opts; -use vortex::expr::list_transform; -use vortex::expr::lit; -use vortex::expr::lower; -use vortex::expr::nested_case_when; -use vortex::expr::not; use vortex::expr::pack; use vortex::expr::root; -use vortex::expr::strpos; -use vortex::expr::traversal::NodeExt; -use vortex::expr::traversal::Transformed; -use vortex::expr::var; -use vortex::functions::like::Like; -use vortex::functions::like::LikeOptions; use vortex::layout::layouts::row_idx; -use vortex::scalar::Scalar; -use vortex::scalar_fn::ScalarFnVTableExt; -use vortex::scalar_fn::builtin::binary::Binary; -use vortex::scalar_fn::builtin::get_item::GetItem; -use vortex::scalar_fn::builtin::literal::Literal; -use vortex::scalar_fn::builtin::operators::Operator; use vortex::session::VortexSession; use vortex_arrow::ArrowSessionExt; +use self::convertible::ConvertibleCtx; +use self::convertible::MustConvert; +use self::convertible::Scoped; +use self::convertible::Unsupported; +use self::convertible::default_convert_recursive; +use self::convertible::must; use crate::row_index::RowIndex; +pub mod convertible; + /// Result of splitting a projection into Vortex expressions and leftover DataFusion projections. pub struct ProcessedProjection { /// Projection evaluated by the Vortex scan. @@ -245,160 +205,6 @@ pub(crate) fn raw_projection( }) } -/// Why an expression was not converted. -enum Unconverted { - /// A valid expression that Vortex cannot evaluate; it stays in DataFusion. - Unsupported, - /// A malformed expression or a failed conversion. - Failed(DataFusionError), -} - -impl From for Unconverted { - fn from(error: DataFusionError) -> Self { - Self::Failed(error) - } -} - -/// Conversion result where `?` propagates both unsupported expressions and errors. -type Conversion = Result; - -/// Constructs a native node from its converted children in the selected order. -pub type ExpressionConstructor<'a> = - Box) -> DFResult> + 'a>; - -/// A recognized node and the inputs the caller should convert before constructing it. -pub struct NodeConversion<'a> { - /// Inputs to convert, in construction order. - pub children: Vec<&'a Arc>, - /// Construct the node, returning `None` for incompatible converted inputs. - pub construct: ExpressionConstructor<'a>, -} - -impl<'a> NodeConversion<'a> { - fn new( - children: Vec<&'a Arc>, - converter: &DefaultExpressionConverter, - construct: impl FnOnce(&DefaultExpressionConverter, Vec) -> Conversion - + 'a, - ) -> Self { - let arity = children.len(); - let converter = DefaultExpressionConverter { - session: converter.session.clone(), - scope: converter.scope.clone(), - }; - Self { - children, - construct: Box::new(move |children| { - if children.len() != arity { - return Err(exec_datafusion_err!( - "Expected {arity} converted children, found {}", - children.len() - )); - } - conversion_result(construct(&converter, children)) - }), - } - } - - fn fixed( - children: [&'a Arc; N], - converter: &DefaultExpressionConverter, - construct: impl FnOnce(&DefaultExpressionConverter, [Expression; N]) -> Conversion - + 'a, - ) -> Self { - Self::new(Vec::from(children), converter, move |converter, children| { - let children = children - .try_into() - .map_err(|_| exec_datafusion_err!("Expected {N} converted children"))?; - construct(converter, children) - }) - } -} - -fn conversion_result(result: Conversion) -> DFResult> { - match result { - Ok(converted) => Ok(Some(converted)), - Err(Unconverted::Unsupported) => Ok(None), - Err(Unconverted::Failed(error)) => Err(error), - } -} - -/// Recognize one node without converting its selected children. -/// -/// Convert `children` using your own traversal, then call `construct` with those results. -/// Field paths remain configuration and repeated IN literals are deduplicated before traversal. -/// Unlike [`ExpressionConverter::try_convert`], this does not validate the whole tree or its -/// column references and result dtype. Lambda-scoped traversal stays with the recursive converter. -pub fn try_convert_node<'a>( - expr: &'a Arc, - schema: &'a Schema, - session: &'a VortexSession, -) -> DFResult>> { - conversion_result(DefaultExpressionConverter::new(session.clone()).convert_expr(expr, schema)) -} - -fn next_child(children: &mut impl Iterator) -> Conversion { - children - .next() - .ok_or_else(|| exec_datafusion_err!("Missing converted child").into()) -} - -enum BinaryOperand<'a> { - Child, - Literal { - literal: &'a df_expr::Literal, - field: FieldRef, - }, -} - -impl BinaryOperand<'_> { - fn construct( - self, - children: &mut impl Iterator, - converter: &DefaultExpressionConverter, - schema: &Schema, - ) -> Conversion { - match self { - Self::Child => next_child(children), - Self::Literal { literal, field } => Ok(lit(converter.import_literal_for_operand( - literal, &field, schema, - )?)), - } - } -} - -enum InListElements<'a> { - Children, - Imported { - literals: Vec<&'a Arc>, - field: FieldRef, - }, -} - -impl InListElements<'_> { - fn construct( - self, - children: impl Iterator, - converter: &DefaultExpressionConverter, - schema: &Schema, - ) -> Conversion> { - match self { - Self::Children => children - .map(|expr| expr.as_opt::().cloned().ok_or(Unconverted::Unsupported)) - .collect(), - Self::Imported { literals, field } => literals - .into_iter() - .map(|expr| { - let literal = expr - .downcast_ref::() - .ok_or(Unconverted::Unsupported)?; - converter.import_literal_for_operand(literal, &field, schema) - }) - .collect(), - } - } -} - /// The default [`ExpressionConverter`] implementation. /// /// Supported arithmetic is pushed down using Vortex semantics, including its checked @@ -417,18 +223,6 @@ pub struct DefaultExpressionConverter { /// `FixedSizeBinary[16]`) convert correctly instead of hitting the static, /// non-plugin-aware `DType::from_arrow`. session: VortexSession, - /// What `$` is in the expressions this converts. - scope: Scope, -} - -/// What `$` is where an expression is converted. -#[derive(Clone)] -enum Scope { - /// Outside any lambda, the scan's columns: a column `c` reads `$.c`. - Global, - /// A lambda's parameters: a parameter `x` reads `$.x`, as Vortex runs a lambda's body. Vortex - /// lambdas can't read columns yet. - Lambda(StructFields), } impl Default for DefaultExpressionConverter { @@ -441,26 +235,7 @@ impl DefaultExpressionConverter { /// Create a converter that resolves Arrow extension types using `session`'s /// dtype registry. pub fn new(session: VortexSession) -> Self { - Self { - session, - scope: Scope::Global, - } - } - - /// Resolve an Arrow field through the session registry; unknown types are unsupported. - fn arrow_dtype(&self, field: &Field) -> Conversion { - self.session - .arrow() - .from_arrow_field(field) - .map_err(|_| Unconverted::Unsupported) - } - - fn node_dtype(&self, expr: &Expression, schema: &Schema) -> Conversion { - let scope = match &self.scope { - Scope::Global => None, - Scope::Lambda(params) => Some(params), - }; - node_dtype(expr, schema, &self.session, scope) + Self { session } } /// Convert `expr` and check that it returns the dtype DataFusion expects. @@ -468,25 +243,29 @@ impl DefaultExpressionConverter { &self, expr: &Arc, schema: &Schema, - ) -> Conversion { + ) -> MustConvert { + let ctx = ConvertibleCtx::new(schema, &self.session); let columns = collect_columns(expr); let mut column_indices = Vec::with_capacity(columns.len()); for column in columns { - let field = schema.fields().get(column.index()).ok_or_else(|| { - exec_datafusion_err!( - "Column {}@{} is out of bounds", - column.name(), - column.index() - ) - })?; + let field = schema + .fields() + .get(column.index()) + .ok_or_else(|| { + exec_datafusion_err!( + "Column {}@{} is out of bounds", + column.name(), + column.index() + ) + }) + .map_err(Err)?; if field.name() != column.name() { - return Err(exec_datafusion_err!( + return Err(Err(exec_datafusion_err!( "Column {}@{} refers to field {}", column.name(), column.index(), field.name() - ) - .into()); + ))); } column_indices.push(column.index()); } @@ -498,642 +277,28 @@ impl DefaultExpressionConverter { .from_arrow_schema( &schema .project(&column_indices) - .map_err(DataFusionError::from)?, + .map_err(DataFusionError::from) + .map_err(Err)?, ) - .map_err(|_| Unconverted::Unsupported)?; - let converted = self.convert_tree(expr, schema, &input_dtype)?; + .map_err(|_| Ok(Unsupported))?; + let converted = convert_tree(expr, &ctx)?; // `return_field` names the field by formatting the whole expression. For the IN list of a // hash join filter, with thousands of keys, that costs more than the conversion. A // predicate has no field metadata, so its type and nullability are enough. - let expected_dtype = if expr.data_type(schema)? == DataType::Boolean { - DType::Bool(expr.nullable(schema)?.into()) + let expected_dtype = if expr.data_type(schema).map_err(Err)? == DataType::Boolean { + DType::Bool(expr.nullable(schema).map_err(Err)?.into()) } else { - self.arrow_dtype(expr.return_field(schema)?.as_ref())? + ctx.arrow_dtype(expr.return_field(schema).map_err(Err)?.as_ref())? }; - if !converted_dtype(&converted, &input_dtype)?.eq_ignore_nullability(&expected_dtype) { - return Err(Unconverted::Unsupported); - } - Ok(converted) - } - - fn convert_tree( - &self, - expr: &Arc, - schema: &Schema, - input_dtype: &DType, - ) -> Conversion { - if let Some(function) = expr.downcast_ref::() { - let function_impl: &dyn std::any::Any = function.fun().inner().as_ref(); - if function_impl.downcast_ref::().is_some() { - return self.convert_array_transform(function, schema, input_dtype); - } - return Err(Unconverted::Unsupported); - } - let node = self.convert_expr(expr, schema)?; - let children = node - .children - .iter() - .map(|child| self.convert_tree(child, schema, input_dtype)) - .collect::>>()?; - (node.construct)(children)?.ok_or(Unconverted::Unsupported) - } - - fn convert_expr<'a>( - &self, - expr: &'a Arc, - schema: &'a Schema, - ) -> Conversion> { - if expr.is::() { - return Ok(NodeConversion::fixed([], self, |_, []| { - Ok(row_idx::row_idx()) - })); - } - if let Some(binary_expr) = expr.downcast_ref::() { - let operator = - try_operator_from_df(binary_expr.op()).ok_or(Unconverted::Unsupported)?; - let boolean_operator = matches!(operator, Operator::And | Operator::Or); - let left_type = binary_expr.left().data_type(schema)?; - let right_type = binary_expr.right().data_type(schema)?; - if boolean_operator { - if left_type != DataType::Boolean || right_type != DataType::Boolean { - return Err(exec_datafusion_err!( - "Boolean operator requires Boolean operands: {expr}" - ) - .into()); - } - } else if !supported_data_types(&left_type) || !supported_data_types(&right_type) { - return Err(Unconverted::Unsupported); - } - let mut children = Vec::with_capacity(2); - let left = self.convert_binary_operand( - binary_expr.left(), - binary_expr.right(), - operator, - schema, - &mut children, - )?; - let right = self.convert_binary_operand( - binary_expr.right(), - binary_expr.left(), - operator, - schema, - &mut children, - )?; - - return Ok(NodeConversion::new(children, self, move |converter, children| { - let mut children = children.into_iter(); - let left = left.construct(&mut children, converter, schema)?; - let right = right.construct(&mut children, converter, schema)?; - // DataFusion may evaluate the RHS only on rows selected by the LHS. - if boolean_operator && !(is_infallible(&left) && is_infallible(&right)) { - return Err(Unconverted::Unsupported); - } - if !converter.node_dtype(&left, schema)? - .eq_ignore_nullability(&converter.node_dtype(&right, schema)?) - { - return Err(Unconverted::Unsupported); - } - Ok(Binary.new_expr(operator, [left, right])) - })); - } - - if let Some(col_expr) = expr.downcast_ref::() { - return match self.scope { - Scope::Global => Ok(NodeConversion::fixed([], self, move |_, []| { - Ok(get_item(col_expr.name(), root())) - })), - Scope::Lambda(_) => Err(Unconverted::Unsupported), - }; - } - - if let Some(variable) = expr.downcast_ref::() { - return match &self.scope { - Scope::Lambda(params) if params.find(variable.name()).is_some() => { - Ok(NodeConversion::fixed([], self, move |_, []| { - Ok(get_item(variable.name(), root())) - })) - } - // Outside any lambda, or a parameter of an enclosing lambda, which Vortex lambdas - // can't read yet. - _ => Err(Unconverted::Unsupported), - }; - } - - if let Some(literal) = expr.downcast_ref::() { - let field = literal.return_field(schema)?; - - let literal = self.import_literal(literal, &field)?; - return Ok(NodeConversion::fixed([], self, move |_, []| Ok(lit(literal)))); - } - - if let Some(cast_expr) = expr.downcast_ref::() { - let pushdown = classify_cast(cast_expr, schema)?; - // DataFusion casts preserve input nulls even when the target field is declared - // non-nullable. Match the expression's runtime nullability rather than narrowing - // to the target field's metadata. - let cast_dtype = self - .arrow_dtype(cast_expr.target_field())? - .with_nullability(Nullability::from(cast_expr.nullable(schema)?)); - return Ok(NodeConversion::fixed([cast_expr.expr()], self, move |converter, [child]| { - let child_dtype = converter.node_dtype(&child, schema)?; - match pushdown { - // Matching Arrow types do not imply matching Vortex dtypes, e.g. for extensions. - CastPushdown::Drop if child_dtype.eq_ignore_nullability(&cast_dtype) => Ok(child), - CastPushdown::Drop => Err(Unconverted::Unsupported), - CastPushdown::Keep => { - // Matching Arrow storage types do not imply matching extension semantics. - if (child_dtype.is_extension() || cast_dtype.is_extension()) - && !child_dtype.eq_ignore_nullability(&cast_dtype) - { - return Err(Unconverted::Unsupported); - } - Ok(cast(child, cast_dtype)) - } - } - })); - } - - if let Some(not_expr) = expr.downcast_ref::() { - if not_expr.arg().data_type(schema)? != DataType::Boolean { - return Err(exec_datafusion_err!("NOT requires a Boolean operand: {expr}").into()); - } - return Ok(NodeConversion::fixed([not_expr.arg()], self, |_, [arg]| Ok(not(arg)))); - } - - if let Some(is_null_expr) = expr.downcast_ref::() { - return Ok(NodeConversion::fixed([is_null_expr.arg()], self, |_, [arg]| Ok(is_null(arg)))); - } - - if let Some(is_not_null_expr) = expr.downcast_ref::() { - return Ok(NodeConversion::fixed([is_not_null_expr.arg()], self, |_, [arg]| Ok(is_not_null(arg)))); - } - - if let Some(like) = expr.downcast_ref::() { - // Dictionary-encoded strings convert to Utf8 too. - let options = LikeOptions { - negated: like.negated(), - case_insensitive: like.case_insensitive(), - }; - return Ok(NodeConversion::fixed( - [like.expr(), like.pattern()], - self, - move |converter, [child, pattern]| { - let child = converter.convert_string(child, schema)?; - let pattern = converter.convert_string(pattern, schema)?; - Ok(Like.new_expr(options, [child, pattern])) - }, - )); - } - - if let Some(in_list) = expr.downcast_ref::() { - return self.convert_in_list(in_list, schema); - } - - if let Some(scalar_fn) = expr.downcast_ref::() { - return self.convert_scalar_function(scalar_fn, schema); - } - - if let Some(case_expr) = expr.downcast_ref::() { - return self.convert_case_expr(case_expr, schema); - } - - Err(Unconverted::Unsupported) - } - - /// Selects a binary operand, using the other operand's field to type comparison literals. - /// - /// Arithmetic and Boolean operands convert independently. They do not accept extension dtypes, - /// so the other operand cannot supply an expected extension type for their literals. - fn convert_binary_operand<'a>( - &self, - expr: &'a Arc, - other: &Arc, - operator: Operator, - schema: &Schema, - children: &mut Vec<&'a Arc>, - ) -> Conversion> { - if operator.is_comparison() - && let Some(literal) = expr.downcast_ref::() - && literal.return_field(schema)?.extension_type_name().is_none() + if !converted + .return_dtype(&input_dtype) + .map_err(|_| Ok(Unsupported))? + .eq_ignore_nullability(&expected_dtype) { - let field = other.return_field(schema)?; - if field.extension_type_name().is_some() { - return Ok(BinaryOperand::Literal { literal, field }); - } - } - children.push(expr); - Ok(BinaryOperand::Child) - } - - /// Imports a literal, using `operand_field` only when the literal has no extension metadata. - /// - /// The literal keeps its Arrow dtype, so different storage types or timestamp units still fail - /// the comparison's dtype check. Explicit metadata, including an unknown extension, is preserved. - /// The inherited extension name and payload both come from `operand_field`, including an absent - /// payload, so the import cannot combine metadata from two different types. - fn import_literal_for_operand( - &self, - literal: &df_expr::Literal, - operand_field: &Field, - schema: &Schema, - ) -> Conversion { - let field = literal.return_field(schema)?; - if field.extension_type_name().is_some() || operand_field.extension_type_name().is_none() { - return self.import_literal(literal, &field); - } - - let mut field = field.as_ref().clone(); - for key in [EXTENSION_TYPE_NAME_KEY, EXTENSION_TYPE_METADATA_KEY] { - field.metadata_mut().remove(key); - if let Some(value) = operand_field.metadata().get(key) { - field.metadata_mut().insert(key.into(), value.clone()); - } - } - - self.import_literal(literal, &field) - } - - /// Imports one scalar through the session's Arrow plugins, preserving `field`'s metadata. - /// - /// A literal that the plugins reject stays in DataFusion, including when a plugin accepts the - /// field but rejects the value. - fn import_literal(&self, literal: &df_expr::Literal, field: &Field) -> Conversion { - let array = literal.value().to_array()?; - if array.len() != 1 { - return Err(exec_datafusion_err!( - "Literal must contain exactly one value, got {}", - array.len() - ) - .into()); - } - - self.arrow_dtype(field)?; - - self.session - .arrow() - .from_arrow_array(array, field) - .map_err(|_| Unconverted::Unsupported)? - .execute_scalar(0, &mut self.session.create_execution_ctx()) - .map_err(|error| { - Unconverted::Failed(DataFusionError::External(Box::new( - error.with_context(format!("Failed to convert literal {literal}")), - ))) - }) - } - - /// Converts a string argument of a string function. - fn convert_string( - &self, - converted: Expression, - schema: &Schema, - ) -> Conversion { - if !self.node_dtype(&converted, schema)?.is_utf8() { - return Err(Unconverted::Unsupported); + return Err(Ok(Unsupported)); } Ok(converted) } - - fn convert_in_list<'a>( - &self, - in_list: &'a df_expr::InListExpr, - schema: &'a Schema, - ) -> Conversion> { - let value_type = in_list.expr().data_type(schema)?; - if in_list.is_empty() - || !in_list - .list() - .iter() - .all(|expr| expr.is::()) - || !supported_data_types(&value_type) - { - return Err(Unconverted::Unsupported); - } - // DataFusion reads the nulls of a run-end encoded list from its physical validity, which - // is always empty, so it ignores a NULL element that SQL, and Vortex, do not. - if matches!(value_type, DataType::RunEndEncoded(..)) - && in_list.list().iter().any(|element| { - element - .downcast_ref::() - .is_some_and(|literal| literal.value().is_null()) - }) - { - return Err(Unconverted::Unsupported); - } - let value_field = in_list.expr().return_field(schema)?; - // The list of a hash join filter holds every build-side key, which repeat. Each element - // converts through Arrow, so equal values with equal metadata are converted once. - let literals = in_list - .list() - .iter() - .unique_by(|element| element.downcast_ref::().cloned()) - .collect_vec(); - let mut children = vec![in_list.expr()]; - let elements = if value_field.extension_type_name().is_some() { - InListElements::Imported { literals, field: value_field } - } else { - children.extend(literals); - InListElements::Children - }; - let negated = in_list.negated(); - Ok(NodeConversion::new(children, self, move |converter, children| { - let mut children = children.into_iter(); - let value = next_child(&mut children)?; - // Boolean rewrites may skip evaluating the input, particularly for all-null lists. - if !is_infallible(&value) { - return Err(Unconverted::Unsupported); - } - let value_dtype = converter.node_dtype(&value, schema)?; - let elements = elements.construct(children, converter, schema)?; - // An element of another type than the value declines the pushdown: no implicit casts. - let membership = - in_list_of(value, value_dtype, elements).map_err(|_| Unconverted::Unsupported)?; - Ok(if negated { not(membership) } else { membership }) - })) - } - - fn convert_scalar_function<'a>( - &self, - scalar_fn: &'a ScalarFunctionExpr, - schema: &'a Schema, - ) -> Conversion> { - if ScalarFunctionExpr::try_downcast_func::(scalar_fn).is_some() { - let [input] = scalar_fn.args() else { - return Err(exec_datafusion_err!("lower requires exactly one argument").into()); - }; - return Ok(NodeConversion::fixed([input], self, move |converter, [input]| { - Ok(lower(converter.convert_string(input, schema)?)) - })); - } - - if ScalarFunctionExpr::try_downcast_func::(scalar_fn).is_some() { - let [input, search] = scalar_fn.args() else { - return Err(exec_datafusion_err!("strpos requires exactly two arguments").into()); - }; - if !matches!(scalar_fn.return_type(), DataType::Int32 | DataType::Int64) { - return Err(Unconverted::Unsupported); - } - return Ok(NodeConversion::fixed([input, search], self, move |converter, [input, search]| { - let position = strpos( - converter.convert_string(input, schema)?, - converter.convert_string(search, schema)?, - ); - match scalar_fn.return_type() { - DataType::Int64 => Ok(position), - // DataFusion only returns Int32 for strings with 32-bit offsets, whose positions - // fit. - DataType::Int32 => { - let nullability = converter.node_dtype(&position, schema)?.nullability(); - Ok(cast(position, DType::Primitive(PType::I32, nullability))) - } - _ => Err(Unconverted::Unsupported), - } - })); - } - - let like_pattern: Option String> = - if ScalarFunctionExpr::try_downcast_func::(scalar_fn).is_some() { - Some(|needle| format!("%{needle}%")) - } else if ScalarFunctionExpr::try_downcast_func::(scalar_fn).is_some() { - Some(|needle| format!("{needle}%")) - } else if ScalarFunctionExpr::try_downcast_func::(scalar_fn).is_some() { - Some(|needle| format!("%{needle}")) - } else { - None - }; - if let Some(like_pattern) = like_pattern { - let [input, needle] = scalar_fn.args() else { - return Err(exec_datafusion_err!( - "{} requires exactly two arguments", - scalar_fn.name() - ) - .into()); - }; - // Only a literal needle becomes a LIKE pattern that encodings and stats can use. - let Some(Some(needle)) = needle - .downcast_ref::() - .and_then(|literal| literal.value().try_as_str()) - else { - return Err(Unconverted::Unsupported); - }; - let pattern = like_pattern(&escape_like(needle)); - return Ok(NodeConversion::fixed([input], self, move |converter, [input]| { - Ok(Like.new_expr( - LikeOptions::default(), - [converter.convert_string(input, schema)?, lit(pattern)], - )) - })); - } - - if ScalarFunctionExpr::try_downcast_func::(scalar_fn).is_some() { - return self.convert_get_field(scalar_fn, schema); - } - - if ScalarFunctionExpr::try_downcast_func::(scalar_fn).is_some() { - return self.convert_array_sum(scalar_fn); - } - - let (input, length): (_, fn(Expression) -> Expression) = - if ScalarFunctionExpr::try_downcast_func::(scalar_fn).is_some() { - let [input] = scalar_fn.args() else { - return Err( - exec_datafusion_err!("octet_length requires exactly one argument").into(), - ); - }; - let data_type = input.data_type(schema)?; - let data_type = match &data_type { - DataType::Dictionary(_, value) => value.as_ref(), - data_type => data_type, - }; - if !data_type.is_binary() && !data_type.is_string() { - return Err(Unconverted::Unsupported); - } - (input, byte_length) - } else if ScalarFunctionExpr::try_downcast_func::(scalar_fn).is_some() { - let input = array_length_input(scalar_fn)?.ok_or(Unconverted::Unsupported)?; - if !matches!( - input.data_type(schema)?, - DataType::List(_) | DataType::LargeList(_) | DataType::FixedSizeList(_, _) - ) { - return Err(Unconverted::Unsupported); - } - (input, list_length) - } else { - return Err(Unconverted::Unsupported); - }; - let return_dtype = self.arrow_dtype(&Field::new( - "", - scalar_fn.return_type().clone(), - scalar_fn.nullable(), - ))?; - Ok(NodeConversion::fixed([input], self, move |_, [input]| { - Ok(cast(length(input), return_dtype)) - })) - } - - /// Converts `get_field` to a chain of `get_item` reads. - /// - /// DataFusion can flatten nested access into one call, so `outer.inner.leaf` can arrive as - /// `get_field(outer, "inner", "leaf")`. - /// - /// Vortex extension types are opaque, so `get_item` cannot read into an extension value until - /// `ext_storage` exposes its storage. The converter can add that `ext_storage` without breaking - /// the opacity, because DataFusion already reads the storage: an Arrow extension type is only - /// metadata on its storage field, and `get_field` reads that field like any other struct. Both - /// sides read the same values only when Vortex exports the parent as exactly its storage, which - /// [`exports_extension_storage`] checks. - /// - /// [`exports_extension_storage`]: vortex_arrow::ArrowSession::exports_extension_storage - fn convert_get_field<'a>( - &self, - scalar_fn: &'a ScalarFunctionExpr, - schema: &'a Schema, - ) -> Conversion> { - let [source, paths @ ..] = scalar_fn.args() else { - return Err(exec_datafusion_err!("get_field requires a source and field path").into()); - }; - - if paths.is_empty() { - return Err(exec_datafusion_err!("get_field requires a field path").into()); - } - - // Keep the Arrow field of each step, because its metadata decides how Vortex exports it. - let mut field = source.return_field(schema)?; - let mut steps = Vec::with_capacity(paths.len()); - for path in paths { - let name = path - .downcast_ref::() - .and_then(|literal| literal.value().try_as_str().flatten()) - .ok_or_else(|| { - exec_datafusion_err!("get_field path must be a non-null string literal") - })?; - let DataType::Struct(fields) = field.data_type() else { - return Err(Unconverted::Unsupported); - }; - let (_, child_field) = fields - .find(name) - .ok_or_else(|| exec_datafusion_err!("get_field references missing field {name}"))?; - let child_field = Arc::clone(child_field); - steps.push((field, name)); - field = child_field; - } - - Ok(NodeConversion::fixed([source], self, move |converter, [mut read]| { - let mut reads_extension_storage = false; - for (parent_field, name) in steps { - // Check the Vortex dtype instead of the Arrow extension name, because the session - // imports an unknown extension name as a plain struct that `get_item` reads directly. - if let DType::Extension(ext_dtype) = converter.node_dtype(&read, schema)? { - if !converter - .session - .arrow() - .exports_extension_storage(&ext_dtype, &parent_field) - { - return Err(Unconverted::Unsupported); - } - - read = ext_storage(read); - reads_extension_storage = true; - } - read = get_item(name, read); - } - - // A plugin exporter decides which Arrow data DataFusion sees for the selected field, so - // Vortex and DataFusion agree on that field only if the export keeps values. Columns and - // plain struct fields already assume this, and the check skips them so that their pushdown - // stays the same. - // TODO(connor): Drop this check once the Arrow plugin contract requires exports to keep - // values. - if reads_extension_storage && !converter.session.arrow().exports_without_plugins(&field) { - return Err(Unconverted::Unsupported); - } - - Ok(read) - })) - } - - /// Converts `array_sum` to `list_sum`. - /// - /// DataFusion casts the list to `List`, then adds each list's valid elements in - /// order: an empty or all-null list sums to null and a NaN poisons the sum. `list_sum` with - /// `include_nans` adds the cast elements the same way. - fn convert_array_sum<'a>( - &self, - scalar_fn: &'a ScalarFunctionExpr, - ) -> Conversion> { - let [input] = scalar_fn.args() else { - return Err(exec_datafusion_err!("array_sum requires exactly one argument").into()); - }; - Ok(NodeConversion::fixed([input], self, |_, [list]| { - Ok(list_sum_opts(list, NumericalAggregateOpts::include_nans())) - })) - } - - /// Converts `array_transform` to `list_transform`. - /// - /// The body is converted in the lambda's scope, where it may read only its one parameter, the - /// element. - fn convert_array_transform( - &self, - function: &HigherOrderFunctionExpr, - schema: &Schema, - input_dtype: &DType, - ) -> Conversion { - let [list, lambda] = function.args() else { - return Err( - exec_datafusion_err!("array_transform requires a list and a lambda").into(), - ); - }; - let Some(lambda) = lambda.downcast_ref::() else { - return Err(Unconverted::Unsupported); - }; - let [param] = lambda.params() else { - return Err(Unconverted::Unsupported); - }; - let list = self.convert_tree(list, schema, input_dtype)?; - let DType::List(element, _) = converted_dtype(&list, input_dtype)? else { - return Err(Unconverted::Unsupported); - }; - let params = StructFields::from_iter([(param.as_str(), element.as_ref().clone())]); - let inputs = DType::Struct(params.clone(), Nullability::NonNullable); - let body_converter = Self { - session: self.session.clone(), - scope: Scope::Lambda(params), - }; - // DataFusion also types the body against the outer schema: a lambda variable carries its - // own field. - let body = body_converter.convert_tree(lambda.body(), schema, &inputs)?; - let lambda = Lambda::new([param.as_str()], read_params(body)?) - .map_err(|_| Unconverted::Unsupported)?; - Ok(list_transform(list, lambda)) - } - - fn convert_case_expr<'a>( - &self, - case_expr: &'a df_expr::CaseExpr, - schema: &'a Schema, - ) -> Conversion> { - // Only the searched form (CASE WHEN cond THEN value ...) is supported. - if case_expr.expr().is_some() { - return Err(Unconverted::Unsupported); - } - let num_pairs = case_expr.when_then_expr().len(); - let mut children = Vec::with_capacity(num_pairs * 2 + 1); - for (when_expr, then_expr) in case_expr.when_then_expr() { - if when_expr.data_type(schema)? != DataType::Boolean { - return Err(exec_datafusion_err!("CASE WHEN must be Boolean").into()); - } - children.extend([when_expr, then_expr]); - } - children.extend(case_expr.else_expr()); - // CASE evaluates conditions on remaining rows and values only on selected rows, - // so fallible children retain DataFusion's short-circuit behavior. - Ok(NodeConversion::new(children, self, move |_, children| { - let mut children = children.into_iter(); - let pairs = children.by_ref().take(num_pairs * 2).tuples().collect_vec(); - let else_value = children.next(); - Ok(nested_case_when(pairs, else_value)) - })) - } } impl ExpressionConverter for DefaultExpressionConverter { @@ -1149,8 +314,8 @@ impl ExpressionConverter for DefaultExpressionConverter { } match self.convert_checked(expr, schema) { Ok(converted) => Ok(Some(converted)), - Err(Unconverted::Unsupported) => Ok(None), - Err(Unconverted::Failed(error)) => Err(error), + Err(Ok(Unsupported)) => Ok(None), + Err(Err(error)) => Err(error), } } } @@ -1162,245 +327,17 @@ pub(crate) fn is_infallible(expr: &Expression) -> bool { && expr.children().iter().all(is_infallible) } -/// Escapes the LIKE wildcards and escape character in `literal`. -fn escape_like(literal: &str) -> String { - let mut escaped = String::with_capacity(literal.len()); - for c in literal.chars() { - if matches!(c, '%' | '_' | '\\') { - escaped.push('\\'); - } - escaped.push(c); - } - escaped -} - -/// The Vortex return dtype of a converted expression; unresolvable dtypes are unsupported. -fn converted_dtype(expr: &Expression, input_dtype: &DType) -> Conversion { - expr.return_dtype(input_dtype) - .map_err(|_| Unconverted::Unsupported) -} - -/// Resolve only the input fields read by the converted expression. Resolving a whole Arrow -/// schema here would reject otherwise supported expressions because of unrelated fields. -fn node_dtype( - expr: &Expression, - schema: &Schema, - session: &VortexSession, - scope: Option<&StructFields>, -) -> Conversion { - if let Some(name) = expr.as_opt::() - && expr.child(0).is_root() - { - if let Some(params) = scope { - return params.field(name).ok_or(Unconverted::Unsupported); - } - let field = schema - .field_with_name(name.as_ref()) - .map_err(|_| Unconverted::Unsupported)?; - return DefaultExpressionConverter::new(session.clone()).arrow_dtype(field); - } - match expr { - Expression::Root => match scope { - Some(params) => Ok(DType::Struct(params.clone(), Nullability::NonNullable)), - None => session - .arrow() - .from_arrow_schema(schema) - .map_err(|_| Unconverted::Unsupported), - }, - Expression::Variable(_) => Err(Unconverted::Unsupported), - Expression::Scalar { - scalar_fn, - children, - } => { - let dtypes = children - .iter() - .map(|child| node_dtype(child, schema, session, scope)) - .collect::>>()?; - scalar_fn - .return_dtype(&dtypes) - .map_err(|_| Unconverted::Unsupported) - } - } -} - -/// Turns a body converted in a lambda's scope, where `$.x` is the parameter `x`, into a lambda's -/// body, which reads it as `@x`. -fn read_params(body: Expression) -> Conversion { - body.transform_down(|node| { - if let Some(name) = node.as_opt::() - && node.child(0).is_root() - { - return Ok(Transformed::yes(var(name.clone()))); - } - Ok(Transformed::no(node)) - }) - .map(Transformed::into_inner) - .map_err(|_| Unconverted::Unsupported) -} - -/// How a supported DataFusion cast is converted. -enum CastPushdown { - /// The Arrow cast cannot fail and keeps the Vortex dtype, so the converter omits it. - Drop, - /// The cast becomes a Vortex `cast`. - Keep, -} - -/// Classifies a cast for pushdown; unsupported casts stay in DataFusion. -fn classify_cast(cast: &df_expr::CastExpr, schema: &Schema) -> Conversion { - let options = cast.cast_options(); - if options.safe || options.format_options != DEFAULT_FORMAT_OPTIONS { - return Err(Unconverted::Unsupported); - } - let source = cast.expr().data_type(schema)?; - classify_cast_types(&source, cast.cast_type()) -} - -fn classify_cast_types(source: &DataType, target: &DataType) -> Conversion { - use DataType::*; - Ok(match (source, target) { - _ if source == target => CastPushdown::Drop, - // Views preserve narrow-offset strings without concatenating their values. - (Utf8, Utf8View) => CastPushdown::Drop, - // Decoding to views does not concatenate dictionary values into a narrow offset buffer. - (Dictionary(_, values), Utf8View) if matches!(values.as_ref(), Utf8 | Utf8View) => { - CastPushdown::Drop - } - // Run expansion gathers dictionary keys, then decodes them directly to views. - (RunEndEncoded(run_ends, values), Utf8View) - if matches!(run_ends.data_type(), Int16 | Int32) - && matches!(values.data_type(), Dictionary(_, strings) if matches!(strings.as_ref(), Utf8 | Utf8View)) => - { - CastPushdown::Drop - } - // Arrow expands runs by gathering with `Int32` indices, which fit Int16/Int32 run ends. - // Gathering a dictionary only moves keys and reuses the values, so nothing can overflow. - (RunEndEncoded(run_ends, values), Dictionary(..)) - if matches!(run_ends.data_type(), Int16 | Int32) && values.data_type() == target => - { - CastPushdown::Drop - } - (Int8, Int16 | Int32 | Int64) - | (Int16, Int32 | Int64) - | (Int32, Int64) - | (UInt8, UInt16 | UInt32 | UInt64 | Int16 | Int32 | Int64) - | (UInt16, UInt32 | UInt64 | Int32 | Int64) - | (UInt32, UInt64 | Int64) - | (Float32, Float64) => CastPushdown::Keep, - // Arrow and Vortex both convert with `as f64`: integers round to nearest and never fail, - // booleans become 1.0 or 0.0. - (Boolean | Int8 | Int16 | Int32 | Int64 | UInt8 | UInt16 | UInt32 | UInt64, Float64) => { - CastPushdown::Keep - } - // A list cast casts each element. Vortex has no `FixedSizeList` to `List` cast. - (List(from) | LargeList(from), List(to) | LargeList(to)) - if to.is_nullable() || !from.is_nullable() => - { - classify_cast_types(from.data_type(), to.data_type())? - } - _ => return Err(Unconverted::Unsupported), - }) -} - -fn try_operator_from_df(value: &DFOperator) -> Option { - match value { - DFOperator::Eq => Some(Operator::Eq), - DFOperator::NotEq => Some(Operator::NotEq), - DFOperator::Lt => Some(Operator::Lt), - DFOperator::LtEq => Some(Operator::Lte), - DFOperator::Gt => Some(Operator::Gt), - DFOperator::GtEq => Some(Operator::Gte), - DFOperator::And => Some(Operator::And), - DFOperator::Or => Some(Operator::Or), - DFOperator::Plus => Some(Operator::Add), - DFOperator::Minus => Some(Operator::Sub), - DFOperator::Multiply => Some(Operator::Mul), - DFOperator::Divide => Some(Operator::Div), - DFOperator::IsDistinctFrom - | DFOperator::IsNotDistinctFrom - | DFOperator::RegexMatch - | DFOperator::RegexIMatch - | DFOperator::RegexNotMatch - | DFOperator::RegexNotIMatch - | DFOperator::LikeMatch - | DFOperator::ILikeMatch - | DFOperator::NotLikeMatch - | DFOperator::NotILikeMatch - | DFOperator::BitwiseAnd - | DFOperator::BitwiseOr - | DFOperator::BitwiseXor - | DFOperator::BitwiseShiftRight - | DFOperator::BitwiseShiftLeft - | DFOperator::StringConcat - | DFOperator::AtArrow - | DFOperator::ArrowAt - | DFOperator::Modulo - | DFOperator::Arrow - | DFOperator::LongArrow - | DFOperator::HashArrow - | DFOperator::HashLongArrow - | DFOperator::AtAt - | DFOperator::IntegerDivide - | DFOperator::HashMinus - | DFOperator::AtQuestion - | DFOperator::Question - | DFOperator::QuestionAnd - | DFOperator::QuestionPipe - | DFOperator::Colon => None, - } -} - -fn supported_data_types(dt: &DataType) -> bool { - use DataType::*; - - // For dictionary and run-end encoded types, check if the value type is supported. Arrow's - // comparison kernels only unwrap run-end encoding as the outermost layer. - match dt { - Dictionary(_, value_type) => { - return !matches!(value_type.as_ref(), RunEndEncoded(..)) - && supported_data_types(value_type.as_ref()); - } - RunEndEncoded(_, values) => { - return !matches!(values.data_type(), RunEndEncoded(..)) - && supported_data_types(values.data_type()); - } - _ => {} - } - - let is_supported = dt.is_null() - || dt.is_numeric() - || dt.is_binary() - || dt.is_string() - || matches!( - dt, - Boolean | Date32 | Date64 | Timestamp(_, _) | Time32(_) | Time64(_) - ); - - if !is_supported { - tracing::debug!("DataFusion data type {dt:?} is not supported"); - } - - is_supported -} - -/// Returns the list argument of an `array_length` call that can be rewritten to `list_length`: -/// the single-argument form `array_length(arr)` or the equivalent explicit first dimension -/// `array_length(arr, 1)`. Other dimensions are unsupported (`None`); other arities are errors. -fn array_length_input(scalar_fn: &ScalarFunctionExpr) -> DFResult>> { - match scalar_fn.args() { - [input] => Ok(Some(input)), - [input, dimension] - if dimension - .downcast_ref::() - .is_some_and(|literal| matches!(literal.value(), ScalarValue::Int64(Some(1)))) => - { - Ok(Some(input)) - } - [_, _] => Ok(None), - _ => Err(exec_datafusion_err!( - "array_length requires one or two arguments" - )), - } +fn convert_tree(expr: &Arc, ctx: &ConvertibleCtx<'_>) -> MustConvert { + must(default_convert_recursive(expr, ctx, |child| match child { + Scoped::Same(expr) => convert_tree(expr, ctx), + Scoped::With(expr, scope) => convert_tree( + expr, + &ConvertibleCtx { + scope: Some(&scope), + ..*ctx + }, + ), + })) } #[cfg(test)] diff --git a/vortex-datafusion/src/convert/exprs/tests.rs b/vortex-datafusion/src/convert/exprs/tests.rs index 20acf7f855c..97b23481349 100644 --- a/vortex-datafusion/src/convert/exprs/tests.rs +++ b/vortex-datafusion/src/convert/exprs/tests.rs @@ -43,12 +43,25 @@ use datafusion_common::arrow::buffer::OffsetBuffer; use datafusion_common::arrow::compute::cast; use datafusion_common::arrow::datatypes::i256 as arrow_i256; use datafusion_common::config::ConfigOptions; +use datafusion_common::format::DEFAULT_FORMAT_OPTIONS; use datafusion_common::metadata::FieldMetadata; use datafusion_expr::HigherOrderUDF; use datafusion_expr::Operator as DFOperator; use datafusion_expr::ScalarUDF; use datafusion_functions::core::coalesce::CoalesceFunc; +use datafusion_functions::core::getfield::GetFieldFunc; +use datafusion_functions::string::contains::ContainsFunc; +use datafusion_functions::string::ends_with::EndsWithFunc; +use datafusion_functions::string::lower::LowerFunc; +use datafusion_functions::string::octet_length::OctetLengthFunc; +use datafusion_functions::string::starts_with::StartsWithFunc; +use datafusion_functions::unicode::strpos::StrposFunc; +use datafusion_functions_nested::array_sum::ArraySum; +use datafusion_functions_nested::array_transform::ArrayTransform; +use datafusion_functions_nested::length::ArrayLength; +use datafusion_physical_expr::HigherOrderFunctionExpr; use datafusion_physical_expr::PhysicalExpr; +use datafusion_physical_expr::ScalarFunctionExpr; use datafusion_physical_expr::expressions::DynamicFilterPhysicalExpr; use datafusion_physical_expr::projection::ProjectionExpr; use datafusion_physical_plan::expressions as df_expr; @@ -58,6 +71,7 @@ use vortex::array::ArrayRef; use vortex::array::Canonical; use vortex::array::ExecutionCtx; use vortex::array::IntoArray; +use vortex::array::VortexSessionExecute; use vortex::array::arrays::BoolArray; use vortex::array::arrays::ConstantArray; use vortex::array::arrays::PrimitiveArray; @@ -69,13 +83,22 @@ use vortex::encodings::uuid::Uuid; use vortex::error::VortexResult; use vortex::error::vortex_bail; use vortex::expr::between; +use vortex::expr::is_null; +use vortex::expr::lit; +use vortex::expr::nested_case_when; +use vortex::expr::not; use vortex::expr::proto::ExprSerializeProtoExt; use vortex::functions::between::BetweenOptions; use vortex::functions::between::StrictComparison; +use vortex::functions::like::Like; +use vortex::functions::like::LikeOptions; use vortex::functions::list_contains::ListContains; use vortex::scalar::Scalar; +use vortex::scalar_fn::ScalarFnVTableExt; +use vortex::scalar_fn::builtin::binary::Binary; use vortex::scalar_fn::builtin::cast::Cast; use vortex::scalar_fn::builtin::literal::Literal; +use vortex::scalar_fn::builtin::operators::Operator; use vortex::session::registry::CachedId; use vortex::session::registry::Id; use vortex_array::assert_arrays_eq; @@ -86,11 +109,22 @@ use vortex_arrow::ArrowImport; use vortex_arrow::ArrowImportVTable; use vortex_arrow::ArrowSession; +use super::convertible::supported_data_types; +use super::convertible::try_operator_from_df; use super::*; use crate::common_tests::ANY_STORAGE_ID; use crate::common_tests::AnyStorage; use crate::common_tests::TestSessionContext; +use crate::convert::ConvertArrayTransform; +use crate::convert::ConvertCase; +use crate::convert::ConvertColumn; +use crate::convert::ConvertIsNull; +use crate::convert::ConvertNot; +use crate::convert::Convertible; +use crate::convert::ConvertibleCtx as Ctx; +use crate::convert::Scoped; use crate::convert::TryToDataFusion; +use crate::convert::default_convert; #[test] fn test_row_index_conversion_and_raw_projection() -> DFResult<()> { @@ -690,7 +724,7 @@ fn test_operator_conversion_supported( #[case] df_op: DFOperator, #[case] expected_vortex_op: Operator, ) { - assert_eq!(try_operator_from_df(&df_op), Some(expected_vortex_op)); + assert_eq!(try_operator_from_df(&df_op).unwrap(), expected_vortex_op); } #[rstest] @@ -699,7 +733,7 @@ fn test_operator_conversion_supported( #[case::regex_match(DFOperator::RegexMatch)] #[case::like_match(DFOperator::LikeMatch)] fn test_operator_conversion_unsupported(#[case] df_op: DFOperator) { - assert_eq!(try_operator_from_df(&df_op), None); + assert!(matches!(try_operator_from_df(&df_op), Err(Ok(Unsupported)))); } #[test] @@ -974,8 +1008,10 @@ fn test_comparison_literal_metadata_is_not_replaced( Ok(()) } -#[test] -fn test_comparison_inherits_complete_extension_metadata() -> anyhow::Result<()> { +#[rstest] +fn test_comparison_inherits_complete_extension_metadata( + #[values(false, true)] membership: bool, +) -> anyhow::Result<()> { let mut field = Field::new("id", DataType::FixedSizeBinary(16), false); field.try_with_extension_type(ArrowUuid)?; let bytes = *b"0123456789abcdef"; @@ -995,11 +1031,18 @@ fn test_comparison_inherits_complete_extension_metadata() -> anyhow::Result<()> ScalarValue::FixedSizeBinary(16, Some(bytes.to_vec())), Some(FieldMetadata::new_from_field(&literal_field)), ); - let predicate = Arc::new(df_expr::BinaryExpr::new( - Arc::new(df_expr::Column::new("id", 0)), - DFOperator::Eq, - Arc::new(literal), - )); + let column: Arc = Arc::new(df_expr::Column::new("id", 0)); + let literal: Arc = Arc::new(literal); + let predicate: Arc = if membership { + Arc::new(df_expr::InListExpr::try_new( + column, + vec![literal], + false, + &batch.schema(), + )?) + } else { + Arc::new(df_expr::BinaryExpr::new(column, DFOperator::Eq, literal)) + }; assert_native_matches(predicate, batch) } @@ -3259,29 +3302,49 @@ fn test_fallible_boolean_rhs_is_residual( Ok(()) } +fn conversion_result(result: MustConvert) -> DFResult> { + match result { + Ok(value) => Ok(Some(value)), + Err(Ok(Unsupported)) => Ok(None), + Err(Err(error)) => Err(error), + } +} + +fn try_convert_with<'a>( + expr: &'a Arc, + ctx: &Ctx<'_>, + mut recur: impl FnMut(Scoped<'a>) -> DFResult>, +) -> DFResult> { + conversion_result(must(default_convert_recursive(expr, ctx, |child| { + recur(child).map_err(Err)?.ok_or(Ok(Unsupported)) + }))) +} + fn convert_with_custom_coalesce( expr: &Arc, - schema: &Schema, - session: &VortexSession, + ctx: &Ctx<'_>, visited: &mut Vec, ) -> DFResult> { visited.push(expr.to_string()); - if let Some(node) = try_convert_node(expr, schema, session)? { - let mut children = Vec::with_capacity(node.children.len()); - for child in &node.children { - let Some(child) = convert_with_custom_coalesce(child, schema, session, visited)? else { - return Ok(None); - }; - children.push(child); - } - return (node.construct)(children); + if let Some(converted) = try_convert_with(expr, ctx, |child| match child { + Scoped::Same(expr) => convert_with_custom_coalesce(expr, ctx, visited), + Scoped::With(expr, scope) => convert_with_custom_coalesce( + expr, + &Ctx { + scope: Some(&scope), + ..*ctx + }, + visited, + ), + })? { + return Ok(Some(converted)); } if let Some(scalar_fn) = expr.downcast_ref::() && ScalarFunctionExpr::try_downcast_func::(scalar_fn).is_some() && let [input] = scalar_fn.args() { // A one-argument coalesce is the identity, including for null inputs. - return convert_with_custom_coalesce(input, schema, session, visited); + return convert_with_custom_coalesce(input, ctx, visited); } Ok(None) } @@ -3307,10 +3370,16 @@ fn test_one_step_custom_child_under_native_parents() -> anyhow::Result<()> { let session = VortexSession::default(); let converter = DefaultExpressionConverter::new(session.clone()); assert!(converter.try_convert(&expr, &schema)?.is_none()); - assert!(try_convert_node(&custom, &schema, &session)?.is_none()); + assert!( + try_convert_with(&custom, &Ctx::new(&schema, &session), |_| { + Err(exec_datafusion_err!("Unsupported nodes must not recurse")) + })? + .is_none() + ); let mut visited = Vec::new(); - let converted = convert_with_custom_coalesce(&expr, &schema, &session, &mut visited)? - .ok_or_else(|| exec_datafusion_err!("Expected custom conversion"))?; + let converted = + convert_with_custom_coalesce(&expr, &Ctx::new(&schema, &session), &mut visited)? + .ok_or_else(|| exec_datafusion_err!("Expected custom conversion"))?; assert_eq!( visited, vec![ @@ -3335,7 +3404,9 @@ fn test_one_step_custom_child_under_native_parents() -> anyhow::Result<()> { } #[rstest] -fn test_one_step_selects_function_inputs(#[values(false, true)] length: bool) -> anyhow::Result<()> { +fn test_one_step_selects_function_inputs( + #[values(false, true)] length: bool, +) -> anyhow::Result<()> { let schema = Schema::new(vec![Field::new( "a", if length { @@ -3359,19 +3430,22 @@ fn test_one_step_selects_function_inputs(#[values(false, true)] length: bool) -> }; let session = VortexSession::default(); let converter = DefaultExpressionConverter::new(session.clone()); - let node = try_convert_node(&expr, &schema, &session)? - .ok_or_else(|| exec_datafusion_err!("Expected function conversion"))?; - assert_eq!(node.children.len(), 1); - assert!(Arc::ptr_eq(node.children[0], &source)); - assert_eq!( - (node.construct)(vec![get_item("a", root())])?, - converter.try_convert(&expr, &schema)? - ); + let mut selected = Vec::new(); + let converted = try_convert_with(&expr, &Ctx::new(&schema, &session), |child| { + let Scoped::Same(child) = child else { + panic!("Expected an input in the current scope"); + }; + selected.push(child); + Ok(Some(get_item("a", root()))) + })?; + assert_eq!(selected.len(), 1); + assert!(Arc::ptr_eq(selected[0], &source)); + assert_eq!(converted, converter.try_convert(&expr, &schema)?); Ok(()) } #[test] -fn test_one_step_deduplicates_in_list_before_traversal() -> anyhow::Result<()> { +fn test_one_step_imports_in_list_literals_before_traversal() -> anyhow::Result<()> { let schema = Schema::new(vec![Field::new("a", DataType::Int32, true)]); let expr: Arc = Arc::new(df_expr::InListExpr::try_new( Arc::new(df_expr::Column::new("a", 0)), @@ -3381,23 +3455,20 @@ fn test_one_step_deduplicates_in_list_before_traversal() -> anyhow::Result<()> { )?); let session = VortexSession::default(); let converter = DefaultExpressionConverter::new(session.clone()); - let node = try_convert_node(&expr, &schema, &session)? - .ok_or_else(|| exec_datafusion_err!("Expected IN conversion"))?; - assert_eq!(node.children.len(), 4); + let mut selected = Vec::new(); + let converted = try_convert_with(&expr, &Ctx::new(&schema, &session), |child| { + let Scoped::Same(child) = child else { + panic!("Expected an input in the current scope"); + }; + selected.push(child); + Ok(Some(convert(Arc::clone(child), &schema)?)) + })?; + assert_eq!(selected.len(), 1); let original_children = expr.children(); - for (selected, original) in node.children.iter().zip(original_children) { + for (selected, original) in selected.iter().zip(original_children) { assert!(Arc::ptr_eq(selected, original)); } - let converted = node - .children - .iter() - .copied() - .map(|child| convert(Arc::clone(child), &schema)) - .collect::>>()?; - assert_eq!( - (node.construct)(converted)?, - converter.try_convert(&expr, &schema)? - ); + assert_eq!(converted, converter.try_convert(&expr, &schema)?); Ok(()) } @@ -3415,24 +3486,29 @@ fn test_one_step_constructor_declines_fallible_children( column, )); let session = VortexSession::default(); - let node = try_convert_node(&expr, &schema, &session)? - .ok_or_else(|| exec_datafusion_err!("Expected boolean conversion"))?; let fallible = is_null(Binary.new_expr(Operator::Div, [lit(1i32), lit(0i32)])); - assert!((node.construct)(vec![get_item("a", root()), fallible])?.is_none()); + let mut children = [get_item("a", root()), fallible].into_iter(); + assert!( + try_convert_with(&expr, &Ctx::new(&schema, &session), |_| Ok(children.next()))?.is_none() + ); Ok(()) } #[rstest] -fn test_one_step_constructor_rejects_wrong_arity(#[values(0, 2)] arity: usize) -> anyhow::Result<()> { +fn test_fixed_arity_converter_rejects_wrong_arity( + #[values(0, 2)] arity: usize, +) -> anyhow::Result<()> { let expr: Arc = Arc::new(df_expr::NotExpr::new(Arc::new( df_expr::Literal::new(ScalarValue::Boolean(Some(true))), ))); let session = VortexSession::default(); let schema = Schema::empty(); - let node = try_convert_node(&expr, &schema, &session)? - .ok_or_else(|| exec_datafusion_err!("Expected NOT conversion"))?; - let error = (node.construct)(vec![lit(true); arity]).unwrap_err(); - assert!(error.to_string().contains("Expected 1 converted children")); + let (_, convertible) = ConvertNot::recognize(&expr, &Ctx::new(&schema, &session)) + .expect_err("Expected NOT converter")?; + let error = convertible + .construct(vec![lit(true); arity], &Ctx::new(&schema, &session)) + .unwrap_err(); + assert!(error.is_err()); Ok(()) } @@ -3441,7 +3517,8 @@ fn test_one_step_case_child_order(#[values(false, true)] with_else: bool) -> any let condition: Arc = Arc::new(df_expr::Literal::new(ScalarValue::Boolean(Some(false)))); let value: Arc = Arc::new(df_expr::Literal::new(ScalarValue::Int32(Some(1)))); - let otherwise: Arc = Arc::new(df_expr::Literal::new(ScalarValue::Int32(Some(2)))); + let otherwise: Arc = + Arc::new(df_expr::Literal::new(ScalarValue::Int32(Some(2)))); let expr: Arc = Arc::new(df_expr::CaseExpr::try_new( None, vec![(Arc::clone(&condition), Arc::clone(&value))], @@ -3449,24 +3526,31 @@ fn test_one_step_case_child_order(#[values(false, true)] with_else: bool) -> any )?); let schema = Schema::empty(); let session = VortexSession::default(); - let node = try_convert_node(&expr, &schema, &session)? - .ok_or_else(|| exec_datafusion_err!("Expected CASE conversion"))?; - assert_eq!(node.children.len(), if with_else { 3 } else { 2 }); - assert!(Arc::ptr_eq(node.children[0], &condition)); - assert!(Arc::ptr_eq(node.children[1], &value)); + let mut children = vec![lit(false), lit(1i32)]; if with_else { - assert!(Arc::ptr_eq(node.children[2], &otherwise)); + children.push(lit(2i32)); } - let mut converted = vec![lit(false), lit(1i32)]; + let mut children = children.into_iter(); + let mut selected = Vec::new(); + let converted = try_convert_with(&expr, &Ctx::new(&schema, &session), |child| { + let Scoped::Same(child) = child else { + panic!("Expected an input in the current scope"); + }; + selected.push(child); + Ok(children.next()) + })?; + assert_eq!(selected.len(), if with_else { 3 } else { 2 }); + assert!(Arc::ptr_eq(selected[0], &condition)); + assert!(Arc::ptr_eq(selected[1], &value)); if with_else { - converted.push(lit(2i32)); + assert!(Arc::ptr_eq(selected[2], &otherwise)); } assert_eq!( - (node.construct)(converted)?, + converted, Some(nested_case_when( vec![(lit(false), lit(1i32))], with_else.then(|| lit(2i32)), - )) + )), ); Ok(()) } @@ -3483,10 +3567,240 @@ fn test_one_step_ignores_unreferenced_unsupported_field() -> anyhow::Result<()> Arc::new(df_expr::Literal::new(ScalarValue::Int32(Some(1)))), )); let session = VortexSession::default(); - let converted = convert_with_custom_coalesce(&expr, &schema, &session, &mut Vec::new())?; + let converted = + convert_with_custom_coalesce(&expr, &Ctx::new(&schema, &session), &mut Vec::new())?; assert_eq!( converted, Some(Binary.new_expr(Operator::Eq, [get_item("a", root()), lit(1i32)])) ); Ok(()) } + +#[rstest] +fn test_variable_arity_converter_rejects_wrong_arity( + #[values(1, 3)] arity: usize, +) -> anyhow::Result<()> { + let expr: Arc = Arc::new(df_expr::CaseExpr::try_new( + None, + vec![( + Arc::new(df_expr::Literal::new(ScalarValue::Boolean(Some(true)))), + Arc::new(df_expr::Literal::new(ScalarValue::Int32(Some(1)))) as Arc, + )], + None, + )?); + let session = VortexSession::default(); + let schema = Schema::empty(); + let (_, convertible) = ConvertCase::recognize(&expr, &Ctx::new(&schema, &session)) + .expect_err("Expected CASE converter")?; + let error = convertible + .construct(vec![lit(true); arity], &Ctx::new(&schema, &session)) + .unwrap_err(); + let error = error.expect_err("Wrong arity must be a conversion error"); + assert!(error.to_string().contains("Expected 2 converted children")); + Ok(()) +} + +fn convert_with_subset( + expr: &Arc, + ctx: &Ctx<'_>, +) -> DFResult> { + let mut recur = |child| { + let Scoped::Same(expr) = child else { + return Err(Ok(Unsupported)); + }; + convert_with_subset(expr, ctx) + .map_err(Err)? + .ok_or(Ok(Unsupported)) + }; + if let Some(converted) = + conversion_result(ConvertNot::convert_recursive(expr, ctx, &mut recur))? + { + return Ok(Some(converted)); + } + if let Some(converted) = + conversion_result(ConvertIsNull::convert_recursive(expr, ctx, &mut recur))? + { + return Ok(Some(converted)); + } + conversion_result(ConvertColumn::convert_recursive(expr, ctx, recur)) +} + +#[test] +fn test_compose_public_converters_with_borrowed_inputs() -> anyhow::Result<()> { + let batch = arrow_array::record_batch!(("a", Int32, vec![Some(1), None, Some(3)]))?; + let schema = batch.schema(); + let expr: Arc = Arc::new(df_expr::NotExpr::new(Arc::new( + df_expr::IsNullExpr::new(Arc::new(df_expr::Column::new("a", 0))), + ))); + let session = VortexSession::default(); + let converted = convert_with_subset(&expr, &Ctx::new(&schema, &session))? + .ok_or_else(|| exec_datafusion_err!("Expected subset conversion"))?; + assert_eq!(converted, not(is_null(get_item("a", root())))); + let input = session.arrow().from_arrow_record_batch(batch, &schema)?; + assert_arrays_eq!( + input.apply(&converted)?, + BoolArray::from_iter([true, false, true]), + &mut session.create_execution_ctx() + ); + Ok(()) +} + +#[test] +fn test_boxed_converter_borrows_expression_not_context() -> anyhow::Result<()> { + let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]); + let session = VortexSession::default(); + let expr: Arc = Arc::new(df_expr::Column::new("a", 0)); + let (children, constructible) = default_convert(&expr, &Ctx::new(&schema, &session)) + .expect_err("Expected column converter")?; + assert!(children.is_empty()); + let converted = + conversion_result(constructible.construct(Vec::new(), &Ctx::new(&schema, &session)))?; + assert_eq!(converted, Some(get_item("a", root()))); + Ok(()) +} + +#[test] +fn test_boxed_converter_preserves_conversion_errors() { + let schema = Schema::empty(); + let session = VortexSession::default(); + let expr: Arc = Arc::new(df_expr::Literal::new(ScalarValue::Decimal128( + Some(1), + 0, + 0, + ))); + assert!(matches!( + default_convert(&expr, &Ctx::new(&schema, &session)), + Err(Err(_)) + )); +} + +#[rstest] +fn test_array_transform_selects_child_scopes( + #[values(false, true)] boxed: bool, +) -> anyhow::Result<()> { + let batch = int_lists()?; + let schema = batch.schema(); + let session = VortexSession::default(); + let ctx = Ctx::new(&schema, &session); + let expr = array_transform_expr( + Arc::new(df_expr::Column::new("xs", 0)), + "x", + 1, + plus_one_body, + &schema, + )?; + let mut visited = Vec::new(); + let mut recur = |child| match child { + Scoped::Same(expr) => { + visited.push((expr, ctx.scope.cloned())); + convert_tree(expr, &ctx) + } + Scoped::With(expr, scope) => { + visited.push((expr, Some(scope.clone()))); + convert_tree( + expr, + &Ctx { + scope: Some(&scope), + ..ctx + }, + ) + } + }; + let result = if boxed { + let (children, constructible) = + default_convert(&expr, &ctx).expect_err("Expected array transform converter")?; + assert!(matches!( + children.as_slice(), + [Scoped::Same(_), Scoped::With(_, _)] + )); + let children = children + .into_iter() + .map(&mut recur) + .collect::>>(); + children.and_then(|children| constructible.construct(children, &ctx)) + } else { + ConvertArrayTransform::convert_recursive(&expr, &ctx, &mut recur) + }; + let converted = conversion_result(result)?; + assert_eq!( + converted, + DefaultExpressionConverter::default().try_convert(&expr, &schema)? + ); + assert_eq!(visited.len(), 2); + let function = expr.downcast_ref::().unwrap(); + assert!(Arc::ptr_eq(visited[0].0, &function.args()[0])); + assert!(visited[0].1.is_none()); + let lambda = function.args()[1] + .downcast_ref::() + .unwrap(); + assert!(Arc::ptr_eq(visited[1].0, lambda.body())); + assert_eq!( + visited[1].1.as_ref().unwrap().field("x"), + Some(DType::Primitive(PType::I64, Nullability::Nullable)), + ); + assert!(ctx.scope.is_none()); + Ok(()) +} + +#[test] +fn test_array_transform_custom_conversion_in_lambda_body() -> anyhow::Result<()> { + let batch = int_lists()?; + let schema = batch.schema(); + let session = VortexSession::default(); + let expr = array_transform_expr( + Arc::new(df_expr::Column::new("xs", 0)), + "x", + 1, + |x| { + Ok(Arc::new(ScalarFunctionExpr::try_new( + Arc::new(ScalarUDF::from(CoalesceFunc::new())), + vec![x], + &schema, + Arc::new(ConfigOptions::new()), + )?)) + }, + &schema, + )?; + assert!( + DefaultExpressionConverter::default() + .try_convert(&expr, &schema)? + .is_none() + ); + let converted = + convert_with_custom_coalesce(&expr, &Ctx::new(&schema, &session), &mut Vec::new())? + .ok_or_else(|| exec_datafusion_err!("Expected custom lambda conversion"))?; + let input = session.arrow().from_arrow_record_batch(batch, &schema)?; + assert_arrays_eq!( + input.clone().apply(&converted)?, + input.apply(&get_item("xs", root()))?, + &mut session.create_execution_ctx() + ); + Ok(()) +} + +#[test] +fn test_array_transform_rejects_changed_list_element_type() -> anyhow::Result<()> { + let batch = int_lists()?; + let schema = batch.schema(); + let session = VortexSession::default(); + let ctx = Ctx::new(&schema, &session); + let expr = array_transform_expr( + Arc::new(df_expr::Column::new("xs", 0)), + "x", + 1, + plus_one_body, + &schema, + )?; + let (_, convertible) = ConvertArrayTransform::recognize(&expr, &ctx) + .expect_err("Expected array transform converter")?; + let replacement = Scalar::list( + Arc::new(DType::Utf8(Nullability::NonNullable)), + vec![Scalar::from("changed")], + Nullability::NonNullable, + ); + assert!(matches!( + convertible.construct(vec![lit(replacement), get_item("x", root())], &ctx), + Err(Ok(Unsupported)), + )); + Ok(()) +} diff --git a/vortex-datafusion/src/convert/mod.rs b/vortex-datafusion/src/convert/mod.rs index fe386bb5758..7b10cbc5168 100644 --- a/vortex-datafusion/src/convert/mod.rs +++ b/vortex-datafusion/src/convert/mod.rs @@ -24,11 +24,9 @@ pub(crate) mod schema; pub(crate) mod stats; pub use exprs::DefaultExpressionConverter; -pub use exprs::ExpressionConstructor; pub use exprs::ExpressionConverter; -pub use exprs::NodeConversion; pub use exprs::ProcessedProjection; -pub use exprs::try_convert_node; +pub use exprs::convertible::*; pub use scalars::scalar_from_df; /// Convert a scan chunk using the non-nullable struct field for its projected Arrow columns.