sqltk_parser/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, LockTableType, LockTables, MySqlTableLock, 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::TABLE]) {
98            Some(parse_lock_tables(parser, false))
99        } else if parser.parse_keywords(&[Keyword::LOCK, Keyword::TABLES]) {
100            Some(parse_lock_tables(parser, true))
101        } else if parser.parse_keywords(&[Keyword::UNLOCK, Keyword::TABLE]) {
102            Some(parse_unlock_tables(parser, false))
103        } else if parser.parse_keywords(&[Keyword::UNLOCK, Keyword::TABLES]) {
104            Some(parse_unlock_tables(parser, true))
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(
162    parser: &mut Parser,
163    pluralized_table_keyword: bool,
164) -> Result<Statement, ParserError> {
165    let tables = parser.parse_comma_separated(parse_lock_table)?;
166    Ok(Statement::LockTables(LockTables::MySql {
167        pluralized_table_keyword,
168        tables,
169    }))
170}
171
172// tbl_name [[AS] alias] lock_type
173fn parse_lock_table(parser: &mut Parser) -> Result<MySqlTableLock, ParserError> {
174    let table = parser.parse_object_name(false)?;
175    let alias =
176        parser.parse_optional_alias(&[Keyword::READ, Keyword::WRITE, Keyword::LOW_PRIORITY])?;
177    let lock_type = parse_lock_tables_type(parser)?;
178
179    Ok(MySqlTableLock {
180        table,
181        alias,
182        lock_type: Some(lock_type),
183    })
184}
185
186// READ [LOCAL] | [LOW_PRIORITY] WRITE
187fn parse_lock_tables_type(parser: &mut Parser) -> Result<LockTableType, ParserError> {
188    if parser.parse_keyword(Keyword::READ) {
189        if parser.parse_keyword(Keyword::LOCAL) {
190            Ok(LockTableType::Read { local: true })
191        } else {
192            Ok(LockTableType::Read { local: false })
193        }
194    } else if parser.parse_keyword(Keyword::WRITE) {
195        Ok(LockTableType::Write {
196            low_priority: false,
197        })
198    } else if parser.parse_keywords(&[Keyword::LOW_PRIORITY, Keyword::WRITE]) {
199        Ok(LockTableType::Write { low_priority: true })
200    } else {
201        parser.expected("an lock type in LOCK TABLES", parser.peek_token())
202    }
203}
204
205/// UNLOCK TABLES
206/// <https://dev.mysql.com/doc/refman/8.0/en/lock-tables.html>
207fn parse_unlock_tables(
208    _parser: &mut Parser,
209    pluralized_table: bool,
210) -> Result<Statement, ParserError> {
211    Ok(Statement::UnlockTables(pluralized_table))
212}