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, LockTable, LockTableType, Statement},
23    dialect::Dialect,
24    keywords::Keyword,
25    parser::{Parser, ParserError},
26};
27
28/// A [`Dialect`] for [MySQL](https://www.mysql.com/)
29#[derive(Debug)]
30pub struct MySqlDialect {}
31
32impl Dialect for MySqlDialect {
33    fn is_identifier_start(&self, ch: char) -> bool {
34        // See https://dev.mysql.com/doc/refman/8.0/en/identifiers.html.
35        // Identifiers which begin with a digit are recognized while tokenizing numbers,
36        // so they can be distinguished from exponent numeric literals.
37        ch.is_alphabetic()
38            || ch == '_'
39            || ch == '$'
40            || ch == '@'
41            || ('\u{0080}'..='\u{ffff}').contains(&ch)
42    }
43
44    fn is_identifier_part(&self, ch: char) -> bool {
45        self.is_identifier_start(ch) || ch.is_ascii_digit()
46    }
47
48    fn is_delimited_identifier_start(&self, ch: char) -> bool {
49        ch == '`'
50    }
51
52    fn identifier_quote_style(&self, _identifier: &str) -> Option<char> {
53        Some('`')
54    }
55
56    // See https://dev.mysql.com/doc/refman/8.0/en/string-literals.html#character-escape-sequences
57    fn supports_string_literal_backslash_escape(&self) -> bool {
58        true
59    }
60
61    fn supports_numeric_prefix(&self) -> bool {
62        true
63    }
64
65    fn parse_infix(
66        &self,
67        parser: &mut crate::parser::Parser,
68        expr: &crate::ast::Expr,
69        _precedence: u8,
70    ) -> Option<Result<crate::ast::Expr, ParserError>> {
71        // Parse DIV as an operator
72        if parser.parse_keyword(Keyword::DIV) {
73            Some(Ok(Expr::BinaryOp {
74                left: Box::new(expr.clone()),
75                op: BinaryOperator::MyIntegerDivide,
76                right: Box::new(parser.parse_expr().unwrap()),
77            }))
78        } else {
79            None
80        }
81    }
82
83    fn parse_statement(&self, parser: &mut Parser) -> Option<Result<Statement, ParserError>> {
84        if parser.parse_keywords(&[Keyword::LOCK, Keyword::TABLES]) {
85            Some(parse_lock_tables(parser))
86        } else if parser.parse_keywords(&[Keyword::UNLOCK, Keyword::TABLES]) {
87            Some(parse_unlock_tables(parser))
88        } else {
89            None
90        }
91    }
92
93    fn require_interval_qualifier(&self) -> bool {
94        true
95    }
96
97    fn supports_limit_comma(&self) -> bool {
98        true
99    }
100}
101
102/// `LOCK TABLES`
103/// <https://dev.mysql.com/doc/refman/8.0/en/lock-tables.html>
104fn parse_lock_tables(parser: &mut Parser) -> Result<Statement, ParserError> {
105    let tables = parser.parse_comma_separated(parse_lock_table)?;
106    Ok(Statement::LockTables { tables })
107}
108
109// tbl_name [[AS] alias] lock_type
110fn parse_lock_table(parser: &mut Parser) -> Result<LockTable, ParserError> {
111    let table = parser.parse_identifier(false)?;
112    let alias =
113        parser.parse_optional_alias(&[Keyword::READ, Keyword::WRITE, Keyword::LOW_PRIORITY])?;
114    let lock_type = parse_lock_tables_type(parser)?;
115
116    Ok(LockTable {
117        table,
118        alias,
119        lock_type,
120    })
121}
122
123// READ [LOCAL] | [LOW_PRIORITY] WRITE
124fn parse_lock_tables_type(parser: &mut Parser) -> Result<LockTableType, ParserError> {
125    if parser.parse_keyword(Keyword::READ) {
126        if parser.parse_keyword(Keyword::LOCAL) {
127            Ok(LockTableType::Read { local: true })
128        } else {
129            Ok(LockTableType::Read { local: false })
130        }
131    } else if parser.parse_keyword(Keyword::WRITE) {
132        Ok(LockTableType::Write {
133            low_priority: false,
134        })
135    } else if parser.parse_keywords(&[Keyword::LOW_PRIORITY, Keyword::WRITE]) {
136        Ok(LockTableType::Write { low_priority: true })
137    } else {
138        parser.expected("an lock type in LOCK TABLES", parser.peek_token())
139    }
140}
141
142/// UNLOCK TABLES
143/// <https://dev.mysql.com/doc/refman/8.0/en/lock-tables.html>
144fn parse_unlock_tables(_parser: &mut Parser) -> Result<Statement, ParserError> {
145    Ok(Statement::UnlockTables)
146}