Skip to main content

sqlparser/dialect/
sqlite.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, string::String};
20
21use crate::ast::{BinaryOperator, DataType, Expr, ObjectName, Statement};
22use crate::dialect::{BindPlaceholderStyle, Dialect, Precedence};
23use crate::keywords::{self, Keyword};
24use crate::parser::{Parser, ParserError};
25use crate::tokenizer::Token;
26
27/// Precedence of `<`, `<=`, `>` and `>=`, between `=` and the bitwise operators, see
28/// <https://www.sqlite.org/lang_expr.html#operators_and_parse_affecting_attributes>
29const COMPARISON_PREC: u8 = 21;
30
31/// A [`Dialect`] for [SQLite](https://www.sqlite.org)
32///
33/// This dialect allows columns in a
34/// [`CREATE TABLE`](https://sqlite.org/lang_createtable.html) statement with no
35/// type specified, as in `CREATE TABLE t1 (a)`. In the AST, these columns will
36/// have the data type [`Unspecified`](crate::ast::DataType::Unspecified).
37#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
38#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
39pub struct SQLiteDialect {}
40
41impl Dialect for SQLiteDialect {
42    // see https://www.sqlite.org/lang_keywords.html
43    // parse `...`, [...] and "..." as identifier
44    // TODO: support depending on the context tread '...' as identifier too.
45    fn is_delimited_identifier_start(&self, ch: char) -> bool {
46        ch == '`' || ch == '"' || ch == '['
47    }
48
49    fn identifier_quote_style(&self, _identifier: &str) -> Option<char> {
50        Some('`')
51    }
52
53    fn ordered_bind_placeholder_style(&self) -> Option<BindPlaceholderStyle> {
54        Some(BindPlaceholderStyle::QuestionMark)
55    }
56
57    fn is_identifier_start(&self, ch: char) -> bool {
58        // See https://www.sqlite.org/draft/tokenreq.html
59        ch.is_ascii_lowercase() || ch.is_ascii_uppercase() || ch == '_' || ch >= '\u{0080}'
60    }
61
62    fn supports_filter_during_aggregation(&self) -> bool {
63        true
64    }
65
66    fn supports_start_transaction_modifier(&self) -> bool {
67        true
68    }
69
70    fn is_identifier_part(&self, ch: char) -> bool {
71        self.is_identifier_start(ch) || ch.is_ascii_digit() || ch == '$'
72    }
73
74    fn parse_statement(&self, parser: &mut Parser) -> Option<Result<Statement, ParserError>> {
75        if parser.parse_keyword(Keyword::REPLACE) {
76            parser.prev_token();
77            Some(parser.parse_insert(parser.get_current_token().clone()))
78        } else {
79            None
80        }
81    }
82
83    fn parse_data_type(&self, parser: &mut Parser) -> Option<Result<DataType, ParserError>> {
84        parse_type_with_numeric_modifiers(parser).map(Ok)
85    }
86
87    fn parse_infix(
88        &self,
89        parser: &mut crate::parser::Parser,
90        expr: &crate::ast::Expr,
91        precedence: u8,
92    ) -> Option<Result<crate::ast::Expr, ParserError>> {
93        // Parse MATCH, REGEXP and GLOB as operators
94        // See <https://www.sqlite.org/lang_expr.html#the_like_glob_regexp_match_and_extract_operators>
95        for (keyword, op) in [
96            (Keyword::REGEXP, BinaryOperator::Regexp),
97            (Keyword::MATCH, BinaryOperator::Match),
98            (Keyword::GLOB, BinaryOperator::Glob),
99        ] {
100            if parser.parse_keyword(keyword) {
101                let left = Box::new(expr.clone());
102                let right = Box::new(match parser.parse_subexpr(precedence) {
103                    Ok(expr) => expr,
104                    Err(e) => return Some(Err(e)),
105                });
106                return Some(Ok(Expr::BinaryOp { left, op, right }));
107            }
108        }
109        None
110    }
111
112    /// `&`, `|`, `<<`, and `>>` share one left-associative precedence level.
113    /// See <https://www.sqlite.org/lang_expr.html#operators_and_parse_affecting_attributes>
114    fn get_next_precedence(&self, parser: &Parser) -> Option<Result<u8, ParserError>> {
115        match parser.peek_token_ref().token {
116            Token::Ampersand | Token::Pipe | Token::ShiftLeft | Token::ShiftRight => {
117                Some(Ok(self.prec_value(Precedence::Ampersand)))
118            }
119            Token::Lt | Token::LtEq | Token::Gt | Token::GtEq => Some(Ok(COMPARISON_PREC)),
120            // lowest prec to prevent it from turning into a binary op
121            Token::Colon => Some(Ok(self.prec_unknown())),
122            _ => None,
123        }
124    }
125
126    fn prec_value(&self, prec: Precedence) -> u8 {
127        match prec {
128            Precedence::Period => 100,
129            Precedence::DoubleColon => 50,
130            Precedence::AtTz => 41,
131            Precedence::MulDivModOp => 40,
132            Precedence::PlusMinus => 30,
133            Precedence::Xor => 25,
134            Precedence::Ampersand => 24,
135            Precedence::Caret => 23,
136            Precedence::Pipe | Precedence::Colon | Precedence::PgOther => 22,
137            Precedence::Between | Precedence::Eq => 20,
138            Precedence::Like => 19,
139            Precedence::Is => 17,
140            Precedence::UnaryNot => 15,
141            Precedence::And => 10,
142            Precedence::Or => 5,
143        }
144    }
145
146    fn supports_in_empty_list(&self) -> bool {
147        true
148    }
149
150    fn supports_limit_comma(&self) -> bool {
151        true
152    }
153
154    fn supports_asc_desc_in_column_definition(&self) -> bool {
155        true
156    }
157
158    fn supports_dollar_placeholder(&self) -> bool {
159        true
160    }
161
162    /// SQLite supports `NOTNULL` as aliases for `IS NOT NULL`
163    /// See: <https://sqlite.org/syntax/expr.html>
164    fn supports_notnull_operator(&self) -> bool {
165        true
166    }
167
168    fn supports_is_operator(&self) -> bool {
169        true
170    }
171
172    fn supports_comma_separated_trim(&self) -> bool {
173        true
174    }
175
176    fn supports_numeric_literal_underscores(&self) -> bool {
177        true
178    }
179
180    fn supports_double_eq_assignment(&self) -> bool {
181        true
182    }
183
184    fn supports_string_literal_column_names(&self) -> bool {
185        true
186    }
187
188    fn supports_cast_empty_data_type_to_unspecified(&self) -> bool {
189        true
190    }
191
192    fn supports_national_string_literal(&self) -> bool {
193        false
194    }
195
196    fn supports_parens_around_table_factor(&self) -> bool {
197        true
198    }
199
200    fn supports_unterminated_block_comments(&self) -> bool {
201        true
202    }
203
204    fn is_column_alias(&self, kw: &Keyword, _parser: &mut Parser) -> bool {
205        // https://www.sqlite.org/lang_keywords.html
206        !matches!(
207            kw,
208            Keyword::SELECT
209                | Keyword::WHERE
210                | Keyword::GROUP
211                | Keyword::HAVING
212                | Keyword::ORDER
213                | Keyword::LIMIT
214                | Keyword::UNION
215                | Keyword::EXCEPT
216                | Keyword::INTERSECT
217                | Keyword::RETURNING
218                | Keyword::VALUES
219                | Keyword::FROM
220                | Keyword::INTO
221        )
222    }
223
224    fn supports_over_keyword_as_column_alias(&self) -> bool {
225        true
226    }
227
228    fn supports_indexed_by(&self) -> bool {
229        true
230    }
231
232    /// `INDEXED BY` and `NOT INDEXED` follow the table name or alias.
233    fn is_table_alias(&self, kw: &Keyword, parser: &mut Parser) -> bool {
234        match kw {
235            Keyword::INDEXED => false,
236            Keyword::NOT => !parser.peek_keyword(Keyword::INDEXED),
237            _ => !keywords::RESERVED_FOR_TABLE_ALIAS.contains(kw),
238        }
239    }
240
241    fn supports_comma_join_constraint(&self) -> bool {
242        true
243    }
244
245    fn supports_aggregate_order_by_with_empty_args(&self) -> bool {
246        true
247    }
248
249    /// See <https://www.sqlite.org/lang_expr.html#binaryops>
250    fn supports_bitwise_shift_operators(&self) -> bool {
251        true
252    }
253
254    fn supports_in_table_expression(&self) -> bool {
255        true
256    }
257
258    /// The keywords SQLite does not accept as a name, as opposed to the
259    /// keywords its grammar lets fall back to an identifier.
260    /// See <https://www.sqlite.org/lang_keywords.html> and the `%fallback ID`
261    /// list in [parse.y](https://sqlite.org/src/file?name=src/parse.y)
262    fn is_table_factor(&self, kw: &Keyword, _parser: &mut Parser) -> bool {
263        !matches!(
264            kw,
265            Keyword::ADD
266                | Keyword::ALL
267                | Keyword::ALTER
268                | Keyword::AND
269                | Keyword::AS
270                | Keyword::AUTOINCREMENT
271                | Keyword::BETWEEN
272                | Keyword::CASE
273                | Keyword::CHECK
274                | Keyword::COLLATE
275                | Keyword::COMMIT
276                | Keyword::CONSTRAINT
277                | Keyword::CREATE
278                | Keyword::DEFAULT
279                | Keyword::DEFERRABLE
280                | Keyword::DELETE
281                | Keyword::DISTINCT
282                | Keyword::DROP
283                | Keyword::ELSE
284                | Keyword::ESCAPE
285                | Keyword::EXCEPT
286                | Keyword::EXISTS
287                | Keyword::FOREIGN
288                | Keyword::FROM
289                | Keyword::GROUP
290                | Keyword::HAVING
291                | Keyword::IN
292                | Keyword::INDEX
293                | Keyword::INSERT
294                | Keyword::INTERSECT
295                | Keyword::INTO
296                | Keyword::IS
297                | Keyword::JOIN
298                | Keyword::LIMIT
299                | Keyword::NOT
300                | Keyword::NOTHING
301                | Keyword::NOTNULL
302                | Keyword::NULL
303                | Keyword::ON
304                | Keyword::OR
305                | Keyword::ORDER
306                | Keyword::PRIMARY
307                | Keyword::REFERENCES
308                | Keyword::RETURNING
309                | Keyword::SELECT
310                | Keyword::SET
311                | Keyword::TABLE
312                | Keyword::THEN
313                | Keyword::TO
314                | Keyword::TRANSACTION
315                | Keyword::UNION
316                | Keyword::UNIQUE
317                | Keyword::UPDATE
318                | Keyword::USING
319                | Keyword::VALUES
320                | Keyword::WHEN
321                | Keyword::WHERE
322        )
323    }
324
325    /// Comparison and postfix operators bind within the BETWEEN low bound in SQLite (<https://www.sqlite.org/lang_expr.html>).
326    fn between_low_bound_precedence(&self) -> u8 {
327        self.prec_value(Precedence::And)
328    }
329}
330
331/// SQLite permits signed and decimal numeric type modifiers.
332fn parse_type_with_numeric_modifiers(parser: &mut Parser) -> Option<DataType> {
333    let (data_type, token_count) = {
334        let first = parser.peek_token_ref();
335        let Token::Word(word) = &first.token else {
336            return None;
337        };
338        if parser.peek_nth_token_ref(1).token != Token::LParen {
339            return None;
340        }
341        let mut modifiers = [None; 2];
342        let mut nth = 2;
343        let mut is_nonstandard = false;
344        let mut closed = false;
345        for modifier in &mut modifiers {
346            let sign = match parser.peek_nth_token_ref(nth).token {
347                Token::Minus => "-",
348                Token::Plus => "+",
349                _ => "",
350            };
351            if !sign.is_empty() {
352                is_nonstandard = true;
353                nth += 1;
354            }
355            let Token::Number(number, _) = &parser.peek_nth_token_ref(nth).token else {
356                return None;
357            };
358            is_nonstandard |= number.parse::<u64>().is_err();
359            *modifier = Some((sign, number));
360            match parser.peek_nth_token_ref(nth + 1).token {
361                Token::RParen => {
362                    closed = true;
363                    break;
364                }
365                Token::Comma => nth += 2,
366                _ => return None,
367            }
368        }
369        if !closed || !is_nonstandard {
370            return None;
371        }
372        let modifiers = modifiers
373            .into_iter()
374            .flatten()
375            .map(|(sign, number)| {
376                let mut value = String::with_capacity(sign.len() + number.len());
377                value.push_str(sign);
378                value.push_str(number);
379                crate::ast::TypeModifier::Number(value, false)
380            })
381            .collect();
382        (
383            DataType::Custom(
384                ObjectName::from(word.clone().into_ident(first.span)),
385                modifiers,
386            ),
387            nth + 2,
388        )
389    };
390    for _ in 0..token_count {
391        parser.advance_token();
392    }
393    Some(data_type)
394}