datafusion_cli/
print_options.rs1use std::fmt::{Display, Formatter};
6use std::io;
7use std::pin::Pin;
8use std::str::FromStr;
9use std::sync::Arc;
10
11use crate::object_storage::instrumented::{
12 InstrumentedObjectStoreMode, InstrumentedObjectStoreRegistry, RequestSummaries,
13};
14use crate::print_format::PrintFormat;
15
16use arrow::datatypes::SchemaRef;
17use arrow::record_batch::RecordBatch;
18use datafusion::common::DataFusionError;
19use datafusion::common::instant::Instant;
20use datafusion::error::Result;
21use datafusion::physical_plan::RecordBatchStream;
22
23use datafusion::config::FormatOptions;
24use futures::StreamExt;
25
26#[derive(Debug, Clone, PartialEq, Copy)]
27pub enum MaxRows {
28 Unlimited,
30 Limited(usize),
32}
33
34impl FromStr for MaxRows {
35 type Err = String;
36
37 fn from_str(maxrows: &str) -> Result<Self, Self::Err> {
38 if maxrows.to_lowercase() == "inf"
39 || maxrows.to_lowercase() == "infinite"
40 || maxrows.to_lowercase() == "none"
41 {
42 Ok(Self::Unlimited)
43 } else {
44 match maxrows.parse::<usize>() {
45 Ok(nrows) => Ok(Self::Limited(nrows)),
46 _ => Err(format!(
47 "Invalid maxrows {maxrows}. Valid inputs are natural numbers or \'none\', \'inf\', or \'infinite\' for no limit."
48 )),
49 }
50 }
51 }
52}
53
54impl Display for MaxRows {
55 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
56 match self {
57 Self::Unlimited => write!(f, "unlimited"),
58 Self::Limited(max_rows) => write!(f, "at most {max_rows}"),
59 }
60 }
61}
62
63const OBJECT_STORE_PROFILING_HEADER: &str = "Object Store Profiling";
64
65#[derive(Debug, Clone)]
66pub struct PrintOptions {
67 pub format: PrintFormat,
68 pub quiet: bool,
69 pub maxrows: MaxRows,
70 pub color: bool,
71 pub instrumented_registry: Arc<InstrumentedObjectStoreRegistry>,
72}
73
74fn get_execution_details_formatted(
76 row_count: usize,
77 maxrows: MaxRows,
78 query_start_time: Instant,
79) -> String {
80 let nrows_shown_msg = match maxrows {
81 MaxRows::Limited(nrows) if nrows < row_count => {
82 format!("(First {nrows} displayed. Use --maxrows to adjust)")
83 }
84 _ => String::new(),
85 };
86
87 format!(
88 "{} row(s) fetched. {}\nElapsed {:.3} seconds.\n",
89 row_count,
90 nrows_shown_msg,
91 query_start_time.elapsed().as_secs_f64()
92 )
93}
94
95impl PrintOptions {
96 pub fn print_batches(
98 &self,
99 schema: SchemaRef,
100 batches: &[RecordBatch],
101 query_start_time: Instant,
102 row_count: usize,
103 format_options: &FormatOptions,
104 ) -> Result<()> {
105 let stdout = io::stdout();
106 let mut writer = stdout.lock();
107
108 self.format.print_batches(
109 &mut writer,
110 schema,
111 batches,
112 self.maxrows,
113 true,
114 format_options,
115 )?;
116
117 let formatted_exec_details = get_execution_details_formatted(
118 row_count,
119 if self.format == PrintFormat::Table {
120 self.maxrows
121 } else {
122 MaxRows::Unlimited
123 },
124 query_start_time,
125 );
126
127 self.write_output(&mut writer, &formatted_exec_details)
128 }
129
130 pub async fn print_stream(
132 &self,
133 mut stream: Pin<Box<dyn RecordBatchStream>>,
134 query_start_time: Instant,
135 format_options: &FormatOptions,
136 ) -> Result<()> {
137 if self.format == PrintFormat::Table {
138 return Err(DataFusionError::External(
139 "PrintFormat::Table is not implemented".to_string().into(),
140 ));
141 }
142
143 let stdout = io::stdout();
144 let mut writer = stdout.lock();
145
146 let mut row_count = 0_usize;
147 let mut with_header = true;
148
149 while let Some(maybe_batch) = stream.next().await {
150 let batch = maybe_batch?;
151 row_count += batch.num_rows();
152 self.format.print_batches(
153 &mut writer,
154 batch.schema(),
155 &[batch],
156 MaxRows::Unlimited,
157 with_header,
158 format_options,
159 )?;
160 with_header = false;
161 }
162
163 let formatted_exec_details = get_execution_details_formatted(
164 row_count,
165 MaxRows::Unlimited,
166 query_start_time,
167 );
168
169 self.write_output(&mut writer, &formatted_exec_details)
170 }
171
172 fn write_output<W: io::Write>(
173 &self,
174 writer: &mut W,
175 formatted_exec_details: &str,
176 ) -> Result<()> {
177 if !self.quiet {
178 writeln!(writer, "{formatted_exec_details}")?;
179
180 let instrument_mode = self.instrumented_registry.instrument_mode();
181 if instrument_mode != InstrumentedObjectStoreMode::Disabled {
182 writeln!(writer, "{OBJECT_STORE_PROFILING_HEADER}")?;
183 for store in self.instrumented_registry.stores() {
184 let requests = store.take_requests();
185
186 if !requests.is_empty() {
187 writeln!(writer, "{store}")?;
188 if instrument_mode == InstrumentedObjectStoreMode::Trace {
189 for req in requests.iter() {
190 writeln!(writer, "{req}")?;
191 }
192 writeln!(writer)?;
194 }
195
196 writeln!(writer, "Summaries:")?;
197 let summaries = RequestSummaries::new(&requests);
198 writeln!(writer, "{summaries}")?;
199 }
200 }
201 }
202 }
203
204 Ok(())
205 }
206}
207
208#[cfg(test)]
209mod tests {
210 use datafusion::error::Result;
211
212 use super::*;
213
214 #[test]
215 fn write_output() -> Result<()> {
216 let instrumented_registry = Arc::new(InstrumentedObjectStoreRegistry::new());
217 let mut print_options = PrintOptions {
218 format: PrintFormat::Automatic,
219 quiet: true,
220 maxrows: MaxRows::Unlimited,
221 color: true,
222 instrumented_registry: Arc::clone(&instrumented_registry),
223 };
224
225 let mut print_output: Vec<u8> = Vec::new();
226 let exec_out = String::from("Formatted Exec Output");
227 print_options.write_output(&mut print_output, &exec_out)?;
228 assert!(print_output.is_empty());
229
230 print_options.quiet = false;
231 print_options.write_output(&mut print_output, &exec_out)?;
232 let out_str: String = print_output
233 .clone()
234 .try_into()
235 .expect("Expected successful String conversion");
236 assert!(out_str.contains(&exec_out));
237
238 print_output.clear();
240 print_options
241 .instrumented_registry
242 .set_instrument_mode(InstrumentedObjectStoreMode::Trace);
243 print_options.write_output(&mut print_output, &exec_out)?;
244 let out_str: String = print_output
245 .clone()
246 .try_into()
247 .expect("Expected successful String conversion");
248 assert!(out_str.contains(&exec_out));
249 assert!(out_str.contains(OBJECT_STORE_PROFILING_HEADER));
250
251 Ok(())
252 }
253}