datafusion_physical_plan/
analyze.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18//! Defines the ANALYZE operator
19
20use std::any::Any;
21use std::sync::Arc;
22
23use super::stream::{RecordBatchReceiverStream, RecordBatchStreamAdapter};
24use super::{
25    DisplayAs, Distribution, ExecutionPlanProperties, PlanProperties,
26    SendableRecordBatchStream,
27};
28use crate::display::DisplayableExecutionPlan;
29use crate::{DisplayFormatType, ExecutionPlan, Partitioning};
30
31use arrow::{array::StringBuilder, datatypes::SchemaRef, record_batch::RecordBatch};
32use datafusion_common::instant::Instant;
33use datafusion_common::{internal_err, DataFusionError, Result};
34use datafusion_execution::TaskContext;
35use datafusion_physical_expr::EquivalenceProperties;
36
37use futures::StreamExt;
38
39/// `EXPLAIN ANALYZE` execution plan operator. This operator runs its input,
40/// discards the results, and then prints out an annotated plan with metrics
41#[derive(Debug, Clone)]
42pub struct AnalyzeExec {
43    /// Control how much extra to print
44    verbose: bool,
45    /// If statistics should be displayed
46    show_statistics: bool,
47    /// The input plan (the plan being analyzed)
48    pub(crate) input: Arc<dyn ExecutionPlan>,
49    /// The output schema for RecordBatches of this exec node
50    schema: SchemaRef,
51    cache: PlanProperties,
52}
53
54impl AnalyzeExec {
55    /// Create a new AnalyzeExec
56    pub fn new(
57        verbose: bool,
58        show_statistics: bool,
59        input: Arc<dyn ExecutionPlan>,
60        schema: SchemaRef,
61    ) -> Self {
62        let cache = Self::compute_properties(&input, Arc::clone(&schema));
63        AnalyzeExec {
64            verbose,
65            show_statistics,
66            input,
67            schema,
68            cache,
69        }
70    }
71
72    /// Access to verbose
73    pub fn verbose(&self) -> bool {
74        self.verbose
75    }
76
77    /// Access to show_statistics
78    pub fn show_statistics(&self) -> bool {
79        self.show_statistics
80    }
81
82    /// The input plan
83    pub fn input(&self) -> &Arc<dyn ExecutionPlan> {
84        &self.input
85    }
86
87    /// This function creates the cache object that stores the plan properties such as schema, equivalence properties, ordering, partitioning, etc.
88    fn compute_properties(
89        input: &Arc<dyn ExecutionPlan>,
90        schema: SchemaRef,
91    ) -> PlanProperties {
92        PlanProperties::new(
93            EquivalenceProperties::new(schema),
94            Partitioning::UnknownPartitioning(1),
95            input.pipeline_behavior(),
96            input.boundedness(),
97        )
98    }
99}
100
101impl DisplayAs for AnalyzeExec {
102    fn fmt_as(
103        &self,
104        t: DisplayFormatType,
105        f: &mut std::fmt::Formatter,
106    ) -> std::fmt::Result {
107        match t {
108            DisplayFormatType::Default | DisplayFormatType::Verbose => {
109                write!(f, "AnalyzeExec verbose={}", self.verbose)
110            }
111        }
112    }
113}
114
115impl ExecutionPlan for AnalyzeExec {
116    fn name(&self) -> &'static str {
117        "AnalyzeExec"
118    }
119
120    /// Return a reference to Any that can be used for downcasting
121    fn as_any(&self) -> &dyn Any {
122        self
123    }
124
125    fn properties(&self) -> &PlanProperties {
126        &self.cache
127    }
128
129    fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
130        vec![&self.input]
131    }
132
133    /// AnalyzeExec is handled specially so this value is ignored
134    fn required_input_distribution(&self) -> Vec<Distribution> {
135        vec![]
136    }
137
138    fn with_new_children(
139        self: Arc<Self>,
140        mut children: Vec<Arc<dyn ExecutionPlan>>,
141    ) -> Result<Arc<dyn ExecutionPlan>> {
142        Ok(Arc::new(Self::new(
143            self.verbose,
144            self.show_statistics,
145            children.pop().unwrap(),
146            Arc::clone(&self.schema),
147        )))
148    }
149
150    fn execute(
151        &self,
152        partition: usize,
153        context: Arc<TaskContext>,
154    ) -> Result<SendableRecordBatchStream> {
155        if 0 != partition {
156            return internal_err!(
157                "AnalyzeExec invalid partition. Expected 0, got {partition}"
158            );
159        }
160
161        // Gather futures that will run each input partition in
162        // parallel (on a separate tokio task) using a JoinSet to
163        // cancel outstanding futures on drop
164        let num_input_partitions = self.input.output_partitioning().partition_count();
165        let mut builder =
166            RecordBatchReceiverStream::builder(self.schema(), num_input_partitions);
167
168        for input_partition in 0..num_input_partitions {
169            builder.run_input(
170                Arc::clone(&self.input),
171                input_partition,
172                Arc::clone(&context),
173            );
174        }
175
176        // Create future that computes the final output
177        let start = Instant::now();
178        let captured_input = Arc::clone(&self.input);
179        let captured_schema = Arc::clone(&self.schema);
180        let verbose = self.verbose;
181        let show_statistics = self.show_statistics;
182
183        // future that gathers the results from all the tasks in the
184        // JoinSet that computes the overall row count and final
185        // record batch
186        let mut input_stream = builder.build();
187        let output = async move {
188            let mut total_rows = 0;
189            while let Some(batch) = input_stream.next().await.transpose()? {
190                total_rows += batch.num_rows();
191            }
192
193            let duration = Instant::now() - start;
194            create_output_batch(
195                verbose,
196                show_statistics,
197                total_rows,
198                duration,
199                captured_input,
200                captured_schema,
201            )
202        };
203
204        Ok(Box::pin(RecordBatchStreamAdapter::new(
205            Arc::clone(&self.schema),
206            futures::stream::once(output),
207        )))
208    }
209}
210
211/// Creates the output of AnalyzeExec as a RecordBatch
212fn create_output_batch(
213    verbose: bool,
214    show_statistics: bool,
215    total_rows: usize,
216    duration: std::time::Duration,
217    input: Arc<dyn ExecutionPlan>,
218    schema: SchemaRef,
219) -> Result<RecordBatch> {
220    let mut type_builder = StringBuilder::with_capacity(1, 1024);
221    let mut plan_builder = StringBuilder::with_capacity(1, 1024);
222
223    // TODO use some sort of enum rather than strings?
224    type_builder.append_value("Plan with Metrics");
225
226    let annotated_plan = DisplayableExecutionPlan::with_metrics(input.as_ref())
227        .set_show_statistics(show_statistics)
228        .indent(verbose)
229        .to_string();
230    plan_builder.append_value(annotated_plan);
231
232    // Verbose output
233    // TODO make this more sophisticated
234    if verbose {
235        type_builder.append_value("Plan with Full Metrics");
236
237        let annotated_plan = DisplayableExecutionPlan::with_full_metrics(input.as_ref())
238            .set_show_statistics(show_statistics)
239            .indent(verbose)
240            .to_string();
241        plan_builder.append_value(annotated_plan);
242
243        type_builder.append_value("Output Rows");
244        plan_builder.append_value(total_rows.to_string());
245
246        type_builder.append_value("Duration");
247        plan_builder.append_value(format!("{duration:?}"));
248    }
249
250    RecordBatch::try_new(
251        schema,
252        vec![
253            Arc::new(type_builder.finish()),
254            Arc::new(plan_builder.finish()),
255        ],
256    )
257    .map_err(DataFusionError::from)
258}
259
260#[cfg(test)]
261mod tests {
262    use super::*;
263    use crate::{
264        collect,
265        test::{
266            assert_is_pending,
267            exec::{assert_strong_count_converges_to_zero, BlockingExec},
268        },
269    };
270
271    use arrow::datatypes::{DataType, Field, Schema};
272    use futures::FutureExt;
273
274    #[tokio::test]
275    async fn test_drop_cancel() -> Result<()> {
276        let task_ctx = Arc::new(TaskContext::default());
277        let schema =
278            Arc::new(Schema::new(vec![Field::new("a", DataType::Float32, true)]));
279
280        let blocking_exec = Arc::new(BlockingExec::new(Arc::clone(&schema), 1));
281        let refs = blocking_exec.refs();
282        let analyze_exec = Arc::new(AnalyzeExec::new(true, false, blocking_exec, schema));
283
284        let fut = collect(analyze_exec, task_ctx);
285        let mut fut = fut.boxed();
286
287        assert_is_pending(&mut fut);
288        drop(fut);
289        assert_strong_count_converges_to_zero(refs).await;
290
291        Ok(())
292    }
293}