Skip to main content

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