datafusion-physical-plan 56.0.0

Physical (ExecutionPlan) implementations for DataFusion query engine
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

//! Aggregate table for single aggregation when raw input is clustered.
//!
//! See comments in [`super::clustered_partial_table`] for details.

use arrow::datatypes::SchemaRef;
use arrow::record_batch::RecordBatch;
use datafusion_common::Result;

use crate::aggregates::aggregate_hash_table::SingleMarker;
use crate::aggregates::{AggregateExec, AggregateMode, group_values::AccumulatorPhase};

use super::common::HashAggregateAccumulator;
use super::common_clustered::{ClusteredAggregateTable, ClusteredAggregateTableMetrics};

/// Implementation specific to single aggregation, where the table stores final
/// aggregate values and the input rows are raw rows.
///
/// Example: `AVG(x) GROUP BY k`
///
/// - Aggregate table stores: `k, avg(x)`
/// - Input rows: `k, x`
///
/// See comments at [`ClusteredAggregateTable`] for details.
impl ClusteredAggregateTable<SingleMarker> {
    pub(in crate::aggregates) fn new(
        agg: &AggregateExec,
        partition: usize,
        output_schema: SchemaRef,
        state_schema: SchemaRef,
    ) -> Result<Self> {
        debug_assert!(matches!(
            agg.mode,
            AggregateMode::Single | AggregateMode::SinglePartitioned
        ));

        let input_schema = agg.input().schema();
        let metrics = ClusteredAggregateTableMetrics::new(agg, partition);
        Self::new_for_mode(
            agg,
            &input_schema,
            output_schema,
            state_schema,
            &agg.group_clustering_mode,
            &agg.mode,
            agg.filter_expr().to_vec(),
            metrics,
        )
    }

    /// Aggregates one raw input batch and updates completion state for any
    /// newly observed groups.
    pub(in crate::aggregates) fn aggregate_batch(
        &mut self,
        batch: &RecordBatch,
    ) -> Result<()> {
        let evaluated_batch = self.evaluate_batch(batch)?;
        self.aggregate_evaluated_batch(
            &evaluated_batch,
            HashAggregateAccumulator::update_batch,
            AccumulatorPhase::Update,
        )
    }

    /// Materializes final results for all completed groups, leaving
    /// the active contiguous-key range in the table.
    ///
    /// Returns None if there are no completed groups.
    pub(in crate::aggregates) fn take_completed_result_batch(
        &mut self,
    ) -> Result<Option<RecordBatch>> {
        if self.is_empty() {
            return Ok(None);
        }
        let Some(emit_to) = self.group_clustering().emit_to() else {
            return Ok(None);
        };
        self.materialize_groups(
            emit_to,
            HashAggregateAccumulator::evaluate_to_columns,
            AccumulatorPhase::Evaluate,
        )
        .map(Some)
    }
}