Skip to main content

datafusion_cli/
command.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Command within CLI
6
7use crate::cli_context::CliSessionContext;
8use crate::exec::{exec_and_print, exec_from_lines};
9use crate::functions::{Function, display_all_functions};
10use crate::print_format::PrintFormat;
11use crate::print_options::PrintOptions;
12use clap::ValueEnum;
13use datafusion::arrow::array::{ArrayRef, StringArray};
14use datafusion::arrow::datatypes::{DataType, Field, Schema};
15use datafusion::arrow::record_batch::RecordBatch;
16use datafusion::common::instant::Instant;
17use datafusion::common::{exec_datafusion_err, exec_err};
18use datafusion::error::Result;
19use std::fs::File;
20use std::io::BufReader;
21use std::str::FromStr;
22use std::sync::Arc;
23
24/// Command
25#[derive(Debug)]
26pub enum Command {
27    Quit,
28    Help,
29    ListTables,
30    DescribeTableStmt(String),
31    ListFunctions,
32    Include(Option<String>),
33    SearchFunctions(String),
34    QuietMode(Option<bool>),
35    OutputFormat(Option<String>),
36    ObjectStoreProfileMode(Option<String>),
37}
38
39pub enum OutputFormat {
40    ChangeFormat(String),
41}
42
43impl Command {
44    pub async fn execute(
45        &self,
46        ctx: &dyn CliSessionContext,
47        print_options: &mut PrintOptions,
48    ) -> Result<()> {
49        match self {
50            Self::Help => {
51                let now = Instant::now();
52                let command_batch = all_commands_info();
53                let schema = command_batch.schema();
54                let num_rows = command_batch.num_rows();
55                let task_ctx = ctx.task_ctx();
56                let config = &task_ctx.session_config().options().format;
57                print_options.print_batches(
58                    schema,
59                    &[command_batch],
60                    now,
61                    num_rows,
62                    config,
63                )
64            }
65            Self::ListTables => {
66                exec_and_print(ctx, print_options, "SHOW TABLES".into()).await
67            }
68            Self::DescribeTableStmt(name) => {
69                exec_and_print(ctx, print_options, format!("SHOW COLUMNS FROM {name}"))
70                    .await
71            }
72            Self::Include(filename) => {
73                if let Some(filename) = filename {
74                    let file = File::open(filename).map_err(|e| {
75                        exec_datafusion_err!("Error opening {filename:?} {e}")
76                    })?;
77                    exec_from_lines(ctx, &mut BufReader::new(file), print_options)
78                        .await?;
79                    Ok(())
80                } else {
81                    exec_err!("Required filename argument is missing")
82                }
83            }
84            Self::QuietMode(quiet) => {
85                if let Some(quiet) = quiet {
86                    print_options.quiet = *quiet;
87                    println!(
88                        "Quiet mode set to {}",
89                        if print_options.quiet { "true" } else { "false" }
90                    );
91                } else {
92                    println!(
93                        "Quiet mode is {}",
94                        if print_options.quiet { "true" } else { "false" }
95                    );
96                }
97                Ok(())
98            }
99            Self::Quit => exec_err!("Unexpected quit, this should be handled outside"),
100            Self::ListFunctions => display_all_functions(),
101            Self::SearchFunctions(function) => {
102                if let Ok(func) = function.parse::<Function>() {
103                    let details = func.function_details()?;
104                    println!("{details}");
105                    Ok(())
106                } else {
107                    exec_err!("{function} is not a supported function")
108                }
109            }
110            Self::OutputFormat(_) => exec_err!(
111                "Unexpected change output format, this should be handled outside"
112            ),
113            Self::ObjectStoreProfileMode(mode) => {
114                if let Some(mode) = mode {
115                    let profile_mode = mode
116                        .parse()
117                        .map_err(|_|
118                            exec_datafusion_err!("Failed to parse input: {mode}. Valid options are disabled, summary, trace")
119                        )?;
120                    print_options
121                        .instrumented_registry
122                        .set_instrument_mode(profile_mode);
123                    println!(
124                        "ObjectStore Profile mode set to {}",
125                        print_options.instrumented_registry.instrument_mode()
126                    );
127                } else {
128                    println!(
129                        "ObjectStore Profile mode is {}",
130                        print_options.instrumented_registry.instrument_mode()
131                    );
132                }
133
134                Ok(())
135            }
136        }
137    }
138
139    fn get_name_and_description(&self) -> (&'static str, &'static str) {
140        match self {
141            Self::Quit => ("\\q", "quit datafusion-cli"),
142            Self::ListTables => ("\\d", "list tables"),
143            Self::DescribeTableStmt(_) => ("\\d name", "describe table"),
144            Self::Help => ("\\?", "help"),
145            Self::Include(_) => {
146                ("\\i filename", "reads input from the specified filename")
147            }
148            Self::ListFunctions => ("\\h", "function list"),
149            Self::SearchFunctions(_) => ("\\h function", "search function"),
150            Self::QuietMode(_) => ("\\quiet (true|false)?", "print or set quiet mode"),
151            Self::OutputFormat(_) => {
152                ("\\pset [NAME [VALUE]]", "set table output option\n(format)")
153            }
154            Self::ObjectStoreProfileMode(_) => (
155                "\\object_store_profiling (disabled|summary|trace)",
156                "print or set object store profile mode",
157            ),
158        }
159    }
160}
161
162const ALL_COMMANDS: [Command; 10] = [
163    Command::ListTables,
164    Command::DescribeTableStmt(String::new()),
165    Command::Quit,
166    Command::Help,
167    Command::Include(Some(String::new())),
168    Command::ListFunctions,
169    Command::SearchFunctions(String::new()),
170    Command::QuietMode(None),
171    Command::OutputFormat(None),
172    Command::ObjectStoreProfileMode(None),
173];
174
175fn all_commands_info() -> RecordBatch {
176    let schema = Arc::new(Schema::new(vec![
177        Field::new("Command", DataType::Utf8, false),
178        Field::new("Description", DataType::Utf8, false),
179    ]));
180    let (names, description): (Vec<&str>, Vec<&str>) = ALL_COMMANDS
181        .into_iter()
182        .map(|c| c.get_name_and_description())
183        .unzip();
184    RecordBatch::try_new(
185        schema,
186        [names, description]
187            .into_iter()
188            .map(|i| Arc::new(StringArray::from(i)) as ArrayRef)
189            .collect::<Vec<_>>(),
190    )
191    .expect("This should not fail")
192}
193
194impl FromStr for Command {
195    type Err = ();
196
197    fn from_str(s: &str) -> Result<Self, Self::Err> {
198        let (c, arg) = if let Some((a, b)) = s.split_once(' ') {
199            (a, Some(b))
200        } else {
201            (s, None)
202        };
203        Ok(match (c, arg) {
204            ("q", None) => Self::Quit,
205            ("d", None) => Self::ListTables,
206            ("d", Some(name)) => Self::DescribeTableStmt(name.into()),
207            ("?", None) => Self::Help,
208            ("h", None) => Self::ListFunctions,
209            ("h", Some(function)) => Self::SearchFunctions(function.into()),
210            ("i", None) => Self::Include(None),
211            ("i", Some(filename)) => Self::Include(Some(filename.to_owned())),
212            ("quiet", Some("true" | "t" | "yes" | "y" | "on")) => {
213                Self::QuietMode(Some(true))
214            }
215            ("quiet", Some("false" | "f" | "no" | "n" | "off")) => {
216                Self::QuietMode(Some(false))
217            }
218            ("quiet", None) => Self::QuietMode(None),
219            ("pset", Some(subcommand)) => {
220                Self::OutputFormat(Some(subcommand.to_string()))
221            }
222            ("pset", None) => Self::OutputFormat(None),
223            ("object_store_profiling", Some(mode)) => {
224                Self::ObjectStoreProfileMode(Some(mode.to_string()))
225            }
226            ("object_store_profiling", None) => Self::ObjectStoreProfileMode(None),
227            _ => return Err(()),
228        })
229    }
230}
231
232impl FromStr for OutputFormat {
233    type Err = ();
234
235    fn from_str(s: &str) -> Result<Self, Self::Err> {
236        let (c, arg) = if let Some((a, b)) = s.split_once(' ') {
237            (a, Some(b))
238        } else {
239            (s, None)
240        };
241        Ok(match (c, arg) {
242            ("format", Some(format)) => Self::ChangeFormat(format.to_string()),
243            _ => return Err(()),
244        })
245    }
246}
247
248impl OutputFormat {
249    pub fn execute(&self, print_options: &mut PrintOptions) -> Result<()> {
250        match self {
251            Self::ChangeFormat(format) => {
252                if let Ok(format) = format.parse::<PrintFormat>() {
253                    print_options.format = format;
254                    println!("Output format is {:?}.", print_options.format);
255                    Ok(())
256                } else {
257                    exec_err!(
258                        "{:?} is not a valid format type [possible values: {:?}]",
259                        format,
260                        PrintFormat::value_variants()
261                    )
262                }
263            }
264        }
265    }
266}
267
268#[cfg(test)]
269mod tests {
270    use datafusion::prelude::SessionContext;
271
272    use crate::{
273        object_storage::instrumented::{
274            InstrumentedObjectStoreMode, InstrumentedObjectStoreRegistry,
275        },
276        print_options::MaxRows,
277    };
278
279    use super::*;
280
281    #[tokio::test]
282    async fn command_execute_profile_mode() {
283        let ctx = SessionContext::new();
284
285        let mut print_options = PrintOptions {
286            format: PrintFormat::Automatic,
287            quiet: false,
288            maxrows: MaxRows::Unlimited,
289            color: true,
290            instrumented_registry: Arc::new(InstrumentedObjectStoreRegistry::new()),
291        };
292
293        let mut cmd: Command = "object_store_profiling"
294            .parse()
295            .expect("expected parse to succeed");
296        assert!(cmd.execute(&ctx, &mut print_options).await.is_ok());
297        assert_eq!(
298            print_options.instrumented_registry.instrument_mode(),
299            InstrumentedObjectStoreMode::default()
300        );
301
302        cmd = "object_store_profiling summary"
303            .parse()
304            .expect("expected parse to succeed");
305        assert!(cmd.execute(&ctx, &mut print_options).await.is_ok());
306        assert_eq!(
307            print_options.instrumented_registry.instrument_mode(),
308            InstrumentedObjectStoreMode::Summary
309        );
310
311        cmd = "object_store_profiling trace"
312            .parse()
313            .expect("expected parse to succeed");
314        assert!(cmd.execute(&ctx, &mut print_options).await.is_ok());
315        assert_eq!(
316            print_options.instrumented_registry.instrument_mode(),
317            InstrumentedObjectStoreMode::Trace
318        );
319
320        cmd = "object_store_profiling does_not_exist"
321            .parse()
322            .expect("expected parse to succeed");
323        assert!(cmd.execute(&ctx, &mut print_options).await.is_err());
324    }
325}