sql/parsers/
query_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::prelude::*;
16
17use crate::error::{self, Result};
18use crate::parser::ParserContext;
19use crate::statements::query::Query;
20use crate::statements::statement::Statement;
21
22impl ParserContext<'_> {
23    /// Parses select and it's variants.
24    pub(crate) fn parse_query(&mut self) -> Result<Statement> {
25        let spquery = self.parser.parse_query().context(error::SyntaxSnafu)?;
26
27        Ok(Statement::Query(Box::new(Query::try_from(*spquery)?)))
28    }
29}
30
31#[cfg(test)]
32mod tests {
33    use common_error::ext::ErrorExt;
34
35    use crate::dialect::GreptimeDbDialect;
36    use crate::parser::{ParseOptions, ParserContext};
37
38    #[test]
39    pub fn test_parse_query() {
40        let sql = "SELECT a, b, 123, myfunc(b) \
41           FROM table_1 \
42           WHERE a > b AND b < 100 \
43           ORDER BY a DESC, b";
44
45        let _ =
46            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default())
47                .unwrap();
48    }
49
50    #[test]
51    pub fn test_parse_invalid_query() {
52        let sql = "SELECT * FROM table_1 WHERE";
53        let result =
54            ParserContext::create_with_dialect(sql, &GreptimeDbDialect {}, ParseOptions::default());
55        assert!(result.is_err());
56        assert!(result
57            .unwrap_err()
58            .output_msg()
59            .contains("Expected: an expression"));
60    }
61}