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
18use crate::{
19    ast::{Expr, LockTable, LockTableType, Statement},
20    dialect::{BindPlaceholderStyle, Dialect, Precedence},
21    keywords::Keyword,
22    parser::{Parser, ParserError},
23    tokenizer::Token,
24};
25
26use super::keywords;
27
28const RESERVED_FOR_TABLE_ALIAS_MYSQL: &[Keyword] = &[
29    Keyword::USE,
30    Keyword::IGNORE,
31    Keyword::FORCE,
32    Keyword::STRAIGHT_JOIN,
33];
34
35/// A [`Dialect`] for [MySQL](https://www.mysql.com/)
36#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
37#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
38pub struct MySqlDialect {}
39
40impl Dialect for MySqlDialect {
41    /// Only select-list aliases may use string quoting, see
42    /// <https://dev.mysql.com/doc/refman/8.4/en/problems-with-alias.html>
43    fn supports_string_literal_table_alias(&self, _explicit: bool) -> bool {
44        false
45    }
46
47    fn is_identifier_start(&self, ch: char) -> bool {
48        // See https://dev.mysql.com/doc/refman/8.0/en/identifiers.html.
49        // Identifiers which begin with a digit are recognized while tokenizing numbers,
50        // so they can be distinguished from exponent numeric literals.
51        // MySQL also implements non ascii utf-8 charecters
52        ch.is_alphabetic()
53            || ch == '_'
54            || ch == '$'
55            || ch == '@'
56            || ('\u{0080}'..='\u{ffff}').contains(&ch)
57            || !ch.is_ascii()
58    }
59
60    fn is_identifier_part(&self, ch: char) -> bool {
61        self.is_identifier_start(ch) || ch.is_ascii_digit() ||
62        // MySQL implements Unicode characters in identifiers.
63        !ch.is_ascii()
64    }
65
66    fn is_delimited_identifier_start(&self, ch: char) -> bool {
67        ch == '`'
68    }
69
70    fn identifier_quote_style(&self, _identifier: &str) -> Option<char> {
71        Some('`')
72    }
73
74    fn ordered_bind_placeholder_style(&self) -> Option<BindPlaceholderStyle> {
75        Some(BindPlaceholderStyle::QuestionMark)
76    }
77
78    // See https://dev.mysql.com/doc/refman/8.0/en/string-literals.html#character-escape-sequences
79    fn supports_string_literal_backslash_escape(&self) -> bool {
80        true
81    }
82
83    /// see <https://dev.mysql.com/doc/refman/8.4/en/string-functions.html#function_concat>
84    fn supports_string_literal_concatenation(&self) -> bool {
85        true
86    }
87
88    fn ignores_wildcard_escapes(&self) -> bool {
89        true
90    }
91
92    fn supports_numeric_prefix(&self) -> bool {
93        true
94    }
95
96    fn supports_literal_prefix_in_qualified_name(&self) -> bool {
97        true
98    }
99
100    fn supports_bitwise_shift_operators(&self) -> bool {
101        true
102    }
103
104    fn supports_singular_value_keyword(&self) -> bool {
105        true
106    }
107
108    /// see <https://dev.mysql.com/doc/refman/8.4/en/comments.html>
109    fn supports_multiline_comment_hints(&self) -> bool {
110        true
111    }
112
113    fn parse_infix(
114        &self,
115        parser: &mut Parser,
116        expr: &Expr,
117        precedence: u8,
118    ) -> Option<Result<Expr, ParserError>> {
119        super::parse_div_infix(parser, expr, precedence)
120    }
121
122    fn parse_statement(&self, parser: &mut Parser) -> Option<Result<Statement, ParserError>> {
123        if parser.parse_keywords(&[Keyword::LOCK, Keyword::TABLES]) {
124            Some(parse_lock_tables(parser))
125        } else if parser.parse_keywords(&[Keyword::UNLOCK, Keyword::TABLES]) {
126            Some(parse_unlock_tables(parser))
127        } else {
128            None
129        }
130    }
131
132    fn require_interval_qualifier(&self) -> bool {
133        true
134    }
135
136    fn supports_limit_comma(&self) -> bool {
137        true
138    }
139
140    /// See: <https://dev.mysql.com/doc/refman/8.4/en/create-table-select.html>
141    fn supports_create_table_select(&self) -> bool {
142        true
143    }
144
145    /// See: <https://dev.mysql.com/doc/refman/8.4/en/insert.html>
146    fn supports_insert_set(&self) -> bool {
147        true
148    }
149
150    fn supports_user_host_grantee(&self) -> bool {
151        true
152    }
153
154    fn is_table_factor_alias(&self, explicit: bool, kw: &Keyword, _parser: &mut Parser) -> bool {
155        explicit
156            || (!keywords::RESERVED_FOR_TABLE_ALIAS.contains(kw)
157                && !RESERVED_FOR_TABLE_ALIAS_MYSQL.contains(kw))
158    }
159
160    fn supports_table_hints(&self) -> bool {
161        true
162    }
163
164    fn requires_single_line_comment_whitespace(&self) -> bool {
165        true
166    }
167
168    fn supports_hash_comment(&self) -> bool {
169        true
170    }
171
172    fn supports_match_against(&self) -> bool {
173        true
174    }
175
176    fn supports_select_modifiers(&self) -> bool {
177        true
178    }
179
180    fn supports_set_names(&self) -> bool {
181        true
182    }
183
184    fn supports_comma_separated_set_assignments(&self) -> bool {
185        true
186    }
187
188    /// See: <https://dev.mysql.com/doc/refman/8.4/en/alter-table.html>
189    fn supports_alter_column_position(&self) -> bool {
190        true
191    }
192
193    /// See: <https://dev.mysql.com/doc/refman/8.4/en/update.html>
194    fn supports_update_order_by(&self) -> bool {
195        true
196    }
197
198    fn supports_data_type_signed_suffix(&self) -> bool {
199        true
200    }
201
202    fn supports_data_type_zerofill_suffix(&self) -> bool {
203        true
204    }
205
206    fn supports_cross_join_constraint(&self) -> bool {
207        true
208    }
209
210    /// See: <https://dev.mysql.com/doc/refman/8.4/en/expressions.html>
211    fn supports_double_ampersand_operator(&self) -> bool {
212        true
213    }
214
215    /// `&&` binds like `AND`.
216    /// See: <https://dev.mysql.com/doc/refman/8.4/en/operator-precedence.html>
217    fn get_next_precedence(&self, parser: &Parser) -> Option<Result<u8, ParserError>> {
218        match parser.peek_token_ref().token {
219            Token::Overlap => Some(Ok(self.prec_value(Precedence::And))),
220            _ => None,
221        }
222    }
223
224    /// Deprecated functionality by MySQL but still supported
225    /// See: <https://dev.mysql.com/doc/refman/8.4/en/cast-functions.html#operator_binary>
226    fn supports_binary_kw_as_cast(&self) -> bool {
227        true
228    }
229
230    /// See: <https://dev.mysql.com/doc/refman/8.4/en/partitioning-selection.html>
231    fn supports_table_partitions(&self) -> bool {
232        true
233    }
234
235    fn supports_comment_optimizer_hint(&self) -> bool {
236        true
237    }
238
239    /// See: <https://dev.mysql.com/doc/refman/8.4/en/create-table.html>
240    fn supports_constraint_keyword_without_name(&self) -> bool {
241        true
242    }
243
244    /// See: <https://dev.mysql.com/doc/refman/8.4/en/create-table.html>
245    fn supports_key_column_option(&self) -> bool {
246        true
247    }
248
249    /// See: <https://dev.mysql.com/doc/refman/9.7/en/group-by-modifiers.html>
250    fn supports_group_by_with_modifier(&self) -> bool {
251        true
252    }
253
254    fn supports_left_associative_joins_without_parens(&self) -> bool {
255        false
256    }
257}
258
259/// `LOCK TABLES`
260/// <https://dev.mysql.com/doc/refman/8.0/en/lock-tables.html>
261fn parse_lock_tables(parser: &mut Parser) -> Result<Statement, ParserError> {
262    let tables = parser.parse_comma_separated(parse_lock_table)?;
263    Ok(Statement::LockTables { tables })
264}
265
266// tbl_name [[AS] alias] lock_type
267fn parse_lock_table(parser: &mut Parser) -> Result<LockTable, ParserError> {
268    let table = parser.parse_identifier()?;
269    let alias =
270        parser.parse_optional_alias(&[Keyword::READ, Keyword::WRITE, Keyword::LOW_PRIORITY])?;
271    let lock_type = parse_lock_tables_type(parser)?;
272
273    Ok(LockTable {
274        table,
275        alias,
276        lock_type,
277    })
278}
279
280// READ [LOCAL] | [LOW_PRIORITY] WRITE
281fn parse_lock_tables_type(parser: &mut Parser) -> Result<LockTableType, ParserError> {
282    if parser.parse_keyword(Keyword::READ) {
283        if parser.parse_keyword(Keyword::LOCAL) {
284            Ok(LockTableType::Read { local: true })
285        } else {
286            Ok(LockTableType::Read { local: false })
287        }
288    } else if parser.parse_keyword(Keyword::WRITE) {
289        Ok(LockTableType::Write {
290            low_priority: false,
291        })
292    } else if parser.parse_keywords(&[Keyword::LOW_PRIORITY, Keyword::WRITE]) {
293        Ok(LockTableType::Write { low_priority: true })
294    } else {
295        parser.expected_ref("an lock type in LOCK TABLES", parser.peek_token_ref())
296    }
297}
298
299/// UNLOCK TABLES
300/// <https://dev.mysql.com/doc/refman/8.0/en/lock-tables.html>
301fn parse_unlock_tables(_parser: &mut Parser) -> Result<Statement, ParserError> {
302    Ok(Statement::UnlockTables)
303}