diff --git a/vortex-datafusion/src/convert/exprs/mod.rs b/vortex-datafusion/src/convert/exprs/mod.rs index 1165eb2f6e2..5d386a09d10 100644 --- a/vortex-datafusion/src/convert/exprs/mod.rs +++ b/vortex-datafusion/src/convert/exprs/mod.rs @@ -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; @@ -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. @@ -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::(scalar_fn).is_some() { let [input] = scalar_fn.args() else { @@ -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 { + let [input, path, _type] = scalar_fn.args() else { + return Err(Unconverted::Unsupported); + }; + let Some(Some(path)) = path + .downcast_ref::() + .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::(); + + 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))) + } + /// Converts `array_sum` to `list_sum`. /// /// DataFusion casts the list to `List`, then adds each list's valid elements in diff --git a/vortex-datafusion/src/convert/exprs/tests.rs b/vortex-datafusion/src/convert/exprs/tests.rs index 20b889bc750..90bda50fe25 100644 --- a/vortex-datafusion/src/convert/exprs/tests.rs +++ b/vortex-datafusion/src/convert/exprs/tests.rs @@ -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 { + Ok(DataType::Utf8View) + } + + fn invoke_with_args( + &self, + _args: datafusion_expr::ScalarFunctionArgs, + ) -> DFResult { + 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)> { + 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 { + 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)> { + 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(()) +} +