Skip to main content

sqlparser/dialect/
mysql.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18#[cfg(not(feature = "std"))]
19use alloc::boxed::Box;
20
21use crate::{
22    ast::{BinaryOperator, Expr, LockTable, LockTableType, Statement},
23    dialect::Dialect,
24    keywords::Keyword,
25    parser::{Parser, ParserError},
26};
27
28use super::keywords;
29
30const RESERVED_FOR_TABLE_ALIAS_MYSQL: &[Keyword] = &[
31    Keyword::USE,
32    Keyword::IGNORE,
33    Keyword::FORCE,
34    Keyword::STRAIGHT_JOIN,
35];
36
37/// A [`Dialect`] for [MySQL](https://www.mysql.com/)
38#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
39#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
40pub struct MySqlDialect {}
41
42impl Dialect for MySqlDialect {
43    fn is_identifier_start(&self, ch: char) -> bool {
44        // See https://dev.mysql.com/doc/refman/8.0/en/identifiers.html.
45        // Identifiers which begin with a digit are recognized while tokenizing numbers,
46        // so they can be distinguished from exponent numeric literals.
47        // MySQL also implements non ascii utf-8 charecters
48        ch.is_alphabetic()
49            || ch == '_'
50            || ch == '$'
51            || ch == '@'
52            || ('\u{0080}'..='\u{ffff}').contains(&ch)
53            || !ch.is_ascii()
54    }
55
56    fn is_identifier_part(&self, ch: char) -> bool {
57        self.is_identifier_start(ch) || ch.is_ascii_digit() ||
58        // MySQL implements Unicode characters in identifiers.
59        !ch.is_ascii()
60    }
61
62    fn is_delimited_identifier_start(&self, ch: char) -> bool {
63        ch == '`'
64    }
65
66    fn identifier_quote_style(&self, _identifier: &str) -> Option<char> {
67        Some('`')
68    }
69
70    // See https://dev.mysql.com/doc/refman/8.0/en/string-literals.html#character-escape-sequences
71    fn supports_string_literal_backslash_escape(&self) -> bool {
72        true
73    }
74
75    /// see <https://dev.mysql.com/doc/refman/8.4/en/string-functions.html#function_concat>
76    fn supports_string_literal_concatenation(&self) -> bool {
77        true
78    }
79
80    fn ignores_wildcard_escapes(&self) -> bool {
81        true
82    }
83
84    fn supports_numeric_prefix(&self) -> bool {
85        true
86    }
87
88    fn supports_bitwise_shift_operators(&self) -> bool {
89        true
90    }
91
92    /// see <https://dev.mysql.com/doc/refman/8.4/en/comments.html>
93    fn supports_multiline_comment_hints(&self) -> bool {
94        true
95    }
96
97    fn parse_infix(
98        &self,
99        parser: &mut crate::parser::Parser,
100        expr: &crate::ast::Expr,
101        _precedence: u8,
102    ) -> Option<Result<crate::ast::Expr, ParserError>> {
103        // Parse DIV as an operator
104        if parser.parse_keyword(Keyword::DIV) {
105            let left = Box::new(expr.clone());
106            let right = Box::new(match parser.parse_expr() {
107                Ok(expr) => expr,
108                Err(e) => return Some(Err(e)),
109            });
110            Some(Ok(Expr::BinaryOp {
111                left,
112                op: BinaryOperator::MyIntegerDivide,
113                right,
114            }))
115        } else {
116            None
117        }
118    }
119
120    fn parse_statement(&self, parser: &mut Parser) -> Option<Result<Statement, ParserError>> {
121        if parser.parse_keywords(&[Keyword::LOCK, Keyword::TABLES]) {
122            Some(parse_lock_tables(parser))
123        } else if parser.parse_keywords(&[Keyword::UNLOCK, Keyword::TABLES]) {
124            Some(parse_unlock_tables(parser))
125        } else {
126            None
127        }
128    }
129
130    fn require_interval_qualifier(&self) -> bool {
131        true
132    }
133
134    fn supports_limit_comma(&self) -> bool {
135        true
136    }
137
138    /// See: <https://dev.mysql.com/doc/refman/8.4/en/create-table-select.html>
139    fn supports_create_table_select(&self) -> bool {
140        true
141    }
142
143    /// See: <https://dev.mysql.com/doc/refman/8.4/en/insert.html>
144    fn supports_insert_set(&self) -> bool {
145        true
146    }
147
148    fn supports_user_host_grantee(&self) -> bool {
149        true
150    }
151
152    fn is_table_factor_alias(&self, explicit: bool, kw: &Keyword, _parser: &mut Parser) -> bool {
153        explicit
154            || (!keywords::RESERVED_FOR_TABLE_ALIAS.contains(kw)
155                && !RESERVED_FOR_TABLE_ALIAS_MYSQL.contains(kw))
156    }
157
158    fn supports_table_hints(&self) -> bool {
159        true
160    }
161
162    fn requires_single_line_comment_whitespace(&self) -> bool {
163        true
164    }
165
166    fn supports_match_against(&self) -> bool {
167        true
168    }
169
170    fn supports_select_modifiers(&self) -> bool {
171        true
172    }
173
174    fn supports_set_names(&self) -> bool {
175        true
176    }
177
178    fn supports_comma_separated_set_assignments(&self) -> bool {
179        true
180    }
181
182    /// See: <https://dev.mysql.com/doc/refman/8.4/en/update.html>
183    fn supports_update_order_by(&self) -> bool {
184        true
185    }
186
187    fn supports_data_type_signed_suffix(&self) -> bool {
188        true
189    }
190
191    fn supports_cross_join_constraint(&self) -> bool {
192        true
193    }
194
195    /// See: <https://dev.mysql.com/doc/refman/8.4/en/expressions.html>
196    fn supports_double_ampersand_operator(&self) -> bool {
197        true
198    }
199
200    /// Deprecated functionality by MySQL but still supported
201    /// See: <https://dev.mysql.com/doc/refman/8.4/en/cast-functions.html#operator_binary>
202    fn supports_binary_kw_as_cast(&self) -> bool {
203        true
204    }
205
206    fn supports_comment_optimizer_hint(&self) -> bool {
207        true
208    }
209
210    /// See: <https://dev.mysql.com/doc/refman/8.4/en/create-table.html>
211    fn supports_constraint_keyword_without_name(&self) -> bool {
212        true
213    }
214
215    /// See: <https://dev.mysql.com/doc/refman/8.4/en/create-table.html>
216    fn supports_key_column_option(&self) -> bool {
217        true
218    }
219}
220
221/// `LOCK TABLES`
222/// <https://dev.mysql.com/doc/refman/8.0/en/lock-tables.html>
223fn parse_lock_tables(parser: &mut Parser) -> Result<Statement, ParserError> {
224    let tables = parser.parse_comma_separated(parse_lock_table)?;
225    Ok(Statement::LockTables { tables })
226}
227
228// tbl_name [[AS] alias] lock_type
229fn parse_lock_table(parser: &mut Parser) -> Result<LockTable, ParserError> {
230    let table = parser.parse_identifier()?;
231    let alias =
232        parser.parse_optional_alias(&[Keyword::READ, Keyword::WRITE, Keyword::LOW_PRIORITY])?;
233    let lock_type = parse_lock_tables_type(parser)?;
234
235    Ok(LockTable {
236        table,
237        alias,
238        lock_type,
239    })
240}
241
242// READ [LOCAL] | [LOW_PRIORITY] WRITE
243fn parse_lock_tables_type(parser: &mut Parser) -> Result<LockTableType, ParserError> {
244    if parser.parse_keyword(Keyword::READ) {
245        if parser.parse_keyword(Keyword::LOCAL) {
246            Ok(LockTableType::Read { local: true })
247        } else {
248            Ok(LockTableType::Read { local: false })
249        }
250    } else if parser.parse_keyword(Keyword::WRITE) {
251        Ok(LockTableType::Write {
252            low_priority: false,
253        })
254    } else if parser.parse_keywords(&[Keyword::LOW_PRIORITY, Keyword::WRITE]) {
255        Ok(LockTableType::Write { low_priority: true })
256    } else {
257        parser.expected_ref("an lock type in LOCK TABLES", parser.peek_token_ref())
258    }
259}
260
261/// UNLOCK TABLES
262/// <https://dev.mysql.com/doc/refman/8.0/en/lock-tables.html>
263fn parse_unlock_tables(_parser: &mut Parser) -> Result<Statement, ParserError> {
264    Ok(Statement::UnlockTables)
265}