sql/parsers/
describe_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::{ensure, ResultExt};
16use sqlparser::keywords::Keyword;
17
18use crate::error::{self, InvalidTableNameSnafu, Result};
19use crate::parser::ParserContext;
20use crate::statements::describe::DescribeTable;
21use crate::statements::statement::Statement;
22
23/// DESCRIBE statement parser implementation
24impl ParserContext<'_> {
25    pub(crate) fn parse_describe(&mut self) -> Result<Statement> {
26        if self.matches_keyword(Keyword::TABLE) {
27            let _ = self.parser.next_token();
28        }
29        self.parse_describe_table()
30    }
31
32    fn parse_describe_table(&mut self) -> Result<Statement> {
33        let raw_table_idents =
34            self.parse_object_name()
35                .with_context(|_| error::UnexpectedSnafu {
36                    expected: "a table name",
37                    actual: self.peek_token_as_string(),
38                })?;
39        let table_idents = Self::canonicalize_object_name(raw_table_idents);
40        ensure!(
41            !table_idents.0.is_empty(),
42            InvalidTableNameSnafu {
43                name: table_idents.to_string(),
44            }
45        );
46        Ok(Statement::DescribeTable(DescribeTable::new(table_idents)))
47    }
48}
49
50#[cfg(test)]
51mod tests {
52    use sqlparser::ast::Expr;
53
54    use super::*;
55    use crate::dialect::GreptimeDbDialect;
56    use crate::parser::ParseOptions;
57
58    #[test]
59    fn test_parse_function() {
60        let expr =
61            ParserContext::parse_function("current_timestamp()", &GreptimeDbDialect {}).unwrap();
62        assert!(matches!(expr, Expr::Function(_)));
63    }
64
65    fn assert_describe_table(sql: &str) {
66        let stmt =
67            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
68                .unwrap()
69                .pop()
70                .unwrap();
71        assert!(matches!(stmt, Statement::DescribeTable(_)))
72    }
73
74    #[test]
75    fn test_parse_describe_table() {
76        assert_describe_table("desc table t;");
77        assert_describe_table("describe table t;");
78        assert_describe_table("desc t;");
79        assert_describe_table("describe t;");
80    }
81}