Skip to main content

sql/parsers/
drop_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, ensure};
16use sqlparser::dialect::keywords::Keyword;
17use sqlparser::tokenizer::Token;
18
19use crate::error::{self, InvalidFlowNameSnafu, InvalidTableNameSnafu, Result};
20use crate::parser::{FLOW, ParserContext};
21#[cfg(feature = "enterprise")]
22use crate::statements::drop::trigger::DropTrigger;
23use crate::statements::drop::{DropDatabase, DropFlow, DropTable, DropView, UndropTable};
24use crate::statements::statement::Statement;
25
26/// DROP statement parser implementation
27impl ParserContext<'_> {
28    pub(crate) fn parse_undrop_table(&mut self) -> Result<Statement> {
29        let _ = self.parser.next_token();
30        if !self.parser.parse_keyword(Keyword::TABLE) {
31            return self.expected("TABLE", self.parser.peek_token());
32        }
33
34        let raw_table_name = self
35            .parse_object_name()
36            .with_context(|_| error::UnexpectedSnafu {
37                expected: "a table name",
38                actual: self.peek_token_as_string(),
39            })?;
40        let table_name = Self::canonicalize_object_name(raw_table_name)?;
41        ensure!(
42            !table_name.0.is_empty(),
43            InvalidTableNameSnafu {
44                name: table_name.to_string()
45            }
46        );
47
48        Ok(Statement::UndropTable(UndropTable::new(table_name)))
49    }
50
51    pub(crate) fn parse_drop(&mut self) -> Result<Statement> {
52        let _ = self.parser.next_token();
53        match self.parser.peek_token().token {
54            Token::Word(w) => match w.keyword {
55                Keyword::TABLE => self.parse_drop_table(),
56                Keyword::VIEW => self.parse_drop_view(),
57                #[cfg(feature = "enterprise")]
58                Keyword::TRIGGER => self.parse_drop_trigger(),
59                Keyword::SCHEMA | Keyword::DATABASE => self.parse_drop_database(),
60                Keyword::NoKeyword => {
61                    let uppercase = w.value.to_uppercase();
62                    match uppercase.as_str() {
63                        FLOW => self.parse_drop_flow(),
64                        _ => self.unsupported(w.to_string()),
65                    }
66                }
67                _ => self.unsupported(w.to_string()),
68            },
69            unexpected => self.unsupported(unexpected.to_string()),
70        }
71    }
72
73    #[cfg(feature = "enterprise")]
74    fn parse_drop_trigger(&mut self) -> Result<Statement> {
75        let _ = self.parser.next_token();
76
77        let if_exists = self.parser.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
78        let raw_trigger_ident =
79            self.parse_object_name()
80                .with_context(|_| error::UnexpectedSnafu {
81                    expected: "a trigger name",
82                    actual: self.peek_token_as_string(),
83                })?;
84        let trigger_ident = Self::canonicalize_object_name(raw_trigger_ident)?;
85        ensure!(
86            !trigger_ident.0.is_empty(),
87            error::InvalidTriggerNameSnafu {
88                name: trigger_ident.to_string()
89            }
90        );
91
92        Ok(Statement::DropTrigger(DropTrigger::new(
93            trigger_ident,
94            if_exists,
95        )))
96    }
97
98    fn parse_drop_view(&mut self) -> Result<Statement> {
99        let _ = self.parser.next_token();
100
101        let if_exists = self.parser.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
102        let raw_view_ident = self
103            .parse_object_name()
104            .with_context(|_| error::UnexpectedSnafu {
105                expected: "a view name",
106                actual: self.peek_token_as_string(),
107            })?;
108        let view_ident = Self::canonicalize_object_name(raw_view_ident)?;
109        ensure!(
110            !view_ident.0.is_empty(),
111            InvalidTableNameSnafu {
112                name: view_ident.to_string()
113            }
114        );
115
116        Ok(Statement::DropView(DropView {
117            view_name: view_ident,
118            drop_if_exists: if_exists,
119        }))
120    }
121
122    fn parse_drop_flow(&mut self) -> Result<Statement> {
123        let _ = self.parser.next_token();
124
125        let if_exists = self.parser.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
126        let raw_flow_ident = self
127            .parse_object_name()
128            .with_context(|_| error::UnexpectedSnafu {
129                expected: "a flow name",
130                actual: self.peek_token_as_string(),
131            })?;
132        let flow_ident = Self::canonicalize_object_name(raw_flow_ident)?;
133        ensure!(
134            !flow_ident.0.is_empty(),
135            InvalidFlowNameSnafu {
136                name: flow_ident.to_string()
137            }
138        );
139
140        Ok(Statement::DropFlow(DropFlow::new(flow_ident, if_exists)))
141    }
142
143    fn parse_drop_table(&mut self) -> Result<Statement> {
144        let _ = self.parser.next_token();
145
146        let if_exists = self.parser.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
147        let mut table_names = Vec::with_capacity(1);
148        loop {
149            let raw_table_ident =
150                self.parse_object_name()
151                    .with_context(|_| error::UnexpectedSnafu {
152                        expected: "a table name",
153                        actual: self.peek_token_as_string(),
154                    })?;
155            let table_ident = Self::canonicalize_object_name(raw_table_ident)?;
156            ensure!(
157                !table_ident.0.is_empty(),
158                InvalidTableNameSnafu {
159                    name: table_ident.to_string()
160                }
161            );
162            table_names.push(table_ident);
163            if !self.parser.consume_token(&Token::Comma) {
164                break;
165            }
166        }
167
168        Ok(Statement::DropTable(DropTable::new(table_names, if_exists)))
169    }
170
171    fn parse_drop_database(&mut self) -> Result<Statement> {
172        let _ = self.parser.next_token();
173
174        let if_exists = self.parser.parse_keywords(&[Keyword::IF, Keyword::EXISTS]);
175        let database_name = self
176            .parse_object_name()
177            .with_context(|_| error::UnexpectedSnafu {
178                expected: "a database name",
179                actual: self.peek_token_as_string(),
180            })?;
181        let database_name = Self::canonicalize_object_name(database_name)?;
182
183        Ok(Statement::DropDatabase(DropDatabase::new(
184            database_name,
185            if_exists,
186        )))
187    }
188}
189
190#[cfg(test)]
191mod tests {
192    use sqlparser::ast::{Ident, ObjectName};
193
194    use super::*;
195    use crate::dialect::GreptimeDbDialect;
196    use crate::parser::ParseOptions;
197    use crate::statements::drop::UndropTable;
198
199    #[test]
200    fn test_undrop_table() {
201        let cases = [
202            ("UNDROP TABLE foo", "foo"),
203            ("undrop table my_schema.FOO", "my_schema.foo"),
204            (
205                "UnDrOp TaBlE my_catalog.my_schema.foo",
206                "my_catalog.my_schema.foo",
207            ),
208            (
209                "UNDROP TABLE `My Catalog`.`My Schema`.`My Table`",
210                "`My Catalog`.`My Schema`.`My Table`",
211            ),
212        ];
213
214        for (sql, expected_name) in cases {
215            let mut stmts = ParserContext::create_with_dialect(
216                sql,
217                &GreptimeDbDialect {},
218                ParseOptions::default(),
219            )
220            .unwrap();
221            let stmt = stmts.pop().unwrap();
222            assert_eq!(
223                stmt,
224                Statement::UndropTable(UndropTable::new(
225                    ParserContext::parse_table_name(expected_name, &GreptimeDbDialect {}).unwrap()
226                ))
227            );
228            assert_eq!(format!("UNDROP TABLE {expected_name}"), stmt.to_string());
229            assert!(!stmt.is_readonly());
230        }
231    }
232
233    #[test]
234    fn test_undrop_table_rejects_unsupported_syntax() {
235        for sql in [
236            "UNDROP",
237            "UNDROP foo",
238            "UNDROP TABLE",
239            "UNDROP TABLE IF EXISTS foo",
240            "UNDROP TABLE foo, bar",
241            "UNDROP TABLE foo bar",
242            "UNDROP TABLE foo RENAME TO bar",
243            "UNDROP TABLE foo AT '2026-01-01'",
244        ] {
245            assert!(
246                ParserContext::create_with_dialect(
247                    sql,
248                    &GreptimeDbDialect {},
249                    ParseOptions::default(),
250                )
251                .is_err(),
252                "unexpectedly parsed: {sql}"
253            );
254        }
255    }
256
257    #[test]
258    pub fn test_drop_table() {
259        let sql = "DROP TABLE foo";
260        let result =
261            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default());
262        let mut stmts = result.unwrap();
263        assert_eq!(
264            stmts.pop().unwrap(),
265            Statement::DropTable(DropTable::new(
266                vec![ObjectName::from(vec![Ident::new("foo")])],
267                false
268            ))
269        );
270
271        let sql = "DROP TABLE IF EXISTS foo";
272        let result =
273            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default());
274        let mut stmts = result.unwrap();
275        assert_eq!(
276            stmts.pop().unwrap(),
277            Statement::DropTable(DropTable::new(
278                vec![ObjectName::from(vec![Ident::new("foo")])],
279                true
280            ))
281        );
282
283        let sql = "DROP TABLE my_schema.foo";
284        let result =
285            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default());
286        let mut stmts = result.unwrap();
287        assert_eq!(
288            stmts.pop().unwrap(),
289            Statement::DropTable(DropTable::new(
290                vec![ObjectName::from(vec![
291                    Ident::new("my_schema"),
292                    Ident::new("foo")
293                ])],
294                false
295            ))
296        );
297
298        let sql = "DROP TABLE my_catalog.my_schema.foo";
299        let result =
300            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default());
301        let mut stmts = result.unwrap();
302        assert_eq!(
303            stmts.pop().unwrap(),
304            Statement::DropTable(DropTable::new(
305                vec![ObjectName::from(vec![
306                    Ident::new("my_catalog"),
307                    Ident::new("my_schema"),
308                    Ident::new("foo")
309                ])],
310                false
311            ))
312        )
313    }
314
315    #[test]
316    pub fn test_drop_database() {
317        let sql = "DROP DATABASE public";
318        let result =
319            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default());
320        let mut stmts = result.unwrap();
321        assert_eq!(
322            stmts.pop().unwrap(),
323            Statement::DropDatabase(DropDatabase::new(
324                ObjectName::from(vec![Ident::new("public")]),
325                false
326            ))
327        );
328
329        let sql = "DROP DATABASE IF EXISTS public";
330        let result =
331            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default());
332        let mut stmts = result.unwrap();
333        assert_eq!(
334            stmts.pop().unwrap(),
335            Statement::DropDatabase(DropDatabase::new(
336                ObjectName::from(vec![Ident::new("public")]),
337                true
338            ))
339        );
340
341        let sql = "DROP DATABASE `fOo`";
342        let result =
343            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default());
344        let mut stmts = result.unwrap();
345        assert_eq!(
346            stmts.pop().unwrap(),
347            Statement::DropDatabase(DropDatabase::new(
348                ObjectName::from(vec![Ident::with_quote('`', "fOo"),]),
349                false
350            ))
351        );
352    }
353
354    #[test]
355    pub fn test_drop_flow() {
356        let sql = "DROP FLOW foo";
357        let result =
358            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default());
359        let mut stmts: Vec<Statement> = result.unwrap();
360        assert_eq!(
361            stmts.pop().unwrap(),
362            Statement::DropFlow(DropFlow::new(
363                ObjectName::from(vec![Ident::new("foo")]),
364                false
365            ))
366        );
367
368        let sql = "DROP FLOW IF EXISTS foo";
369        let result =
370            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default());
371        let mut stmts = result.unwrap();
372        assert_eq!(
373            stmts.pop().unwrap(),
374            Statement::DropFlow(DropFlow::new(
375                ObjectName::from(vec![Ident::new("foo")]),
376                true
377            ))
378        );
379
380        let sql = "DROP FLOW my_schema.foo";
381        let result =
382            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default());
383        let mut stmts = result.unwrap();
384        assert_eq!(
385            stmts.pop().unwrap(),
386            Statement::DropFlow(DropFlow::new(
387                ObjectName::from(vec![Ident::new("my_schema"), Ident::new("foo")]),
388                false
389            ))
390        );
391
392        let sql = "DROP FLOW my_catalog.my_schema.foo";
393        let result =
394            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default());
395        let mut stmts = result.unwrap();
396        assert_eq!(
397            stmts.pop().unwrap(),
398            Statement::DropFlow(DropFlow::new(
399                ObjectName::from(vec![
400                    Ident::new("my_catalog"),
401                    Ident::new("my_schema"),
402                    Ident::new("foo")
403                ]),
404                false
405            ))
406        )
407    }
408
409    #[test]
410    pub fn test_drop_view() {
411        let sql = "DROP VIEW foo";
412        let result =
413            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default());
414        let mut stmts: Vec<Statement> = result.unwrap();
415        let stmt = stmts.pop().unwrap();
416        assert_eq!(
417            stmt,
418            Statement::DropView(DropView {
419                view_name: ObjectName::from(vec![Ident::new("foo")]),
420                drop_if_exists: false,
421            })
422        );
423        assert_eq!(sql, stmt.to_string());
424
425        let sql = "DROP VIEW greptime.public.foo";
426        let result =
427            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default());
428        let mut stmts: Vec<Statement> = result.unwrap();
429        let stmt = stmts.pop().unwrap();
430        assert_eq!(
431            stmt,
432            Statement::DropView(DropView {
433                view_name: ObjectName::from(vec![
434                    Ident::new("greptime"),
435                    Ident::new("public"),
436                    Ident::new("foo")
437                ]),
438                drop_if_exists: false,
439            })
440        );
441        assert_eq!(sql, stmt.to_string());
442
443        let sql = "DROP VIEW IF EXISTS foo";
444        let result =
445            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default());
446        let mut stmts: Vec<Statement> = result.unwrap();
447        let stmt = stmts.pop().unwrap();
448        assert_eq!(
449            stmt,
450            Statement::DropView(DropView {
451                view_name: ObjectName::from(vec![Ident::new("foo")]),
452                drop_if_exists: true,
453            })
454        );
455        assert_eq!(sql, stmt.to_string());
456    }
457}