datafusion-substrait 56.0.0

DataFusion Substrait Producer and Consumer
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 crate::logical_plan::consumer::{
    SubstraitConsumer, from_substrait_func_args, substrait_fun_name,
};
use datafusion::common::{
    DFSchema, ScalarValue, not_impl_datafusion_err, not_impl_err, plan_datafusion_err,
    plan_err,
};
use datafusion::execution::FunctionRegistry;
use datafusion::logical_expr::{Expr, SortExpr, expr};
use std::sync::Arc;
use substrait::proto::{AggregateFunction, AggregationPhase};

pub(super) fn validate_aggregation_phase(phase: i32) -> datafusion::common::Result<()> {
    match AggregationPhase::try_from(phase)
        .map_err(|e| plan_datafusion_err!("Invalid aggregation phase {phase}: {e}"))?
    {
        // Substrait defines UNSPECIFIED as INTERMEDIATE_TO_RESULT. Accept it as a
        // complete call only for compatibility with existing DataFusion-produced
        // aggregate and window plans. This exception also accepts unspecified
        // intermediate-state calls from other producers; their intent cannot be
        // distinguished here. Explicit intermediate phases remain unsupported.
        AggregationPhase::Unspecified | AggregationPhase::InitialToResult => Ok(()),
        phase => not_impl_err!("Unsupported aggregation phase: {}", phase.as_str_name()),
    }
}

/// Convert Substrait AggregateFunction to DataFusion Expr
pub async fn from_substrait_agg_func(
    consumer: &impl SubstraitConsumer,
    f: &AggregateFunction,
    input_schema: &DFSchema,
    filter: Option<Box<Expr>>,
    order_by: Vec<SortExpr>,
    distinct: bool,
) -> datafusion::common::Result<Arc<Expr>> {
    validate_aggregation_phase(f.phase)?;
    let Some(fn_signature) = consumer
        .get_extensions()
        .functions
        .get(&f.function_reference)
    else {
        return plan_err!(
            "Aggregate function not registered: function anchor = {:?}",
            f.function_reference
        );
    };

    let fn_name = substrait_fun_name(fn_signature);
    let udaf = consumer.get_function_registry().udaf(fn_name);
    let udaf = udaf.map_err(|_| {
        not_impl_datafusion_err!(
            "Aggregate function {} is not supported: function anchor = {:?}",
            fn_signature,
            f.function_reference
        )
    })?;

    let args = from_substrait_func_args(consumer, &f.arguments, input_schema).await?;

    // Datafusion does not support aggregate functions with no arguments, so
    // we inject a dummy argument that does not affect the query, but allows
    // us to bypass this limitation.
    let args = if udaf.name() == "count" && args.is_empty() {
        vec![Expr::Literal(ScalarValue::Int64(Some(1)), None)]
    } else {
        args
    };

    Ok(Arc::new(Expr::AggregateFunction(
        expr::AggregateFunction::new_udf(udaf, args, distinct, filter, order_by, None),
    )))
}