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)]
39pub struct MySqlDialect {}
40
41impl Dialect for MySqlDialect {
42    fn is_identifier_start(&self, ch: char) -> bool {
43        // See https://dev.mysql.com/doc/refman/8.0/en/identifiers.html.
44        // Identifiers which begin with a digit are recognized while tokenizing numbers,
45        // so they can be distinguished from exponent numeric literals.
46        // MySQL also implements non ascii utf-8 charecters
47        ch.is_alphabetic()
48            || ch == '_'
49            || ch == '$'
50            || ch == '@'
51            || ('\u{0080}'..='\u{ffff}').contains(&ch)
52            || !ch.is_ascii()
53    }
54
55    fn is_identifier_part(&self, ch: char) -> bool {
56        self.is_identifier_start(ch) || ch.is_ascii_digit() ||
57        // MySQL implements Unicode characters in identifiers.
58        !ch.is_ascii()
59    }
60
61    fn is_delimited_identifier_start(&self, ch: char) -> bool {
62        ch == '`'
63    }
64
65    fn identifier_quote_style(&self, _identifier: &str) -> Option<char> {
66        Some('`')
67    }
68
69    // See https://dev.mysql.com/doc/refman/8.0/en/string-literals.html#character-escape-sequences
70    fn supports_string_literal_backslash_escape(&self) -> bool {
71        true
72    }
73
74    fn ignores_wildcard_escapes(&self) -> bool {
75        true
76    }
77
78    fn supports_numeric_prefix(&self) -> bool {
79        true
80    }
81
82    fn parse_infix(
83        &self,
84        parser: &mut crate::parser::Parser,
85        expr: &crate::ast::Expr,
86        _precedence: u8,
87    ) -> Option<Result<crate::ast::Expr, ParserError>> {
88        // Parse DIV as an operator
89        if parser.parse_keyword(Keyword::DIV) {
90            Some(Ok(Expr::BinaryOp {
91                left: Box::new(expr.clone()),
92                op: BinaryOperator::MyIntegerDivide,
93                right: Box::new(parser.parse_expr().unwrap()),
94            }))
95        } else {
96            None
97        }
98    }
99
100    fn parse_statement(&self, parser: &mut Parser) -> Option<Result<Statement, ParserError>> {
101        if parser.parse_keywords(&[Keyword::LOCK, Keyword::TABLES]) {
102            Some(parse_lock_tables(parser))
103        } else if parser.parse_keywords(&[Keyword::UNLOCK, Keyword::TABLES]) {
104            Some(parse_unlock_tables(parser))
105        } else {
106            None
107        }
108    }
109
110    fn require_interval_qualifier(&self) -> bool {
111        true
112    }
113
114    fn supports_limit_comma(&self) -> bool {
115        true
116    }
117
118    /// See: <https://dev.mysql.com/doc/refman/8.4/en/create-table-select.html>
119    fn supports_create_table_select(&self) -> bool {
120        true
121    }
122
123    /// See: <https://dev.mysql.com/doc/refman/8.4/en/insert.html>
124    fn supports_insert_set(&self) -> bool {
125        true
126    }
127
128    fn supports_user_host_grantee(&self) -> bool {
129        true
130    }
131
132    fn is_table_factor_alias(&self, explicit: bool, kw: &Keyword, _parser: &mut Parser) -> bool {
133        explicit
134            || (!keywords::RESERVED_FOR_TABLE_ALIAS.contains(kw)
135                && !RESERVED_FOR_TABLE_ALIAS_MYSQL.contains(kw))
136    }
137
138    fn supports_table_hints(&self) -> bool {
139        true
140    }
141
142    fn requires_single_line_comment_whitespace(&self) -> bool {
143        true
144    }
145
146    fn supports_match_against(&self) -> bool {
147        true
148    }
149
150    fn supports_set_names(&self) -> bool {
151        true
152    }
153
154    fn supports_comma_separated_set_assignments(&self) -> bool {
155        true
156    }
157}
158
159/// `LOCK TABLES`
160/// <https://dev.mysql.com/doc/refman/8.0/en/lock-tables.html>
161fn parse_lock_tables(parser: &mut Parser) -> Result<Statement, ParserError> {
162    let tables = parser.parse_comma_separated(parse_lock_table)?;
163    Ok(Statement::LockTables { tables })
164}
165
166// tbl_name [[AS] alias] lock_type
167fn parse_lock_table(parser: &mut Parser) -> Result<LockTable, ParserError> {
168    let table = parser.parse_identifier()?;
169    let alias =
170        parser.parse_optional_alias(&[Keyword::READ, Keyword::WRITE, Keyword::LOW_PRIORITY])?;
171    let lock_type = parse_lock_tables_type(parser)?;
172
173    Ok(LockTable {
174        table,
175        alias,
176        lock_type,
177    })
178}
179
180// READ [LOCAL] | [LOW_PRIORITY] WRITE
181fn parse_lock_tables_type(parser: &mut Parser) -> Result<LockTableType, ParserError> {
182    if parser.parse_keyword(Keyword::READ) {
183        if parser.parse_keyword(Keyword::LOCAL) {
184            Ok(LockTableType::Read { local: true })
185        } else {
186            Ok(LockTableType::Read { local: false })
187        }
188    } else if parser.parse_keyword(Keyword::WRITE) {
189        Ok(LockTableType::Write {
190            low_priority: false,
191        })
192    } else if parser.parse_keywords(&[Keyword::LOW_PRIORITY, Keyword::WRITE]) {
193        Ok(LockTableType::Write { low_priority: true })
194    } else {
195        parser.expected("an lock type in LOCK TABLES", parser.peek_token())
196    }
197}
198
199/// UNLOCK TABLES
200/// <https://dev.mysql.com/doc/refman/8.0/en/lock-tables.html>
201fn parse_unlock_tables(_parser: &mut Parser) -> Result<Statement, ParserError> {
202    Ok(Statement::UnlockTables)
203}