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
22/// Normalizes an identifier using ASCII-only case folding when unquoted,
23/// preserving exact casing for quoted identifiers (matching DataFusion's
24/// `IdentNormalizer` with `enable_ident_normalization = true`).
25pub fn normalize_ident(ident: &Ident) -> String {
26    if ident.quote_style.is_some() {
27        ident.value.clone()
28    } else {
29        ident.value.to_ascii_lowercase()
30    }
31}
32
33pub trait ObjectNamePartExt {
34    fn to_string_unquoted(&self) -> String;
35
36    /// Returns the identifier string normalized with ASCII-only lowercase when
37    /// unquoted, preserving original casing for quoted identifiers (matching
38    /// DataFusion's SQL planner with `enable_ident_normalization = true`).
39    fn to_string_normalized(&self) -> String;
40}
41
42impl ObjectNamePartExt for ObjectNamePart {
43    fn to_string_unquoted(&self) -> String {
44        let ObjectNamePart::Identifier(ident) = self else {
45            // If it's not an ident, just return it as a string.
46            return self.to_string();
47        };
48        ident.value.clone()
49    }
50
51    fn to_string_normalized(&self) -> String {
52        let ObjectNamePart::Identifier(ident) = self else {
53            return self.to_string();
54        };
55        normalize_ident(ident)
56    }
57}
58
59/// Formats an object name by joining its identifier values without quotes.
60pub fn object_name_to_string_unquoted(name: &ObjectName) -> String {
61    name.0
62        .iter()
63        .map(ObjectNamePartExt::to_string_unquoted)
64        .collect::<Vec<_>>()
65        .join(".")
66}
67
68#[cfg(test)]
69mod tests {
70    use sqlparser::ast::{Ident, ObjectName, ObjectNamePart};
71
72    use super::{ObjectNamePartExt, object_name_to_string_unquoted};
73
74    #[test]
75    fn test_object_name_to_string_unquoted() {
76        let quoted = ObjectName(vec![ObjectNamePart::Identifier(Ident::with_quote(
77            '"',
78            "query.parallelism",
79        ))]);
80        let unquoted = ObjectName(vec![
81            ObjectNamePart::Identifier(Ident::new("query")),
82            ObjectNamePart::Identifier(Ident::new("parallelism")),
83        ]);
84
85        assert_eq!("query.parallelism", object_name_to_string_unquoted(&quoted));
86        assert_eq!(
87            object_name_to_string_unquoted(&unquoted),
88            object_name_to_string_unquoted(&quoted)
89        );
90    }
91
92    #[test]
93    fn test_object_name_part_to_string_normalized() {
94        let unquoted = ObjectNamePart::Identifier(Ident::new("Readings"));
95        let double_quoted = ObjectNamePart::Identifier(Ident::with_quote('"', "Readings"));
96        let backtick_quoted = ObjectNamePart::Identifier(Ident::with_quote('`', "Readings"));
97        let kelvin_unquoted = ObjectNamePart::Identifier(Ident::new("\u{212A}PI"));
98        let kelvin_quoted = ObjectNamePart::Identifier(Ident::with_quote('"', "\u{212A}PI"));
99
100        assert_eq!("readings", unquoted.to_string_normalized());
101        assert_eq!("Readings", double_quoted.to_string_normalized());
102        assert_eq!("Readings", backtick_quoted.to_string_normalized());
103        assert_eq!("\u{212A}pi", kelvin_unquoted.to_string_normalized());
104        assert_eq!("\u{212A}PI", kelvin_quoted.to_string_normalized());
105    }
106}