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(#[automatically_derived]
impl ::core::fmt::Debug for MySqlDialect {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f, "MySqlDialect")
    }
}Debug, #[automatically_derived]
impl ::core::default::Default for MySqlDialect {
    #[inline]
    fn default() -> MySqlDialect { MySqlDialect {} }
}Default, #[automatically_derived]
impl ::core::clone::Clone for MySqlDialect {
    #[inline]
    fn clone(&self) -> MySqlDialect { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for MySqlDialect { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for MySqlDialect {
    #[inline]
    fn eq(&self, other: &MySqlDialect) -> bool { true }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for MySqlDialect {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::hash::Hash for MySqlDialect {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {}
}Hash, #[automatically_derived]
impl ::core::cmp::PartialOrd for MySqlDialect {
    #[inline]
    fn partial_cmp(&self, other: &MySqlDialect)
        -> ::core::option::Option<::core::cmp::Ordering> {
        ::core::option::Option::Some(::core::cmp::Ordering::Equal)
    }
}PartialOrd, #[automatically_derived]
impl ::core::cmp::Ord for MySqlDialect {
    #[inline]
    fn cmp(&self, other: &MySqlDialect) -> ::core::cmp::Ordering {
        ::core::cmp::Ordering::Equal
    }
}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            Some(Ok(Expr::BinaryOp {
106                left: Box::new(expr.clone()),
107                op: BinaryOperator::MyIntegerDivide,
108                right: Box::new(parser.parse_expr().unwrap()),
109            }))
110        } else {
111            None
112        }
113    }
114
115    fn parse_statement(&self, parser: &mut Parser) -> Option<Result<Statement, ParserError>> {
116        if parser.parse_keywords(&[Keyword::LOCK, Keyword::TABLES]) {
117            Some(parse_lock_tables(parser))
118        } else if parser.parse_keywords(&[Keyword::UNLOCK, Keyword::TABLES]) {
119            Some(parse_unlock_tables(parser))
120        } else {
121            None
122        }
123    }
124
125    fn require_interval_qualifier(&self) -> bool {
126        true
127    }
128
129    fn supports_limit_comma(&self) -> bool {
130        true
131    }
132
133    /// See: <https://dev.mysql.com/doc/refman/8.4/en/create-table-select.html>
134    fn supports_create_table_select(&self) -> bool {
135        true
136    }
137
138    /// See: <https://dev.mysql.com/doc/refman/8.4/en/insert.html>
139    fn supports_insert_set(&self) -> bool {
140        true
141    }
142
143    fn supports_user_host_grantee(&self) -> bool {
144        true
145    }
146
147    fn is_table_factor_alias(&self, explicit: bool, kw: &Keyword, _parser: &mut Parser) -> bool {
148        explicit
149            || (!keywords::RESERVED_FOR_TABLE_ALIAS.contains(kw)
150                && !RESERVED_FOR_TABLE_ALIAS_MYSQL.contains(kw))
151    }
152
153    fn supports_table_hints(&self) -> bool {
154        true
155    }
156
157    fn requires_single_line_comment_whitespace(&self) -> bool {
158        true
159    }
160
161    fn supports_match_against(&self) -> bool {
162        true
163    }
164
165    fn supports_select_modifiers(&self) -> bool {
166        true
167    }
168
169    fn supports_set_names(&self) -> bool {
170        true
171    }
172
173    fn supports_comma_separated_set_assignments(&self) -> bool {
174        true
175    }
176
177    fn supports_data_type_signed_suffix(&self) -> bool {
178        true
179    }
180
181    fn supports_cross_join_constraint(&self) -> bool {
182        true
183    }
184
185    /// See: <https://dev.mysql.com/doc/refman/8.4/en/expressions.html>
186    fn supports_double_ampersand_operator(&self) -> bool {
187        true
188    }
189
190    /// Deprecated functionality by MySQL but still supported
191    /// See: <https://dev.mysql.com/doc/refman/8.4/en/cast-functions.html#operator_binary>
192    fn supports_binary_kw_as_cast(&self) -> bool {
193        true
194    }
195
196    fn supports_comment_optimizer_hint(&self) -> bool {
197        true
198    }
199
200    /// See: <https://dev.mysql.com/doc/refman/8.4/en/create-table.html>
201    fn supports_constraint_keyword_without_name(&self) -> bool {
202        true
203    }
204}
205
206/// `LOCK TABLES`
207/// <https://dev.mysql.com/doc/refman/8.0/en/lock-tables.html>
208fn parse_lock_tables(parser: &mut Parser) -> Result<Statement, ParserError> {
209    let tables = parser.parse_comma_separated(parse_lock_table)?;
210    Ok(Statement::LockTables { tables })
211}
212
213// tbl_name [[AS] alias] lock_type
214fn parse_lock_table(parser: &mut Parser) -> Result<LockTable, ParserError> {
215    let table = parser.parse_identifier()?;
216    let alias =
217        parser.parse_optional_alias(&[Keyword::READ, Keyword::WRITE, Keyword::LOW_PRIORITY])?;
218    let lock_type = parse_lock_tables_type(parser)?;
219
220    Ok(LockTable {
221        table,
222        alias,
223        lock_type,
224    })
225}
226
227// READ [LOCAL] | [LOW_PRIORITY] WRITE
228fn parse_lock_tables_type(parser: &mut Parser) -> Result<LockTableType, ParserError> {
229    if parser.parse_keyword(Keyword::READ) {
230        if parser.parse_keyword(Keyword::LOCAL) {
231            Ok(LockTableType::Read { local: true })
232        } else {
233            Ok(LockTableType::Read { local: false })
234        }
235    } else if parser.parse_keyword(Keyword::WRITE) {
236        Ok(LockTableType::Write {
237            low_priority: false,
238        })
239    } else if parser.parse_keywords(&[Keyword::LOW_PRIORITY, Keyword::WRITE]) {
240        Ok(LockTableType::Write { low_priority: true })
241    } else {
242        parser.expected("an lock type in LOCK TABLES", parser.peek_token())
243    }
244}
245
246/// UNLOCK TABLES
247/// <https://dev.mysql.com/doc/refman/8.0/en/lock-tables.html>
248fn parse_unlock_tables(_parser: &mut Parser) -> Result<Statement, ParserError> {
249    Ok(Statement::UnlockTables)
250}