Skip to main content

sql/
ast.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
15pub use sqlparser::ast::{
16    BinaryOperator, ColumnDef, ColumnOption, ColumnOptionDef, DataType, Expr, Function,
17    FunctionArg, FunctionArgExpr, FunctionArguments, Ident, ObjectName, ObjectNamePart, SqlOption,
18    TableConstraint, TimezoneInfo, Value, ValueWithSpan, Visit, VisitMut, Visitor, VisitorMut,
19    visit_expressions_mut, visit_statements_mut,
20};
21
22pub trait ObjectNamePartExt {
23    fn to_string_unquoted(&self) -> String;
24}
25
26impl ObjectNamePartExt for ObjectNamePart {
27    fn to_string_unquoted(&self) -> String {
28        let ObjectNamePart::Identifier(ident) = self else {
29            // If it's not an ident, just return it as a string.
30            return self.to_string();
31        };
32        ident.value.clone()
33    }
34}
35
36/// Formats an object name by joining its identifier values without quotes.
37pub fn object_name_to_string_unquoted(name: &ObjectName) -> String {
38    name.0
39        .iter()
40        .map(ObjectNamePartExt::to_string_unquoted)
41        .collect::<Vec<_>>()
42        .join(".")
43}
44
45#[cfg(test)]
46mod tests {
47    use sqlparser::ast::{Ident, ObjectName, ObjectNamePart};
48
49    use super::object_name_to_string_unquoted;
50
51    #[test]
52    fn test_object_name_to_string_unquoted() {
53        let quoted = ObjectName(vec![ObjectNamePart::Identifier(Ident::with_quote(
54            '"',
55            "query.parallelism",
56        ))]);
57        let unquoted = ObjectName(vec![
58            ObjectNamePart::Identifier(Ident::new("query")),
59            ObjectNamePart::Identifier(Ident::new("parallelism")),
60        ]);
61
62        assert_eq!("query.parallelism", object_name_to_string_unquoted(&quoted));
63        assert_eq!(
64            object_name_to_string_unquoted(&unquoted),
65            object_name_to_string_unquoted(&quoted)
66        );
67    }
68}