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