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_always_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 // This refers to the PostgreSQL notion of "reserved" keywords,
75 // which generally refers to built in tables, functions, and
76 // constructs that cannot be used as identifiers without quoting.
77 // See https://www.postgresql.org/docs/current/sql-keywords-appendix.html
78 // for more details.
79 pub fn is_reserved_in_scalar_expression(self) -> bool {
80 matches!(self, CASE) || self.is_always_reserved()
81 }
82
83 /// Reports whether this keyword requires quoting when used as a table
84 /// alias.
85 ///
86 /// Note that this rule is only applies when the table alias is "bare";
87 /// i.e., when the table alias is not preceded by `AS`.
88 ///
89 /// Ensures that `FROM <table_name> <table_alias>` can be parsed
90 /// unambiguously.
91 pub fn is_reserved_in_table_alias(self) -> bool {
92 matches!(
93 self,
94 // These keywords are ambiguous when used as a table alias, as they
95 // conflict with the syntax for joins.
96 ON | JOIN | INNER | CROSS | FULL | LEFT | RIGHT | NATURAL | USING |
97 // Needed for UPDATE.
98 SET |
99 // `OUTER` is not strictly ambiguous, but it prevents `a OUTER JOIN
100 // b` from parsing as `a AS outer JOIN b`, instead producing a nice
101 // syntax error.
102 OUTER
103 ) || self.is_always_reserved()
104 }
105
106 /// Reports whether this keyword requires quoting when used as a column
107 /// alias.
108 ///
109 ///
110 /// Note that this rule is only applies when the column alias is "bare";
111 /// i.e., when the column alias is not preceded by `AS`.
112 ///
113 /// Ensures that `SELECT <column_name> <column_alias>` can be parsed
114 /// unambiguously.
115 pub fn is_reserved_in_column_alias(self) -> bool {
116 matches!(
117 self,
118 // These timelike keywords conflict with interval timeframe
119 // suffixes. They are not strictly ambiguous, but marking them
120 // reserved prevents e.g. `SELECT pg_catalog.interval '1' year` from
121 // parsing as `SELECT pg_catalog.interval '1' AS YEAR`.
122 YEAR | MONTH | DAY | HOUR | MINUTE | SECOND
123 ) || self.is_always_reserved()
124 }
125
126 /// Reports whether a keyword is considered reserved in any context:
127 /// either in table aliases, column aliases, or in all contexts.
128 pub fn is_sometimes_reserved(self) -> bool {
129 self.is_always_reserved()
130 || self.is_reserved_in_table_alias()
131 || self.is_reserved_in_column_alias()
132 || self.is_reserved_in_scalar_expression()
133 }
134}
135
136impl FromStr for Keyword {
137 type Err = ();
138
139 fn from_str(s: &str) -> Result<Keyword, ()> {
140 match KEYWORDS.get(UncasedStr::new(s)) {
141 Some(kw) => Ok(*kw),
142 None => Err(()),
143 }
144 }
145}
146
147impl fmt::Display for Keyword {
148 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
149 f.write_str(self.as_str())
150 }
151}