datafusion-optimizer 56.0.0

DataFusion Query Optimizer
Documentation
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements

use arrow::datatypes::DataType;
use datafusion_common::Result;
use datafusion_expr::function::AccumulatorArgs;
use datafusion_expr::{
    Accumulator, AggregateUDFImpl, ColumnarValue, DistinctHandling, Expr,
    ExpressionPlacement, ScalarFunctionArgs, ScalarUDF, ScalarUDFImpl, Signature,
    TypeSignature, Volatility, lit,
};
use std::hash::{Hash, Hasher};

/// A configurable test UDF for optimizer tests.
/// Defaults to `MoveTowardsLeafNodes` placement. Use `with_placement()` to override.
#[derive(Debug, PartialEq, Eq, Hash)]
pub struct PlacementTestUDF {
    signature: Signature,
    placement: ExpressionPlacement,
    id: usize,
}

impl Default for PlacementTestUDF {
    fn default() -> Self {
        Self::new()
    }
}

impl PlacementTestUDF {
    pub fn new() -> Self {
        Self {
            // Accept any one or two arguments and return UInt32 for testing purposes.
            // The actual types don't matter since this UDF is not intended for execution.
            signature: Signature::new(
                TypeSignature::OneOf(vec![TypeSignature::Any(1), TypeSignature::Any(2)]),
                Volatility::Immutable,
            ),
            placement: ExpressionPlacement::MoveTowardsLeafNodes,
            id: 0,
        }
    }

    /// Set the expression placement for this UDF, which is used by optimizer rules to determine where in the plan the expression should be placed.
    /// This also resets the name of the UDF to a default based on the placement.
    pub fn with_placement(mut self, placement: ExpressionPlacement) -> Self {
        self.placement = placement;
        self
    }

    /// Set the id of the UDF.
    /// This is an arbitrary made up field to allow creating multiple distinct UDFs with the same placement.
    pub fn with_id(mut self, id: usize) -> Self {
        self.id = id;
        self
    }

    /// Set the volatility of the UDF, so that rules which must not duplicate a
    /// volatile computation (e.g. `random()`) can be exercised.
    pub fn with_volatility(mut self, volatility: Volatility) -> Self {
        self.signature.volatility = volatility;
        self
    }
}

impl ScalarUDFImpl for PlacementTestUDF {
    fn name(&self) -> &str {
        match self.placement {
            ExpressionPlacement::MoveTowardsLeafNodes => "leaf_udf",
            ExpressionPlacement::KeepInPlace => "keep_in_place_udf",
            ExpressionPlacement::Column => "column_udf",
            ExpressionPlacement::Literal => "literal_udf",
        }
    }
    fn signature(&self) -> &Signature {
        &self.signature
    }
    fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
        Ok(DataType::UInt32)
    }
    fn invoke_with_args(&self, _args: ScalarFunctionArgs) -> Result<ColumnarValue> {
        panic!("PlacementTestUDF: not intended for execution")
    }
    fn placement(&self, _args: &[ExpressionPlacement]) -> ExpressionPlacement {
        self.placement
    }
}

/// Create a `leaf_udf(arg)` expression with `MoveTowardsLeafNodes` placement.
pub fn leaf_udf_expr(arg: Expr) -> Expr {
    let udf = ScalarUDF::new_from_impl(
        PlacementTestUDF::new().with_placement(ExpressionPlacement::MoveTowardsLeafNodes),
    );
    udf.call(vec![arg])
}

/// A `get_field`-like test UDF for modeling struct-field access (`f(c)['a']`),
/// so tests need not depend on `datafusion-functions` (which this crate avoids —
/// see its `Cargo.toml`).
///
/// Placement mirrors `GetFieldFunc`: `MoveTowardsLeafNodes` when the base is
/// pushable and the keys are literals, else `KeepInPlace`. That flip drives the
/// issue #23655 pushdown interaction: the access is `KeepInPlace` until
/// `CommonSubexprEliminate` hoists the UDF into a column, then becomes pushable.
#[derive(Debug, PartialEq, Eq, Hash)]
pub struct GetFieldLikeUDF {
    signature: Signature,
}

impl Default for GetFieldLikeUDF {
    fn default() -> Self {
        Self::new()
    }
}

impl GetFieldLikeUDF {
    pub fn new() -> Self {
        Self {
            signature: Signature::new(TypeSignature::Any(2), Volatility::Immutable),
        }
    }
}

impl ScalarUDFImpl for GetFieldLikeUDF {
    fn name(&self) -> &str {
        "get_field_like"
    }
    fn signature(&self) -> &Signature {
        &self.signature
    }
    fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
        Ok(DataType::UInt32)
    }
    fn invoke_with_args(&self, _args: ScalarFunctionArgs) -> Result<ColumnarValue> {
        panic!("GetFieldLikeUDF: not intended for execution")
    }
    fn placement(&self, args: &[ExpressionPlacement]) -> ExpressionPlacement {
        // Mirror `GetFieldFunc`: cheap to push down only when the base is a
        // column (or already pushable) and every field key is a literal.
        match args.first() {
            Some(
                ExpressionPlacement::Column | ExpressionPlacement::MoveTowardsLeafNodes,
            ) if args[1..]
                .iter()
                .all(|p| matches!(p, ExpressionPlacement::Literal)) =>
            {
                ExpressionPlacement::MoveTowardsLeafNodes
            }
            _ => ExpressionPlacement::KeepInPlace,
        }
    }
}

/// Create a `get_field_like(base, key)` expression that models `base[key]`.
pub fn get_field_like(base: Expr, key: &str) -> Expr {
    let udf = ScalarUDF::new_from_impl(GetFieldLikeUDF::new());
    udf.call(vec![base, lit(key)])
}

/// A test aggregate that reports the [`DistinctHandling`] it was built with.
///
/// Built-in functions only cover the variants they happen to carry. This one
/// exercises the public API a third-party function uses: an
/// [`AggregateUDFImpl::distinct_handling`] override.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DistinctHandlingTestUDAF {
    name: &'static str,
    handling: DistinctHandling,
    signature: Signature,
}

impl DistinctHandlingTestUDAF {
    pub fn new(name: &'static str, handling: DistinctHandling) -> Self {
        Self {
            name,
            handling,
            signature: Signature::any(1, Volatility::Immutable),
        }
    }

    /// Set the volatility of the aggregate function itself.
    pub fn with_volatility(mut self, volatility: Volatility) -> Self {
        self.signature.volatility = volatility;
        self
    }
}

/// Hashed by name and signature. `DistinctHandling` is not `Hash`, and
/// `AggregateUDFImpl` requires one through `DynHash`.
impl Hash for DistinctHandlingTestUDAF {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.name.hash(state);
        self.signature.hash(state);
    }
}

impl AggregateUDFImpl for DistinctHandlingTestUDAF {
    fn name(&self) -> &str {
        self.name
    }
    fn signature(&self) -> &Signature {
        &self.signature
    }
    fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
        Ok(DataType::UInt32)
    }
    fn accumulator(&self, _acc_args: AccumulatorArgs) -> Result<Box<dyn Accumulator>> {
        panic!("DistinctHandlingTestUDAF: not intended for execution")
    }
    fn distinct_handling(&self) -> DistinctHandling {
        self.handling
    }
}