mz_sql_lexer/
keywords.rs

1// Copyright 2018 sqlparser-rs contributors. All rights reserved.
2// Copyright Materialize, Inc. and contributors. All rights reserved.
3//
4// This file is derived from the sqlparser-rs project, available at
5// https://github.com/andygrove/sqlparser-rs. It was incorporated
6// directly into Materialize on December 21, 2019.
7//
8// Licensed under the Apache License, Version 2.0 (the "License");
9// you may not use this file except in compliance with the License.
10// You may obtain a copy of the License in the LICENSE file at the
11// root of this repository, or online at
12//
13//     http://www.apache.org/licenses/LICENSE-2.0
14//
15// Unless required by applicable law or agreed to in writing, software
16// distributed under the License is distributed on an "AS IS" BASIS,
17// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18// See the License for the specific language governing permissions and
19// limitations under the License.
20
21use std::fmt;
22use std::str::FromStr;
23
24use uncased::UncasedStr;
25
26// The `Keyword` type and the keyword constants are automatically generated from
27// the list in keywords.txt by the crate's build script.
28//
29// We go to the trouble of code generation primarily to create a "perfect hash
30// function" at compile time via the phf crate, which enables very fast,
31// case-insensitive keyword parsing. From there it's easy to generate a few
32// more convenience functions and accessors.
33//
34// If the only keywords were `Insert` and `Select`, we'd generate the following
35// code:
36//
37//     pub enum Keyword {
38//         Insert,
39//         Select,
40//     }
41//
42//     pub const INSERT: Keyword = Keyword::Insert;
43//     pub const SELECT: Keyword = Keyword::Select;
44//
45//     impl Keyword {
46//         pub fn as_str(&self) -> &'static str {
47//             match self {
48//                 Keyword::Insert => "INSERT",
49//                 Keyword::Select => "SELECT",
50//             }
51//         }
52//     }
53//
54//     static KEYWORDS: phf::Map<&'static UncasedStr, Keyword> = { /* ... */ };
55//
56include!(concat!(env!("OUT_DIR"), "/keywords.rs"));
57
58impl Keyword {
59    /// Reports whether this keyword requires quoting when used as an
60    /// identifier in any context.
61    ///
62    /// The only exception to the rule is when the keyword follows `AS` in a
63    /// column or table alias.
64    pub fn is_reserved(self) -> bool {
65        matches!(
66            self,
67            // Keywords that can appear at the top-level of a SELECT statement.
68            WITH | SELECT | FROM | WHERE | GROUP | HAVING | QUALIFY | WINDOW | ORDER | LIMIT | OFFSET | FETCH | OPTIONS | RETURNING |
69            // Set operations.
70            UNION | EXCEPT | INTERSECT
71        )
72    }
73
74    /// Reports whether this keyword requires quoting when used as a table
75    /// alias.
76    ///
77    /// Note that this rule is only applies when the table alias is "bare";
78    /// i.e., when the table alias is not preceded by `AS`.
79    ///
80    /// Ensures that `FROM <table_name> <table_alias>` can be parsed
81    /// unambiguously.
82    pub fn is_reserved_in_table_alias(self) -> bool {
83        matches!(
84            self,
85            // These keywords are ambiguous when used as a table alias, as they
86            // conflict with the syntax for joins.
87            ON | JOIN | INNER | CROSS | FULL | LEFT | RIGHT | NATURAL | USING |
88            // Needed for UPDATE.
89            SET |
90            // `OUTER` is not strictly ambiguous, but it prevents `a OUTER JOIN
91            // b` from parsing as `a AS outer JOIN b`, instead producing a nice
92            // syntax error.
93            OUTER
94        ) || self.is_reserved()
95    }
96
97    /// Reports whether this keyword requires quoting when used as a column
98    /// alias.
99    ///
100    ///
101    /// Note that this rule is only applies when the column alias is "bare";
102    /// i.e., when the column alias is not preceded by `AS`.
103    ///
104    /// Ensures that `SELECT <column_name> <column_alias>` can be parsed
105    /// unambiguously.
106    pub fn is_reserved_in_column_alias(self) -> bool {
107        matches!(
108            self,
109            // These timelike keywords conflict with interval timeframe
110            // suffixes. They are not strictly ambiguous, but marking them
111            // reserved prevents e.g. `SELECT pg_catalog.interval '1' year` from
112            // parsing as `SELECT pg_catalog.interval '1' AS YEAR`.
113            YEAR | MONTH | DAY | HOUR | MINUTE | SECOND
114        ) || self.is_reserved()
115    }
116
117    /// Reports whether a keyword is considered reserved in any context:
118    /// either in table aliases, column aliases, or in all contexts.
119    pub fn is_sometimes_reserved(self) -> bool {
120        self.is_reserved()
121            || self.is_reserved_in_table_alias()
122            || self.is_reserved_in_column_alias()
123    }
124}
125
126impl FromStr for Keyword {
127    type Err = ();
128
129    fn from_str(s: &str) -> Result<Keyword, ()> {
130        match KEYWORDS.get(UncasedStr::new(s)) {
131            Some(kw) => Ok(*kw),
132            None => Err(()),
133        }
134    }
135}
136
137impl fmt::Display for Keyword {
138    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
139        f.write_str(self.as_str())
140    }
141}