sql/statements/
query.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 std::fmt;
16
17use serde::Serialize;
18use sqlparser::ast::Query as SpQuery;
19use sqlparser_derive::{Visit, VisitMut};
20
21use crate::error::Error;
22
23/// Query statement instance.
24#[derive(Debug, Clone, PartialEq, Eq, Visit, VisitMut, Serialize)]
25pub struct Query {
26    pub inner: SpQuery,
27}
28
29/// Automatically converts from sqlparser Query instance to SqlQuery.
30impl TryFrom<SpQuery> for Query {
31    type Error = Error;
32
33    fn try_from(q: SpQuery) -> Result<Self, Self::Error> {
34        Ok(Query { inner: q })
35    }
36}
37
38impl TryFrom<Query> for SpQuery {
39    type Error = Error;
40
41    fn try_from(value: Query) -> Result<Self, Self::Error> {
42        Ok(value.inner)
43    }
44}
45
46impl fmt::Display for Query {
47    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48        write!(f, "{}", self.inner)?;
49        Ok(())
50    }
51}
52
53#[cfg(test)]
54mod test {
55
56    use super::Query;
57    use crate::dialect::GreptimeDbDialect;
58    use crate::parser::{ParseOptions, ParserContext};
59    use crate::statements::statement::Statement;
60
61    fn create_query(sql: &str) -> Option<Box<Query>> {
62        match ParserContext::create_with_dialect(
63            sql,
64            &GreptimeDbDialect {},
65            ParseOptions::default(),
66        )
67        .unwrap()
68        .remove(0)
69        {
70            Statement::Query(query) => Some(query),
71            _ => None,
72        }
73    }
74
75    #[test]
76    fn test_query_display() {
77        assert_eq!(
78            create_query("select * from abc where x = 1 and y = 7")
79                .unwrap()
80                .to_string(),
81            "SELECT * FROM abc WHERE x = 1 AND y = 7"
82        );
83        assert_eq!(
84            create_query(
85                "select * from abc left join bcd where abc.a = 1 and bcd.d = 7 and abc.id = bcd.id"
86            )
87            .unwrap()
88            .to_string(),
89            "SELECT * FROM abc LEFT JOIN bcd WHERE abc.a = 1 AND bcd.d = 7 AND abc.id = bcd.id"
90        );
91    }
92}