Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 65 additions & 0 deletions vortex-datafusion/src/convert/exprs/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,11 @@ use vortex::expr::strpos;
use vortex::expr::traversal::NodeExt;
use vortex::expr::traversal::Transformed;
use vortex::expr::var;
use vortex::expr::variant_get;
use vortex::functions::like::Like;
use vortex::functions::like::LikeOptions;
use vortex::functions::variant_get::VariantPath;
use vortex::functions::variant_get::VariantPathElement;
use vortex::layout::layouts::row_idx;
use vortex::scalar::Scalar;
use vortex::scalar_fn::ScalarFnVTableExt;
Expand All @@ -81,6 +84,9 @@ use vortex_arrow::ArrowSessionExt;

use crate::row_index::RowIndex;

/// Name of the Variant extraction function of datafusion-variant.
const TRY_VARIANT_GET: &str = "try_variant_get";

/// Result of splitting a projection into Vortex expressions and leftover DataFusion projections.
pub struct ProcessedProjection {
/// Projection evaluated by the Vortex scan.
Expand Down Expand Up @@ -786,6 +792,10 @@ impl DefaultExpressionConverter {
return self.convert_array_sum(scalar_fn, schema, input_dtype);
}

if scalar_fn.name() == TRY_VARIANT_GET {
return self.convert_variant_get(scalar_fn, schema, input_dtype);
}

let (input, length): (_, fn(Expression) -> Expression) =
if ScalarFunctionExpr::try_downcast_func::<OctetLengthFunc>(scalar_fn).is_some() {
let [input] = scalar_fn.args() else {
Expand Down Expand Up @@ -823,6 +833,61 @@ impl DefaultExpressionConverter {
Ok(cast(length(input), return_dtype))
}

/// Converts `try_variant_get(variant, path, type)` to the Vortex `variant_get`, so that the
/// scan reads a shredded path from its typed column instead of materializing the whole Variant.
///
/// The function is matched by name, because it is not part of DataFusion: it has the contract
/// of [datafusion-variant], where `try_variant_get` returns null for a missing path or a value
/// that does not cast to the requested type (`CastOptions { safe: true }`), matching Vortex's
/// `variant_get` extraction. `variant_get` raises an error on failed casts (`safe: false`) and
/// is left in DataFusion.
///
/// Only the typed form over a `$`-rooted path of plain object fields (`$.field(.field)*`)
/// converts.
///
/// [datafusion-variant]: https://github.com/datafusion-contrib/datafusion-variant
fn convert_variant_get(
&self,
scalar_fn: &ScalarFunctionExpr,
schema: &Schema,
input_dtype: &DType,
) -> Conversion<Expression> {
let [input, path, _type] = scalar_fn.args() else {
return Err(Unconverted::Unsupported);
};
let Some(Some(path)) = path
.downcast_ref::<df_expr::Literal>()
.map(|literal| literal.value().try_as_str().flatten())
else {
return Err(Unconverted::Unsupported);
};
let Some(fields) = path.strip_prefix("$.") else {
return Err(Unconverted::Unsupported);
};
let is_field = |field: &str| {
!field.is_empty() && field.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
};
if !fields.split('.').all(is_field) {
return Err(Unconverted::Unsupported);
}
let path = fields
.split('.')
.map(VariantPathElement::field)
.collect::<VariantPath>();

let input = self.convert_expr(input, schema, input_dtype)?;
if !converted_dtype(&input, input_dtype)?.is_variant() {
return Err(Unconverted::Unsupported);
}
let return_dtype = self
.arrow_dtype(&Field::new("", scalar_fn.return_type().clone(), true))?
.as_nullable();
if return_dtype.is_variant() {
return Err(Unconverted::Unsupported);
}
Ok(variant_get(input, path, Some(return_dtype)))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The description says this is correct on its own, because try_variant_get and Vortex's variant_get both return null for a value that does not convert. But #11850 says that on develop, Vortex's variant_get does not yet convert as Arrow does. A typed value of another type than the requested one falls back to core storage, which does not hold it. datafusion-variant converts through Arrow, so before #11850 this pushdown can return null where try_variant_get returns a converted value: for example, a Variant integer requested as VARCHAR from a shredded column. If that is right, please stack this PR on #11850, or say in the description that the results match only once #11850 lands.

}

/// Converts `array_sum` to `list_sum`.
///
/// DataFusion casts the list to `List<Float64>`, then adds each list's valid elements in
Expand Down
118 changes: 118 additions & 0 deletions vortex-datafusion/src/convert/exprs/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3088,3 +3088,121 @@ fn test_fallible_boolean_rhs_is_residual(
assert!(!converts(&expr, &batch.schema())?);
Ok(())
}

/// A stand-in for `try_variant_get` / `variant_get` of datafusion-variant, which returns the
/// type its third argument names. Only its name and return type matter to the conversion.
#[derive(Debug, PartialEq, Eq, Hash)]
struct TestVariantGet {
name: &'static str,
signature: datafusion_expr::Signature,
}

impl datafusion_expr::ScalarUDFImpl for TestVariantGet {
fn name(&self) -> &str {
self.name
}

fn signature(&self) -> &datafusion_expr::Signature {
&self.signature
}

fn return_type(&self, _arg_types: &[DataType]) -> DFResult<DataType> {
Ok(DataType::Utf8View)
}

fn invoke_with_args(
&self,
_args: datafusion_expr::ScalarFunctionArgs,
) -> DFResult<datafusion_expr::ColumnarValue> {
Err(exec_datafusion_err!(
"the conversion never invokes {}",
self.name
))
}
}

/// A schema with one Variant column, `data`, and `fn_name(data, path, 'VARCHAR')` over it.
fn variant_get_expr_named(
fn_name: &'static str,
path: &str,
) -> anyhow::Result<(Schema, Arc<dyn PhysicalExpr>)> {
let session = VortexSession::default();
let schema =
Schema::new(vec![session.arrow().to_arrow_field(
"data",
&DType::Variant(Nullability::NonNullable),
)?]);
let function = TestVariantGet {
name: fn_name,
signature: datafusion_expr::Signature::any(3, datafusion_expr::Volatility::Immutable),
};
let literal = |value: &str| -> Arc<dyn PhysicalExpr> {
Arc::new(df_expr::Literal::new(ScalarValue::Utf8(Some(
value.to_string(),
))))
};
let expr = Arc::new(ScalarFunctionExpr::try_new(
Arc::new(ScalarUDF::from(function)),
vec![
Arc::new(df_expr::Column::new("data", 0)),
literal(path),
literal("VARCHAR"),
],
&schema,
Arc::new(ConfigOptions::new()),
)?);
Ok((schema, expr))
}

/// A schema with one Variant column, `data`, and `try_variant_get(data, path, 'VARCHAR')` over it.
fn variant_get_expr(path: &str) -> anyhow::Result<(Schema, Arc<dyn PhysicalExpr>)> {
variant_get_expr_named("try_variant_get", path)
}

#[test]
fn test_variant_get_converts_to_native_extraction() -> anyhow::Result<()> {
let (schema, expr) = variant_get_expr("$.commit.collection")?;

assert_eq!(
DefaultExpressionConverter::default().try_convert(&expr, &schema)?,
Some(variant_get(
get_item("data", root()),
VariantPath::new([
VariantPathElement::field("commit"),
VariantPathElement::field("collection"),
]),
Some(DType::Utf8(Nullability::Nullable)),
)),
);
Ok(())
}

#[rstest]
#[case::bare_path("commit.collection")]
#[case::list_index("$.posts[0]")]
#[case::quoted_field("$['a.b']")]
#[case::empty_field("$.commit..collection")]
#[case::root("$")]
#[case::root_dot("$.")]
#[case::empty("")]
fn test_variant_get_keeps_other_paths_in_datafusion(#[case] path: &str) -> anyhow::Result<()> {
let (schema, expr) = variant_get_expr(path)?;

assert_eq!(
DefaultExpressionConverter::default().try_convert(&expr, &schema)?,
None,
);
Ok(())
}

#[test]
fn test_strict_variant_get_stays_in_datafusion() -> anyhow::Result<()> {
let (schema, expr) = variant_get_expr_named("variant_get", "$.commit.collection")?;

assert_eq!(
DefaultExpressionConverter::default().try_convert(&expr, &schema)?,
None,
);
Ok(())
}

Loading