sql/parsers/
delete_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 snafu::ResultExt;
16use sqlparser::ast::Statement as SpStatement;
17
18use crate::error::{self, Result};
19use crate::parser::ParserContext;
20use crate::statements::delete::Delete;
21use crate::statements::statement::Statement;
22
23/// DELETE statement parser implementation
24impl ParserContext<'_> {
25    pub(crate) fn parse_delete(&mut self) -> Result<Statement> {
26        let _ = self.parser.next_token();
27        let spstatement = self.parser.parse_delete().context(error::SyntaxSnafu)?;
28
29        match spstatement {
30            SpStatement::Delete { .. } => {
31                Ok(Statement::Delete(Box::new(Delete { inner: spstatement })))
32            }
33            unexp => error::UnsupportedSnafu {
34                keyword: unexp.to_string(),
35            }
36            .fail(),
37        }
38    }
39}
40
41#[cfg(test)]
42mod tests {
43    use std::assert_matches::assert_matches;
44
45    use super::*;
46    use crate::dialect::GreptimeDbDialect;
47    use crate::parser::ParseOptions;
48
49    #[test]
50    pub fn test_parse_insert() {
51        let sql = r"delete from my_table where k1 = xxx and k2 = xxx and timestamp = xxx;";
52        let result =
53            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
54                .unwrap();
55        assert_eq!(1, result.len());
56        assert_matches!(result[0], Statement::Delete { .. })
57    }
58
59    #[test]
60    pub fn test_parse_invalid_insert() {
61        let sql = r"delete my_table where "; // intentionally a bad sql
62        let result =
63            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default());
64        assert!(result.is_err(), "result is: {result:?}");
65    }
66}