datafusion_physical_plan/
analyze.rs1use 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#[derive(Debug, Clone)]
42pub struct AnalyzeExec {
43 verbose: bool,
45 show_statistics: bool,
47 pub(crate) input: Arc<dyn ExecutionPlan>,
49 schema: SchemaRef,
51 cache: PlanProperties,
52}
53
54impl AnalyzeExec {
55 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 pub fn verbose(&self) -> bool {
74 self.verbose
75 }
76
77 pub fn show_statistics(&self) -> bool {
79 self.show_statistics
80 }
81
82 pub fn input(&self) -> &Arc<dyn ExecutionPlan> {
84 &self.input
85 }
86
87 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 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 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 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 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 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
211fn 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 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 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}