Skip to main content

datafusion_cli/
helper.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//! Helper that helps with interactive editing, including multi-line parsing and validation,
6//! and auto-completion for file name during creating external table.
7
8use std::borrow::Cow;
9use std::cell::Cell;
10
11use crate::highlighter::{Color, NoSyntaxHighlighter, SyntaxHighlighter};
12
13use datafusion::sql::parser::{DFParser, DFParserBuilder, Statement};
14use datafusion::sql::sqlparser::dialect::dialect_from_str;
15use datafusion_common::config::{Dialect, SqlParserOptions};
16
17use rustyline::completion::{Completer, FilenameCompleter, Pair};
18use rustyline::error::ReadlineError;
19use rustyline::highlight::{CmdKind, Highlighter};
20use rustyline::hint::Hinter;
21use rustyline::validate::{ValidationContext, ValidationResult, Validator};
22use rustyline::{Context, Helper, Result};
23
24/// Default suggestion shown when the input line is empty.
25const DEFAULT_HINT_SUGGESTION: &str = " \\? for help, \\q to quit";
26
27pub struct CliHelper {
28    completer: FilenameCompleter,
29    dialect: Dialect,
30    recursion_limit: usize,
31    highlighter: Box<dyn Highlighter>,
32    /// Tracks whether to show the default hint. Set to `false` once the user
33    /// types anything, so the hint doesn't reappear after deleting back to
34    /// an empty line. Reset to `true` when the line is submitted.
35    show_hint: Cell<bool>,
36}
37
38impl CliHelper {
39    pub fn new(dialect: &Dialect, color: bool) -> Self {
40        let highlighter: Box<dyn Highlighter> = if !color {
41            Box::new(NoSyntaxHighlighter {})
42        } else {
43            Box::new(SyntaxHighlighter::new(dialect))
44        };
45        Self {
46            completer: FilenameCompleter::new(),
47            dialect: *dialect,
48            recursion_limit: SqlParserOptions::default().recursion_limit.get(),
49            highlighter,
50            show_hint: Cell::new(true),
51        }
52    }
53
54    pub fn set_dialect(&mut self, dialect: &Dialect) {
55        if *dialect != self.dialect {
56            self.dialect = *dialect;
57        }
58    }
59
60    /// Sets the parser options (dialect and recursion limit) used when
61    /// validating input, see `datafusion.sql_parser.*`.
62    pub fn set_parser_options(&mut self, options: &SqlParserOptions) {
63        self.set_dialect(&options.dialect);
64        self.recursion_limit = options.recursion_limit.get();
65    }
66
67    /// Re-enable the default hint for the next prompt.
68    pub fn reset_hint(&self) {
69        self.show_hint.set(true);
70    }
71
72    fn validate_input(&self, input: &str) -> Result<ValidationResult> {
73        if let Some(sql) = input.strip_suffix(';') {
74            let Some(dialect) = dialect_from_str(self.dialect) else {
75                return Ok(ValidationResult::Invalid(Some(format!(
76                    "  🤔 Invalid dialect: {}",
77                    self.dialect
78                ))));
79            };
80            let lines = split_from_semicolon(sql);
81            for line in lines {
82                let statements = DFParserBuilder::new(line.as_str())
83                    .with_dialect(dialect.as_ref())
84                    .with_recursion_limit(self.recursion_limit)
85                    .build()
86                    .and_then(|mut parser| parser.parse_statements());
87                match statements {
88                    Ok(statements) if statements.is_empty() => {
89                        return Ok(ValidationResult::Invalid(Some(
90                            "  🤔 You entered an empty statement".to_string(),
91                        )));
92                    }
93                    Ok(_statements) => {}
94                    Err(err) => {
95                        return Ok(ValidationResult::Invalid(Some(format!(
96                            "  🤔 Invalid statement: {err}",
97                        ))));
98                    }
99                }
100            }
101            Ok(ValidationResult::Valid(None))
102        } else if input.starts_with('\\') {
103            // command
104            Ok(ValidationResult::Valid(None))
105        } else {
106            Ok(ValidationResult::Incomplete)
107        }
108    }
109}
110
111impl Default for CliHelper {
112    fn default() -> Self {
113        Self::new(&Dialect::Generic, false)
114    }
115}
116
117impl Highlighter for CliHelper {
118    fn highlight<'l>(&self, line: &'l str, pos: usize) -> Cow<'l, str> {
119        self.highlighter.highlight(line, pos)
120    }
121
122    fn highlight_char(&self, line: &str, pos: usize, kind: CmdKind) -> bool {
123        self.highlighter.highlight_char(line, pos, kind)
124    }
125
126    fn highlight_hint<'h>(&self, hint: &'h str) -> Cow<'h, str> {
127        Color::gray(hint).into()
128    }
129}
130
131impl Hinter for CliHelper {
132    type Hint = String;
133
134    fn hint(&self, line: &str, _pos: usize, _ctx: &Context<'_>) -> Option<String> {
135        if !line.is_empty() {
136            self.show_hint.set(false);
137        }
138        (self.show_hint.get() && line.trim().is_empty())
139            .then(|| DEFAULT_HINT_SUGGESTION.to_owned())
140    }
141}
142
143/// returns true if the current position is after the open quote for
144/// creating an external table.
145fn is_open_quote_for_location(line: &str, pos: usize) -> bool {
146    let mut sql = line[..pos].to_string();
147    sql.push('\'');
148    DFParser::parse_sql(&sql).is_ok_and(|stmts| {
149        matches!(stmts.back(), Some(Statement::CreateExternalTable(_)))
150    })
151}
152
153impl Completer for CliHelper {
154    type Candidate = Pair;
155
156    fn complete(
157        &self,
158        line: &str,
159        pos: usize,
160        ctx: &Context<'_>,
161    ) -> std::result::Result<(usize, Vec<Pair>), ReadlineError> {
162        if is_open_quote_for_location(line, pos) {
163            self.completer.complete(line, pos, ctx)
164        } else {
165            Ok((0, Vec::new()))
166        }
167    }
168}
169
170impl Validator for CliHelper {
171    fn validate(&self, ctx: &mut ValidationContext<'_>) -> Result<ValidationResult> {
172        let input = ctx.input().trim_end();
173        let result = self.validate_input(input);
174        self.reset_hint();
175        result
176    }
177}
178
179impl Helper for CliHelper {}
180
181/// Splits a string which consists of multiple queries.
182pub(crate) fn split_from_semicolon(sql: &str) -> Vec<String> {
183    let mut commands = Vec::new();
184    let mut current_command = String::with_capacity(sql.len());
185    let mut in_single_quote = false;
186    let mut in_double_quote = false;
187
188    for c in sql.chars() {
189        if c == '\'' && !in_double_quote {
190            in_single_quote = !in_single_quote;
191        } else if c == '"' && !in_single_quote {
192            in_double_quote = !in_double_quote;
193        }
194
195        if c == ';' && !in_single_quote && !in_double_quote {
196            if !current_command.trim().is_empty() {
197                commands.push(format!("{};", current_command.trim()));
198                current_command.clear();
199            }
200        } else {
201            current_command.push(c);
202        }
203    }
204
205    if !current_command.trim().is_empty() {
206        commands.push(format!("{};", current_command.trim()));
207    }
208
209    commands
210}
211
212#[cfg(test)]
213mod tests {
214    use std::io::{BufRead, Cursor};
215
216    use super::*;
217
218    use datafusion_common::config::ConfigNonZeroUsize;
219
220    fn readline_direct(
221        mut reader: impl BufRead,
222        validator: &CliHelper,
223    ) -> Result<ValidationResult> {
224        let mut input = String::new();
225
226        if reader.read_line(&mut input)? == 0 {
227            return Err(ReadlineError::Eof);
228        }
229
230        validator.validate_input(&input)
231    }
232
233    #[test]
234    fn unescape_readline_input() -> Result<()> {
235        let validator = CliHelper::default();
236
237        // should be valid
238        let result = readline_direct(
239             Cursor::new(
240                 r"create external table test stored as csv location 'data.csv' options ('format.delimiter' ',');"
241                     .as_bytes(),
242             ),
243             &validator,
244         )?;
245        assert!(matches!(result, ValidationResult::Valid(None)));
246
247        let result = readline_direct(
248             Cursor::new(
249                 r"create external table test stored as csv location 'data.csv' options ('format.delimiter' '\0');"
250                     .as_bytes()),
251             &validator,
252         )?;
253        assert!(matches!(result, ValidationResult::Valid(None)));
254
255        let result = readline_direct(
256             Cursor::new(
257                 r"create external table test stored as csv location 'data.csv' options ('format.delimiter' '\n');"
258                     .as_bytes()),
259             &validator,
260         )?;
261        assert!(matches!(result, ValidationResult::Valid(None)));
262
263        let result = readline_direct(
264             Cursor::new(
265                 r"create external table test stored as csv location 'data.csv' options ('format.delimiter' '\r');"
266                     .as_bytes()),
267             &validator,
268         )?;
269        assert!(matches!(result, ValidationResult::Valid(None)));
270
271        let result = readline_direct(
272             Cursor::new(
273                 r"create external table test stored as csv location 'data.csv' options ('format.delimiter' '\t');"
274                     .as_bytes()),
275             &validator,
276         )?;
277        assert!(matches!(result, ValidationResult::Valid(None)));
278
279        let result = readline_direct(
280             Cursor::new(
281                 r"create external table test stored as csv location 'data.csv' options ('format.delimiter' '\\');"
282                     .as_bytes()),
283             &validator,
284         )?;
285        assert!(matches!(result, ValidationResult::Valid(None)));
286
287        let result = readline_direct(
288             Cursor::new(
289                 r"create external table test stored as csv location 'data.csv' options ('format.delimiter' ',,');"
290                     .as_bytes()),
291             &validator,
292         )?;
293        assert!(matches!(result, ValidationResult::Valid(None)));
294
295        let result = readline_direct(
296            Cursor::new(
297                r"select '\', '\\', '\\\\\', 'dsdsds\\\\', '\t', '\0', '\n';".as_bytes(),
298            ),
299            &validator,
300        )?;
301        assert!(matches!(result, ValidationResult::Valid(None)));
302
303        Ok(())
304    }
305
306    #[test]
307    fn sql_dialect() -> Result<()> {
308        let mut validator = CliHelper::default();
309
310        // should be invalid in generic dialect
311        let result = readline_direct(Cursor::new(br"select 1 # 2;"), &validator)?;
312        assert!(
313            matches!(result, ValidationResult::Invalid(Some(e)) if e.contains("Invalid statement"))
314        );
315
316        // valid in postgresql dialect
317        validator.set_dialect(&Dialect::PostgreSQL);
318        let result = readline_direct(Cursor::new(br"select 1 # 2;"), &validator)?;
319        assert!(matches!(result, ValidationResult::Valid(None)));
320
321        Ok(())
322    }
323
324    #[test]
325    fn sql_recursion_limit() -> Result<()> {
326        let mut validator = CliHelper::default();
327        let nested = |depth: usize| {
328            format!("select {}1{};", "abs(".repeat(depth), ")".repeat(depth))
329        };
330        let with_limit = |limit: usize| SqlParserOptions {
331            recursion_limit: ConfigNonZeroUsize::try_new(limit).unwrap(),
332            ..Default::default()
333        };
334
335        // exceeds the default recursion limit
336        let result = readline_direct(Cursor::new(nested(60)), &validator)?;
337        assert!(
338            matches!(result, ValidationResult::Invalid(Some(e)) if e.contains("RecursionLimitExceeded"))
339        );
340
341        validator.set_parser_options(&with_limit(100));
342        let result = readline_direct(Cursor::new(nested(60)), &validator)?;
343        assert!(matches!(result, ValidationResult::Valid(None)));
344
345        validator.set_parser_options(&with_limit(5));
346        let result = readline_direct(Cursor::new(nested(10)), &validator)?;
347        assert!(
348            matches!(result, ValidationResult::Invalid(Some(e)) if e.contains("RecursionLimitExceeded"))
349        );
350
351        Ok(())
352    }
353
354    #[test]
355    fn test_split_from_semicolon() {
356        let sql = "SELECT 1; SELECT 2;";
357        let expected = vec!["SELECT 1;", "SELECT 2;"];
358        assert_eq!(split_from_semicolon(sql), expected);
359
360        let sql = r#"SELECT ";";"#;
361        let expected = vec![r#"SELECT ";";"#];
362        assert_eq!(split_from_semicolon(sql), expected);
363
364        let sql = "SELECT ';';";
365        let expected = vec!["SELECT ';';"];
366        assert_eq!(split_from_semicolon(sql), expected);
367
368        let sql = r#"SELECT 1; SELECT 'value;value'; SELECT 1 as "text;text";"#;
369        let expected = vec![
370            "SELECT 1;",
371            "SELECT 'value;value';",
372            r#"SELECT 1 as "text;text";"#,
373        ];
374        assert_eq!(split_from_semicolon(sql), expected);
375
376        let sql = "";
377        let expected: Vec<String> = Vec::new();
378        assert_eq!(split_from_semicolon(sql), expected);
379
380        let sql = "SELECT 1";
381        let expected = vec!["SELECT 1;"];
382        assert_eq!(split_from_semicolon(sql), expected);
383
384        let sql = "SELECT 1;   ";
385        let expected = vec!["SELECT 1;"];
386        assert_eq!(split_from_semicolon(sql), expected);
387    }
388}