sql/
parser.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::str::FromStr;
16
17use snafu::ResultExt;
18use sqlparser::ast::{Ident, ObjectNamePart, Query, Value};
19use sqlparser::dialect::Dialect;
20use sqlparser::keywords::Keyword;
21use sqlparser::parser::{Parser, ParserError, ParserOptions};
22use sqlparser::tokenizer::{Token, TokenWithSpan};
23
24use crate::ast::{Expr, ObjectName};
25use crate::error::{self, Result, SyntaxSnafu};
26use crate::parsers::tql_parser;
27use crate::statements::kill::Kill;
28use crate::statements::statement::Statement;
29use crate::statements::transform_statements;
30
31pub const FLOW: &str = "FLOW";
32
33/// SQL Parser options.
34#[derive(Clone, Debug, Default)]
35pub struct ParseOptions {}
36
37/// GrepTime SQL parser context, a simple wrapper for Datafusion SQL parser.
38pub struct ParserContext<'a> {
39    pub(crate) parser: Parser<'a>,
40    pub(crate) sql: &'a str,
41}
42
43impl ParserContext<'_> {
44    /// Construct a new ParserContext.
45    pub fn new<'a>(dialect: &'a dyn Dialect, sql: &'a str) -> Result<ParserContext<'a>> {
46        let parser = Parser::new(dialect)
47            .with_options(ParserOptions::new().with_trailing_commas(true))
48            .try_with_sql(sql)
49            .context(SyntaxSnafu)?;
50
51        Ok(ParserContext { parser, sql })
52    }
53
54    /// Parses parser context to Query.
55    pub fn parser_query(&mut self) -> Result<Box<Query>> {
56        self.parser.parse_query().context(SyntaxSnafu)
57    }
58
59    /// Parses SQL with given dialect
60    pub fn create_with_dialect(
61        sql: &str,
62        dialect: &dyn Dialect,
63        _opts: ParseOptions,
64    ) -> Result<Vec<Statement>> {
65        let mut stmts: Vec<Statement> = Vec::new();
66
67        let mut parser_ctx = ParserContext::new(dialect, sql)?;
68
69        let mut expecting_statement_delimiter = false;
70        loop {
71            // ignore empty statements (between successive statement delimiters)
72            while parser_ctx.parser.consume_token(&Token::SemiColon) {
73                expecting_statement_delimiter = false;
74            }
75
76            if parser_ctx.parser.peek_token() == Token::EOF {
77                break;
78            }
79            if expecting_statement_delimiter {
80                return parser_ctx.unsupported(parser_ctx.peek_token_as_string());
81            }
82
83            let statement = parser_ctx.parse_statement()?;
84            stmts.push(statement);
85            expecting_statement_delimiter = true;
86        }
87
88        transform_statements(&mut stmts)?;
89
90        Ok(stmts)
91    }
92
93    pub fn parse_table_name(sql: &str, dialect: &dyn Dialect) -> Result<ObjectName> {
94        let parser = Parser::new(dialect)
95            .with_options(ParserOptions::new().with_trailing_commas(true))
96            .try_with_sql(sql)
97            .context(SyntaxSnafu)?;
98        ParserContext { parser, sql }.intern_parse_table_name()
99    }
100
101    pub(crate) fn intern_parse_table_name(&mut self) -> Result<ObjectName> {
102        let raw_table_name =
103            self.parser
104                .parse_object_name(false)
105                .context(error::UnexpectedSnafu {
106                    expected: "a table name",
107                    actual: self.parser.peek_token().to_string(),
108                })?;
109        Ok(Self::canonicalize_object_name(raw_table_name))
110    }
111
112    pub fn parse_function(sql: &str, dialect: &dyn Dialect) -> Result<Expr> {
113        let mut parser = Parser::new(dialect)
114            .with_options(ParserOptions::new().with_trailing_commas(true))
115            .try_with_sql(sql)
116            .context(SyntaxSnafu)?;
117
118        let function_name = parser.parse_identifier().context(SyntaxSnafu)?;
119        parser
120            .parse_function(vec![function_name].into())
121            .context(SyntaxSnafu)
122    }
123
124    /// Parses parser context to a set of statements.
125    pub fn parse_statement(&mut self) -> Result<Statement> {
126        match self.parser.peek_token().token {
127            Token::Word(w) => match w.keyword {
128                Keyword::CREATE => {
129                    let _ = self.parser.next_token();
130                    self.parse_create()
131                }
132
133                Keyword::EXPLAIN => {
134                    let _ = self.parser.next_token();
135                    self.parse_explain()
136                }
137
138                Keyword::SHOW => {
139                    let _ = self.parser.next_token();
140                    self.parse_show()
141                }
142
143                Keyword::DELETE => self.parse_delete(),
144
145                Keyword::DESCRIBE | Keyword::DESC => {
146                    let _ = self.parser.next_token();
147                    self.parse_describe()
148                }
149
150                Keyword::INSERT => self.parse_insert(),
151
152                Keyword::REPLACE => self.parse_replace(),
153
154                Keyword::SELECT | Keyword::VALUES => self.parse_query(),
155
156                Keyword::WITH => self.parse_with_tql(),
157
158                Keyword::ALTER => self.parse_alter(),
159
160                Keyword::DROP => self.parse_drop(),
161
162                Keyword::COPY => self.parse_copy(),
163
164                Keyword::TRUNCATE => self.parse_truncate(),
165
166                Keyword::SET => self.parse_set_variables(),
167
168                Keyword::ADMIN => self.parse_admin_command(),
169
170                Keyword::NoKeyword
171                    if w.quote_style.is_none() && w.value.to_uppercase() == tql_parser::TQL =>
172                {
173                    self.parse_tql()
174                }
175
176                Keyword::DECLARE => self.parse_declare_cursor(),
177
178                Keyword::FETCH => self.parse_fetch_cursor(),
179
180                Keyword::CLOSE => self.parse_close_cursor(),
181
182                Keyword::USE => {
183                    let _ = self.parser.next_token();
184
185                    let database_name = self.parser.parse_identifier().with_context(|_| {
186                        error::UnexpectedSnafu {
187                            expected: "a database name",
188                            actual: self.peek_token_as_string(),
189                        }
190                    })?;
191                    Ok(Statement::Use(
192                        Self::canonicalize_identifier(database_name).value,
193                    ))
194                }
195
196                Keyword::KILL => {
197                    let _ = self.parser.next_token();
198                    let kill = if self.parser.parse_keyword(Keyword::QUERY) {
199                        // MySQL KILL QUERY <connection id> statements
200                        let connection_id_exp =
201                            self.parser.parse_number_value().with_context(|_| {
202                                error::UnexpectedSnafu {
203                                    expected: "MySQL numeric connection id",
204                                    actual: self.peek_token_as_string(),
205                                }
206                            })?;
207                        let Value::Number(s, _) = connection_id_exp.value else {
208                            return error::UnexpectedTokenSnafu {
209                                expected: "MySQL numeric connection id",
210                                actual: connection_id_exp.to_string(),
211                            }
212                            .fail();
213                        };
214
215                        let connection_id = u32::from_str(&s).map_err(|_| {
216                            error::UnexpectedTokenSnafu {
217                                expected: "MySQL numeric connection id",
218                                actual: s,
219                            }
220                            .build()
221                        })?;
222                        Kill::ConnectionId(connection_id)
223                    } else {
224                        let process_id_ident =
225                            self.parser.parse_literal_string().with_context(|_| {
226                                error::UnexpectedSnafu {
227                                    expected: "process id string literal",
228                                    actual: self.peek_token_as_string(),
229                                }
230                            })?;
231                        Kill::ProcessId(process_id_ident)
232                    };
233
234                    Ok(Statement::Kill(kill))
235                }
236
237                _ => self.unsupported(self.peek_token_as_string()),
238            },
239            Token::LParen => self.parse_query(),
240            unexpected => self.unsupported(unexpected.to_string()),
241        }
242    }
243
244    /// Parses MySQL style 'PREPARE stmt_name FROM stmt' into a (stmt_name, stmt) tuple.
245    pub fn parse_mysql_prepare_stmt(sql: &str, dialect: &dyn Dialect) -> Result<(String, String)> {
246        ParserContext::new(dialect, sql)?.parse_mysql_prepare()
247    }
248
249    /// Parses MySQL style 'EXECUTE stmt_name USING param_list' into a stmt_name string and a list of parameters.
250    pub fn parse_mysql_execute_stmt(
251        sql: &str,
252        dialect: &dyn Dialect,
253    ) -> Result<(String, Vec<Expr>)> {
254        ParserContext::new(dialect, sql)?.parse_mysql_execute()
255    }
256
257    /// Parses MySQL style 'DEALLOCATE stmt_name' into a stmt_name string.
258    pub fn parse_mysql_deallocate_stmt(sql: &str, dialect: &dyn Dialect) -> Result<String> {
259        ParserContext::new(dialect, sql)?.parse_deallocate()
260    }
261
262    /// Raises an "unsupported statement" error.
263    pub fn unsupported<T>(&self, keyword: String) -> Result<T> {
264        error::UnsupportedSnafu { keyword }.fail()
265    }
266
267    // Report unexpected token
268    pub(crate) fn expected<T>(&self, expected: &str, found: TokenWithSpan) -> Result<T> {
269        Err(ParserError::ParserError(format!(
270            "Expected {expected}, found: {found}",
271        )))
272        .context(SyntaxSnafu)
273    }
274
275    pub fn matches_keyword(&mut self, expected: Keyword) -> bool {
276        match self.parser.peek_token().token {
277            Token::Word(w) => w.keyword == expected,
278            _ => false,
279        }
280    }
281
282    pub fn consume_token(&mut self, expected: &str) -> bool {
283        if self.peek_token_as_string().to_uppercase() == *expected.to_uppercase() {
284            let _ = self.parser.next_token();
285            true
286        } else {
287            false
288        }
289    }
290
291    #[inline]
292    pub(crate) fn peek_token_as_string(&self) -> String {
293        self.parser.peek_token().to_string()
294    }
295
296    /// Canonicalize the identifier to lowercase if it's not quoted.
297    pub fn canonicalize_identifier(ident: Ident) -> Ident {
298        if ident.quote_style.is_some() {
299            ident
300        } else {
301            Ident::new(ident.value.to_lowercase())
302        }
303    }
304
305    /// Like [canonicalize_identifier] but for [ObjectName].
306    pub fn canonicalize_object_name(object_name: ObjectName) -> ObjectName {
307        object_name
308            .0
309            .into_iter()
310            .map(|x| {
311                let ObjectNamePart::Identifier(ident) = x;
312                ident
313            })
314            .map(Self::canonicalize_identifier)
315            .collect::<Vec<_>>()
316            .into()
317    }
318
319    /// Simply a shortcut for sqlparser's same name method `parse_object_name`,
320    /// but with constant argument "false".
321    /// Because the argument is always "false" for us (it's introduced by BigQuery),
322    /// we don't want to write it again and again.
323    pub(crate) fn parse_object_name(&mut self) -> std::result::Result<ObjectName, ParserError> {
324        self.parser.parse_object_name(false)
325    }
326}
327
328#[cfg(test)]
329mod tests {
330
331    use datatypes::prelude::ConcreteDataType;
332    use sqlparser::dialect::MySqlDialect;
333
334    use super::*;
335    use crate::dialect::GreptimeDbDialect;
336    use crate::statements::create::CreateTable;
337    use crate::statements::sql_data_type_to_concrete_data_type;
338
339    fn test_timestamp_precision(sql: &str, expected_type: ConcreteDataType) {
340        match ParserContext::create_with_dialect(
341            sql,
342            &GreptimeDbDialect {},
343            ParseOptions::default(),
344        )
345        .unwrap()
346        .pop()
347        .unwrap()
348        {
349            Statement::CreateTable(CreateTable { columns, .. }) => {
350                let ts_col = columns.first().unwrap();
351                assert_eq!(
352                    expected_type,
353                    sql_data_type_to_concrete_data_type(ts_col.data_type()).unwrap()
354                );
355            }
356            _ => unreachable!(),
357        }
358    }
359
360    #[test]
361    pub fn test_create_table_with_precision() {
362        test_timestamp_precision(
363            "create table demo (ts timestamp time index, cnt int);",
364            ConcreteDataType::timestamp_millisecond_datatype(),
365        );
366        test_timestamp_precision(
367            "create table demo (ts timestamp(0) time index, cnt int);",
368            ConcreteDataType::timestamp_second_datatype(),
369        );
370        test_timestamp_precision(
371            "create table demo (ts timestamp(3) time index, cnt int);",
372            ConcreteDataType::timestamp_millisecond_datatype(),
373        );
374        test_timestamp_precision(
375            "create table demo (ts timestamp(6) time index, cnt int);",
376            ConcreteDataType::timestamp_microsecond_datatype(),
377        );
378        test_timestamp_precision(
379            "create table demo (ts timestamp(9) time index, cnt int);",
380            ConcreteDataType::timestamp_nanosecond_datatype(),
381        );
382    }
383
384    #[test]
385    #[should_panic]
386    pub fn test_create_table_with_invalid_precision() {
387        test_timestamp_precision(
388            "create table demo (ts timestamp(1) time index, cnt int);",
389            ConcreteDataType::timestamp_millisecond_datatype(),
390        );
391    }
392
393    #[test]
394    pub fn test_parse_table_name() {
395        let table_name = "a.b.c";
396
397        let object_name =
398            ParserContext::parse_table_name(table_name, &GreptimeDbDialect {}).unwrap();
399
400        assert_eq!(object_name.0.len(), 3);
401        assert_eq!(object_name.to_string(), table_name);
402
403        let table_name = "a.b";
404
405        let object_name =
406            ParserContext::parse_table_name(table_name, &GreptimeDbDialect {}).unwrap();
407
408        assert_eq!(object_name.0.len(), 2);
409        assert_eq!(object_name.to_string(), table_name);
410
411        let table_name = "Test.\"public-test\"";
412
413        let object_name =
414            ParserContext::parse_table_name(table_name, &GreptimeDbDialect {}).unwrap();
415
416        assert_eq!(object_name.0.len(), 2);
417        assert_eq!(object_name.to_string(), table_name.to_ascii_lowercase());
418
419        let table_name = "HelloWorld";
420
421        let object_name =
422            ParserContext::parse_table_name(table_name, &GreptimeDbDialect {}).unwrap();
423
424        assert_eq!(object_name.0.len(), 1);
425        assert_eq!(object_name.to_string(), table_name.to_ascii_lowercase());
426    }
427
428    #[test]
429    pub fn test_parse_mysql_prepare_stmt() {
430        let sql = "PREPARE stmt1 FROM 'SELECT * FROM t1 WHERE id = ?';";
431        let (stmt_name, stmt) =
432            ParserContext::parse_mysql_prepare_stmt(sql, &MySqlDialect {}).unwrap();
433        assert_eq!(stmt_name, "stmt1");
434        assert_eq!(stmt, "SELECT * FROM t1 WHERE id = ?");
435
436        let sql = "PREPARE stmt2 FROM \"SELECT * FROM t1 WHERE id = ?\"";
437        let (stmt_name, stmt) =
438            ParserContext::parse_mysql_prepare_stmt(sql, &MySqlDialect {}).unwrap();
439        assert_eq!(stmt_name, "stmt2");
440        assert_eq!(stmt, "SELECT * FROM t1 WHERE id = ?");
441    }
442
443    #[test]
444    pub fn test_parse_mysql_execute_stmt() {
445        let sql = "EXECUTE stmt1 USING 1, 'hello';";
446        let (stmt_name, params) =
447            ParserContext::parse_mysql_execute_stmt(sql, &GreptimeDbDialect {}).unwrap();
448        assert_eq!(stmt_name, "stmt1");
449        assert_eq!(params.len(), 2);
450        assert_eq!(params[0].to_string(), "1");
451        assert_eq!(params[1].to_string(), "'hello'");
452
453        let sql = "EXECUTE stmt2;";
454        let (stmt_name, params) =
455            ParserContext::parse_mysql_execute_stmt(sql, &GreptimeDbDialect {}).unwrap();
456        assert_eq!(stmt_name, "stmt2");
457        assert_eq!(params.len(), 0);
458
459        let sql = "EXECUTE stmt3 USING 231, 'hello', \"2003-03-1\", NULL, ;";
460        let (stmt_name, params) =
461            ParserContext::parse_mysql_execute_stmt(sql, &GreptimeDbDialect {}).unwrap();
462        assert_eq!(stmt_name, "stmt3");
463        assert_eq!(params.len(), 4);
464        assert_eq!(params[0].to_string(), "231");
465        assert_eq!(params[1].to_string(), "'hello'");
466        assert_eq!(params[2].to_string(), "\"2003-03-1\"");
467        assert_eq!(params[3].to_string(), "NULL");
468    }
469
470    #[test]
471    pub fn test_parse_mysql_deallocate_stmt() {
472        let sql = "DEALLOCATE stmt1;";
473        let stmt_name = ParserContext::parse_mysql_deallocate_stmt(sql, &MySqlDialect {}).unwrap();
474        assert_eq!(stmt_name, "stmt1");
475
476        let sql = "DEALLOCATE stmt2";
477        let stmt_name = ParserContext::parse_mysql_deallocate_stmt(sql, &MySqlDialect {}).unwrap();
478        assert_eq!(stmt_name, "stmt2");
479    }
480
481    #[test]
482    pub fn test_parse_kill_query_statement() {
483        use crate::statements::kill::Kill;
484
485        // Test MySQL-style KILL QUERY with connection ID
486        let sql = "KILL QUERY 123";
487        let statements =
488            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
489                .unwrap();
490
491        assert_eq!(statements.len(), 1);
492        match &statements[0] {
493            Statement::Kill(Kill::ConnectionId(connection_id)) => {
494                assert_eq!(*connection_id, 123);
495            }
496            _ => panic!("Expected Kill::ConnectionId statement"),
497        }
498
499        // Test with larger connection ID
500        let sql = "KILL QUERY 999999";
501        let statements =
502            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
503                .unwrap();
504
505        assert_eq!(statements.len(), 1);
506        match &statements[0] {
507            Statement::Kill(Kill::ConnectionId(connection_id)) => {
508                assert_eq!(*connection_id, 999999);
509            }
510            _ => panic!("Expected Kill::ConnectionId statement"),
511        }
512    }
513
514    #[test]
515    pub fn test_parse_kill_process_statement() {
516        use crate::statements::kill::Kill;
517
518        // Test KILL with process ID string
519        let sql = "KILL 'process-123'";
520        let statements =
521            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
522                .unwrap();
523
524        assert_eq!(statements.len(), 1);
525        match &statements[0] {
526            Statement::Kill(Kill::ProcessId(process_id)) => {
527                assert_eq!(process_id, "process-123");
528            }
529            _ => panic!("Expected Kill::ProcessId statement"),
530        }
531
532        // Test with double quotes
533        let sql = "KILL \"process-456\"";
534        let statements =
535            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
536                .unwrap();
537
538        assert_eq!(statements.len(), 1);
539        match &statements[0] {
540            Statement::Kill(Kill::ProcessId(process_id)) => {
541                assert_eq!(process_id, "process-456");
542            }
543            _ => panic!("Expected Kill::ProcessId statement"),
544        }
545
546        // Test with UUID-like process ID
547        let sql = "KILL 'f47ac10b-58cc-4372-a567-0e02b2c3d479'";
548        let statements =
549            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
550                .unwrap();
551
552        assert_eq!(statements.len(), 1);
553        match &statements[0] {
554            Statement::Kill(Kill::ProcessId(process_id)) => {
555                assert_eq!(process_id, "f47ac10b-58cc-4372-a567-0e02b2c3d479");
556            }
557            _ => panic!("Expected Kill::ProcessId statement"),
558        }
559    }
560
561    #[test]
562    pub fn test_parse_kill_statement_errors() {
563        // Test KILL QUERY without connection ID
564        let sql = "KILL QUERY";
565        let result =
566            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default());
567        assert!(result.is_err());
568
569        // Test KILL QUERY with non-numeric connection ID
570        let sql = "KILL QUERY 'not-a-number'";
571        let result =
572            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default());
573        assert!(result.is_err());
574
575        // Test KILL without any argument
576        let sql = "KILL";
577        let result =
578            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default());
579        assert!(result.is_err());
580
581        // Test KILL QUERY with connection ID that's too large for u32
582        let sql = "KILL QUERY 4294967296"; // u32::MAX + 1
583        let result =
584            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default());
585        assert!(result.is_err());
586    }
587
588    #[test]
589    pub fn test_parse_kill_statement_edge_cases() {
590        use crate::statements::kill::Kill;
591
592        // Test KILL QUERY with zero connection ID
593        let sql = "KILL QUERY 0";
594        let statements =
595            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
596                .unwrap();
597
598        assert_eq!(statements.len(), 1);
599        match &statements[0] {
600            Statement::Kill(Kill::ConnectionId(connection_id)) => {
601                assert_eq!(*connection_id, 0);
602            }
603            _ => panic!("Expected Kill::ConnectionId statement"),
604        }
605
606        // Test KILL QUERY with maximum u32 value
607        let sql = "KILL QUERY 4294967295"; // u32::MAX
608        let statements =
609            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
610                .unwrap();
611
612        assert_eq!(statements.len(), 1);
613        match &statements[0] {
614            Statement::Kill(Kill::ConnectionId(connection_id)) => {
615                assert_eq!(*connection_id, 4294967295);
616            }
617            _ => panic!("Expected Kill::ConnectionId statement"),
618        }
619
620        // Test KILL with empty string process ID
621        let sql = "KILL ''";
622        let statements =
623            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
624                .unwrap();
625
626        assert_eq!(statements.len(), 1);
627        match &statements[0] {
628            Statement::Kill(Kill::ProcessId(process_id)) => {
629                assert_eq!(process_id, "");
630            }
631            _ => panic!("Expected Kill::ProcessId statement"),
632        }
633    }
634
635    #[test]
636    pub fn test_parse_kill_statement_case_insensitive() {
637        use crate::statements::kill::Kill;
638
639        // Test lowercase
640        let sql = "kill query 123";
641        let statements =
642            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
643                .unwrap();
644
645        assert_eq!(statements.len(), 1);
646        match &statements[0] {
647            Statement::Kill(Kill::ConnectionId(connection_id)) => {
648                assert_eq!(*connection_id, 123);
649            }
650            _ => panic!("Expected Kill::ConnectionId statement"),
651        }
652
653        // Test mixed case
654        let sql = "Kill Query 456";
655        let statements =
656            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
657                .unwrap();
658
659        assert_eq!(statements.len(), 1);
660        match &statements[0] {
661            Statement::Kill(Kill::ConnectionId(connection_id)) => {
662                assert_eq!(*connection_id, 456);
663            }
664            _ => panic!("Expected Kill::ConnectionId statement"),
665        }
666    }
667}