Thanks to visit codestin.com
Credit goes to docs.rs

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