sqlparser/dialect/mod.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
18mod ansi;
19mod bigquery;
20mod clickhouse;
21mod databricks;
22mod duckdb;
23mod generic;
24mod hive;
25mod mssql;
26mod mysql;
27mod oracle;
28mod postgresql;
29mod redshift;
30mod snowflake;
31mod spark;
32mod sqlite;
33mod teradata;
34
35use core::any::{Any, TypeId};
36use core::fmt::Debug;
37use core::iter::Peekable;
38use core::str::Chars;
39
40use log::debug;
41
42pub use self::ansi::AnsiDialect;
43pub use self::bigquery::BigQueryDialect;
44pub use self::clickhouse::ClickHouseDialect;
45pub use self::databricks::DatabricksDialect;
46pub use self::duckdb::DuckDbDialect;
47pub use self::generic::GenericDialect;
48pub use self::hive::HiveDialect;
49pub use self::mssql::MsSqlDialect;
50pub use self::mysql::MySqlDialect;
51pub use self::oracle::OracleDialect;
52pub use self::postgresql::PostgreSqlDialect;
53pub use self::redshift::RedshiftSqlDialect;
54pub use self::snowflake::parse_snowflake_stage_name;
55pub use self::snowflake::SnowflakeDialect;
56pub use self::spark::SparkSqlDialect;
57pub use self::sqlite::SQLiteDialect;
58pub use self::teradata::TeradataDialect;
59
60/// Macro for streamlining the creation of derived `Dialect` objects.
61/// The generated struct includes `new()` and `default()` constructors.
62/// Requires the `derive-dialect` feature.
63///
64/// # Syntax
65///
66/// ```text
67/// derive_dialect!(NewDialect, BaseDialect);
68/// derive_dialect!(NewDialect, BaseDialect, overrides = { method = value, ... });
69/// derive_dialect!(NewDialect, BaseDialect, preserve_type_id = true);
70/// derive_dialect!(NewDialect, BaseDialect, preserve_type_id = true, overrides = { ... });
71/// ```
72///
73/// # Example
74///
75/// ```
76/// use sqlparser::derive_dialect;
77/// use sqlparser::dialect::{Dialect, GenericDialect};
78///
79/// // Override boolean methods (supports_*, allow_*, etc.)
80/// derive_dialect!(CustomDialect, GenericDialect, overrides = {
81/// supports_order_by_all = true,
82/// supports_nested_comments = true,
83/// });
84///
85/// let dialect = CustomDialect::new();
86/// assert!(dialect.supports_order_by_all());
87/// assert!(dialect.supports_nested_comments());
88/// ```
89///
90/// # Overriding `identifier_quote_style`
91///
92/// Use a char literal or `None`:
93/// ```
94/// use sqlparser::derive_dialect;
95/// use sqlparser::dialect::{Dialect, PostgreSqlDialect};
96///
97/// derive_dialect!(BacktickPostgreSqlDialect, PostgreSqlDialect,
98/// preserve_type_id = true,
99/// overrides = { identifier_quote_style = '`' }
100/// );
101/// let d: &dyn Dialect = &BacktickPostgreSqlDialect::new();
102/// assert_eq!(d.identifier_quote_style("foo"), Some('`'));
103///
104/// derive_dialect!(QuotelessPostgreSqlDialect, PostgreSqlDialect,
105/// preserve_type_id = true,
106/// overrides = { identifier_quote_style = None }
107/// );
108/// let d: &dyn Dialect = &QuotelessPostgreSqlDialect::new();
109/// assert_eq!(d.identifier_quote_style("foo"), None);
110/// ```
111///
112/// # Overriding other methods
113///
114/// Any other method can be overridden with an expression of the method's return type:
115/// ```
116/// use sqlparser::derive_dialect;
117/// use sqlparser::dialect::{BindPlaceholderStyle, Dialect, GenericDialect};
118///
119/// derive_dialect!(DollarBindDialect, GenericDialect,
120/// overrides = {
121/// ordered_bind_placeholder_style = true.then_some(BindPlaceholderStyle::DollarNumbered)
122/// }
123/// );
124/// let d: &dyn Dialect = &DollarBindDialect::new();
125/// assert_eq!(
126/// d.ordered_bind_placeholder_style(),
127/// Some(BindPlaceholderStyle::DollarNumbered)
128/// );
129/// ```
130///
131/// # Type Identity
132///
133/// By default, derived dialects have their own `TypeId`. Set `preserve_type_id = true` to
134/// retain the base dialect's identity with respect to the parser's `dialect.is::<T>()` checks:
135/// ```
136/// use sqlparser::derive_dialect;
137/// use sqlparser::dialect::{Dialect, GenericDialect};
138///
139/// derive_dialect!(EnhancedGenericDialect, GenericDialect,
140/// preserve_type_id = true,
141/// overrides = {
142/// supports_order_by_all = true,
143/// supports_nested_comments = true,
144/// }
145/// );
146/// let d: &dyn Dialect = &EnhancedGenericDialect::new();
147/// assert!(d.is::<GenericDialect>()); // still recognized as a GenericDialect
148/// assert!(d.supports_nested_comments());
149/// assert!(d.supports_order_by_all());
150/// ```
151#[cfg(feature = "derive-dialect")]
152pub use sqlparser_derive::derive_dialect;
153
154use crate::ast::{
155 BinaryOperator, ColumnOption, DataType, Expr, GranteesType, Ident, ObjectNamePart, Statement,
156};
157pub use crate::keywords;
158use crate::keywords::Keyword;
159use crate::parser::{Parser, ParserError};
160use crate::tokenizer::Token;
161
162#[cfg(not(feature = "std"))]
163use alloc::boxed::Box;
164
165/// Convenience check if a [`Parser`] uses a certain dialect.
166///
167/// Note: when possible, please use the new style, adding a method to
168/// the [`Dialect`] trait rather than using this macro.
169///
170/// The benefits of adding a method on `Dialect` over this macro are:
171/// 1. user defined [`Dialect`]s can customize the parsing behavior
172/// 2. The differences between dialects can be clearly documented in the trait
173///
174/// `dialect_of!(parser is SQLiteDialect | GenericDialect)` evaluates
175/// to `true` if `parser.dialect` is one of the [`Dialect`]s specified.
176macro_rules! dialect_of {
177 ( $parsed_dialect: ident is $($dialect_type: ty)|+ ) => {
178 ($($parsed_dialect.dialect.is::<$dialect_type>())||+)
179 };
180}
181
182// Similar to above, but for applying directly against an instance of dialect
183// instead of a struct member named dialect. This avoids lifetime issues when
184// mixing match guards and token references.
185macro_rules! dialect_is {
186 ($dialect:ident is $($dialect_type:ty)|+) => {
187 ($($dialect.is::<$dialect_type>())||+)
188 }
189}
190
191/// Placeholder spelling for ordered unnamed bind parameters.
192#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
193#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
194#[non_exhaustive]
195pub enum BindPlaceholderStyle {
196 /// `?`
197 QuestionMark,
198 /// `$1`, `$2`, ...
199 DollarNumbered,
200}
201
202/// Encapsulates the differences between SQL implementations.
203///
204/// # SQL Dialects
205///
206/// SQL implementations deviate from one another, either due to
207/// custom extensions or various historical reasons. This trait
208/// encapsulates the parsing differences between dialects.
209///
210/// [`GenericDialect`] is the most permissive dialect, and parses the union of
211/// all the other dialects, when there is no ambiguity. However, it does not
212/// currently allow `CREATE TABLE` statements without types specified for all
213/// columns; use [`SQLiteDialect`] if you require that.
214///
215/// # Examples
216/// Most users create a [`Dialect`] directly, as shown on the [module
217/// level documentation]:
218///
219/// ```
220/// # use sqlparser::dialect::AnsiDialect;
221/// let dialect = AnsiDialect {};
222/// ```
223///
224/// It is also possible to dynamically create a [`Dialect`] from its
225/// name. For example:
226///
227/// ```
228/// # use sqlparser::dialect::{AnsiDialect, dialect_from_str};
229/// let dialect = dialect_from_str("ansi").unwrap();
230///
231/// // Parsed dialect is an instance of `AnsiDialect`:
232/// assert!(dialect.is::<AnsiDialect>());
233/// ```
234///
235/// [module level documentation]: crate
236pub trait Dialect: Debug + Any {
237 /// Determine the [`TypeId`] of this dialect.
238 ///
239 /// By default, return the same [`TypeId`] as [`Any::type_id`]. Can be overridden by
240 /// dialects that behave like other dialects (for example, when wrapping a dialect).
241 fn dialect(&self) -> TypeId {
242 self.type_id()
243 }
244
245 /// Determine if a character starts a quoted identifier. The default
246 /// implementation, accepting "double quoted" ids is both ANSI-compliant
247 /// and appropriate for most dialects (with the notable exception of
248 /// MySQL, MS SQL, and sqlite). You can accept one of characters listed
249 /// in `Word::matching_end_quote` here
250 fn is_delimited_identifier_start(&self, ch: char) -> bool {
251 ch == '"' || ch == '`'
252 }
253
254 /// Determine if a character starts a potential nested quoted identifier.
255 /// Example: RedShift supports the following quote styles to all mean the same thing:
256 /// ```sql
257 /// SELECT 1 AS foo;
258 /// SELECT 1 AS "foo";
259 /// SELECT 1 AS [foo];
260 /// SELECT 1 AS ["foo"];
261 /// ```
262 fn is_nested_delimited_identifier_start(&self, _ch: char) -> bool {
263 false
264 }
265
266 /// Only applicable whenever [`Self::is_nested_delimited_identifier_start`] returns true
267 /// If the next sequence of tokens potentially represent a nested identifier, then this method
268 /// returns a tuple containing the outer quote style, and if present, the inner (nested) quote style.
269 ///
270 /// Example (Redshift):
271 /// ```text
272 /// `["foo"]` => Some(`[`, Some(`"`))
273 /// `[foo]` => Some(`[`, None)
274 /// `[0]` => None
275 /// `"foo"` => None
276 /// ```
277 fn peek_nested_delimited_identifier_quotes(
278 &self,
279 mut _chars: Peekable<Chars<'_>>,
280 ) -> Option<(char, Option<char>)> {
281 None
282 }
283
284 /// Return the character used to quote identifiers.
285 fn identifier_quote_style(&self, _identifier: &str) -> Option<char> {
286 None
287 }
288
289 /// Return the placeholder syntax this server accepts for ordered unnamed bind parameters.
290 ///
291 /// This describes the server contract rather than every placeholder the parser can tokenize.
292 /// `None` means this dialect does not specify an ordered bind syntax.
293 /// Dollar-quoted strings are controlled by [`Dialect::supports_dollar_placeholder`].
294 fn ordered_bind_placeholder_style(&self) -> Option<BindPlaceholderStyle> {
295 None
296 }
297
298 /// Determine if a character is a valid start character for an unquoted identifier
299 fn is_identifier_start(&self, ch: char) -> bool;
300
301 /// Determine if a character is a valid unquoted identifier character
302 fn is_identifier_part(&self, ch: char) -> bool;
303
304 /// Most dialects do not have custom operators. Override this method to provide custom operators.
305 fn is_custom_operator_part(&self, _ch: char) -> bool {
306 false
307 }
308
309 /// Determine if the dialect supports escaping characters via '\' in string literals.
310 ///
311 /// Some dialects like BigQuery and Snowflake support this while others like
312 /// Postgres do not. Such that the following is accepted by the former but
313 /// rejected by the latter.
314 /// ```sql
315 /// SELECT 'ab\'cd';
316 /// ```
317 ///
318 /// Conversely, such dialects reject the following statement which
319 /// otherwise would be valid in the other dialects.
320 /// ```sql
321 /// SELECT '\';
322 /// ```
323 fn supports_string_literal_backslash_escape(&self) -> bool {
324 false
325 }
326
327 /// Does the dialect tokenize `N'...'` as a national string literal?
328 ///
329 /// Dialects such as SQLite treat `N` as a plain identifier, so `N'foo'` is
330 /// the identifier `N` followed by a string literal, not a national string.
331 fn supports_national_string_literal(&self) -> bool {
332 true
333 }
334
335 /// Treats literal prefixes immediately after `.` as unquoted identifiers.
336 ///
337 /// [MySQL](https://dev.mysql.com/doc/refman/8.4/en/identifiers.html),
338 /// [MariaDB](https://mariadb.com/docs/server/reference/sql-structure/sql-language-structure/identifier-names)
339 fn supports_literal_prefix_in_qualified_name(&self) -> bool {
340 false
341 }
342
343 /// Determine whether the dialect strips the backslash when escaping LIKE wildcards (%, _).
344 ///
345 /// [MySQL] has a special case when escaping single quoted strings which leaves these unescaped
346 /// so they can be used in LIKE patterns without double-escaping (as is necessary in other
347 /// escaping dialects, such as [Snowflake]). Generally, special characters have escaping rules
348 /// causing them to be replaced with a different byte sequences (e.g. `'\0'` becoming the zero
349 /// byte), and the default if an escaped character does not have a specific escaping rule is to
350 /// strip the backslash (e.g. there is no rule for `h`, so `'\h' = 'h'`). MySQL's special case
351 /// for ignoring LIKE wildcard escapes is to *not* strip the backslash, so that `'\%' = '\\%'`.
352 /// This applies to all string literals though, not just those used in LIKE patterns.
353 ///
354 /// ```text
355 /// mysql> select '\_', hex('\\'), hex('_'), hex('\_');
356 /// +----+-----------+----------+-----------+
357 /// | \_ | hex('\\') | hex('_') | hex('\_') |
358 /// +----+-----------+----------+-----------+
359 /// | \_ | 5C | 5F | 5C5F |
360 /// +----+-----------+----------+-----------+
361 /// 1 row in set (0.00 sec)
362 /// ```
363 ///
364 /// [MySQL]: https://dev.mysql.com/doc/refman/8.4/en/string-literals.html
365 /// [Snowflake]: https://docs.snowflake.com/en/sql-reference/functions/like#usage-notes
366 fn ignores_wildcard_escapes(&self) -> bool {
367 false
368 }
369
370 /// Determine if the dialect supports string literals with `U&` prefix.
371 /// This is used to specify Unicode code points in string literals.
372 /// For example, in PostgreSQL, the following is a valid string literal:
373 /// ```sql
374 /// SELECT U&'\0061\0062\0063';
375 /// ```
376 /// This is equivalent to the string literal `'abc'`.
377 /// See
378 /// - [Postgres docs](https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-STRINGS-UESCAPE)
379 /// - [H2 docs](http://www.h2database.com/html/grammar.html#string)
380 fn supports_unicode_string_literal(&self) -> bool {
381 false
382 }
383
384 /// Does the dialect support `FILTER (WHERE expr)` for aggregate queries?
385 fn supports_filter_during_aggregation(&self) -> bool {
386 false
387 }
388
389 /// Returns true if the dialect supports referencing another named window
390 /// within a window clause declaration.
391 ///
392 /// Example
393 /// ```sql
394 /// SELECT * FROM mytable
395 /// WINDOW mynamed_window AS another_named_window
396 /// ```
397 fn supports_window_clause_named_window_reference(&self) -> bool {
398 false
399 }
400
401 /// Returns true if the dialect supports `ARRAY_AGG() [WITHIN GROUP (ORDER BY)]` expressions.
402 /// Otherwise, the dialect should expect an `ORDER BY` without the `WITHIN GROUP` clause, e.g. [`ANSI`]
403 ///
404 /// [`ANSI`]: https://jakewheat.github.io/sql-overview/sql-2016-foundation-grammar.html#array-aggregate-function
405 fn supports_within_after_array_aggregation(&self) -> bool {
406 false
407 }
408
409 /// Returns true if the dialect supports `PARTITION BY` appearing after `ORDER BY`
410 /// in a `CREATE TABLE` statement (in addition to the standard placement before `ORDER BY`).
411 ///
412 /// ClickHouse DDL uses this ordering:
413 /// <https://clickhouse.com/docs/en/sql-reference/statements/create/table#partition-by>
414 fn supports_partition_by_after_order_by(&self) -> bool {
415 false
416 }
417
418 /// Returns true if the dialect supports ClickHouse-style `ARRAY JOIN` / `LEFT ARRAY JOIN` /
419 /// `INNER ARRAY JOIN` syntax for unnesting arrays inline.
420 ///
421 /// <https://clickhouse.com/docs/en/sql-reference/statements/select/array-join>
422 fn supports_array_join_syntax(&self) -> bool {
423 false
424 }
425
426 /// Returns true if the dialect supports `DROP GROUP`.
427 ///
428 /// <https://www.postgresql.org/docs/current/sql-dropgroup.html>
429 fn supports_drop_group(&self) -> bool {
430 false
431 }
432
433 /// Returns true if the dialect treats `ALTER USER` as a synonym for `ALTER ROLE`.
434 ///
435 /// In PostgreSQL, `ALTER USER` and `ALTER ROLE` are synonyms that accept the same
436 /// option syntax, so `ALTER USER` is parsed into a [`Statement::AlterRole`].
437 ///
438 /// <https://www.postgresql.org/docs/current/sql-alteruser.html>
439 ///
440 /// [`Statement::AlterRole`]: crate::ast::Statement::AlterRole
441 fn supports_alter_user_as_alter_role(&self) -> bool {
442 false
443 }
444
445 /// Returns true if the dialect supports `AS MATERIALIZED` and `AS NOT MATERIALIZED`
446 /// in a common table expression.
447 ///
448 /// ```sql
449 /// WITH cte AS MATERIALIZED (SELECT 1) SELECT * FROM cte
450 /// ```
451 fn supports_cte_materialization(&self) -> bool {
452 false
453 }
454
455 /// Returns true if the dialect supports `CREATE GROUP`.
456 ///
457 /// <https://www.postgresql.org/docs/current/sql-creategroup.html>
458 fn supports_create_group(&self) -> bool {
459 false
460 }
461
462 /// Returns true if `CREATE ROLE` accepts `IF NOT EXISTS`.
463 fn supports_create_role_if_not_exists(&self) -> bool {
464 true
465 }
466
467 /// Returns true if the dialects supports `group sets, roll up, or cube` expressions.
468 fn supports_group_by_expr(&self) -> bool {
469 false
470 }
471
472 /// Returns true if the dialects supports `GROUP BY` modifiers prefixed by a `WITH` keyword.
473 /// Example: `GROUP BY value WITH ROLLUP`.
474 fn supports_group_by_with_modifier(&self) -> bool {
475 false
476 }
477
478 /// Indicates whether the dialect supports left-associative join parsing
479 /// by default when parentheses are omitted in nested joins.
480 ///
481 /// Most dialects (like MySQL or Postgres) assume **left-associative** precedence,
482 /// so a query like:
483 ///
484 /// ```sql
485 /// SELECT * FROM t1 NATURAL JOIN t5 INNER JOIN t0 ON ...
486 /// ```
487 /// is interpreted as:
488 /// ```sql
489 /// ((t1 NATURAL JOIN t5) INNER JOIN t0 ON ...)
490 /// ```
491 /// and internally represented as a **flat list** of joins.
492 ///
493 /// In contrast, some dialects (e.g. **Snowflake**) assume **right-associative**
494 /// precedence and interpret the same query as:
495 /// ```sql
496 /// (t1 NATURAL JOIN (t5 INNER JOIN t0 ON ...))
497 /// ```
498 /// which results in a **nested join** structure in the AST.
499 ///
500 /// If this method returns `false`, the parser must build nested join trees
501 /// even in the absence of parentheses to reflect the correct associativity
502 fn supports_left_associative_joins_without_parens(&self) -> bool {
503 true
504 }
505
506 /// Returns true if the dialect supports the `(+)` syntax for OUTER JOIN.
507 fn supports_outer_join_operator(&self) -> bool {
508 false
509 }
510
511 /// Returns true if the dialect supports a join specification on CROSS JOIN.
512 fn supports_cross_join_constraint(&self) -> bool {
513 false
514 }
515
516 /// Returns true if the dialect supports `ON`/`USING` after a comma-joined table,
517 /// e.g. `SELECT * FROM t, u ON t.a = u.a`.
518 ///
519 /// [SQLite](https://www.sqlite.org/syntax/join-clause.html)
520 fn supports_comma_join_constraint(&self) -> bool {
521 false
522 }
523
524 /// Returns true if the dialect supports CONNECT BY.
525 fn supports_connect_by(&self) -> bool {
526 false
527 }
528
529 /// Returns true if the dialect supports `EXECUTE IMMEDIATE` statements.
530 fn supports_execute_immediate(&self) -> bool {
531 false
532 }
533
534 /// Returns true if the dialect supports the MATCH_RECOGNIZE operation.
535 fn supports_match_recognize(&self) -> bool {
536 false
537 }
538
539 /// Returns true if the dialect supports `(NOT) IN ()` expressions
540 fn supports_in_empty_list(&self) -> bool {
541 false
542 }
543
544 /// Returns true if the dialect supports a bare expression as the right-hand
545 /// side of `IN`, without a parenthesized list — as in `x IN 'a'`.
546 fn supports_in_unparenthesized_expr(&self) -> bool {
547 false
548 }
549
550 /// Returns true if the dialect supports `GLOBAL IN` and `GLOBAL NOT IN`.
551 fn supports_global_in(&self) -> bool {
552 false
553 }
554
555 /// Returns true if the dialect supports a table name or table-valued function
556 /// as the right-hand side of `IN`, e.g. `x IN t`, `x IN schema.t`, or `x IN f(args)`.
557 ///
558 /// [SQLite](https://www.sqlite.org/lang_expr.html#in_op)
559 fn supports_in_table_expression(&self) -> bool {
560 false
561 }
562
563 /// Returns true if the dialect supports `BEGIN {DEFERRED | IMMEDIATE | EXCLUSIVE | TRY | CATCH} [TRANSACTION]` statements
564 fn supports_start_transaction_modifier(&self) -> bool {
565 false
566 }
567
568 /// Returns true if the dialect supports `END {TRY | CATCH}` statements
569 fn supports_end_transaction_modifier(&self) -> bool {
570 false
571 }
572
573 /// Returns true if the dialect supports named arguments of the form `FUN(a = '1', b = '2')`.
574 fn supports_named_fn_args_with_eq_operator(&self) -> bool {
575 false
576 }
577
578 /// Returns true if the dialect supports named arguments of the form `FUN(a : '1', b : '2')`.
579 fn supports_named_fn_args_with_colon_operator(&self) -> bool {
580 false
581 }
582
583 /// Returns true if the dialect supports named arguments of the form `FUN(a := '1', b := '2')`.
584 fn supports_named_fn_args_with_assignment_operator(&self) -> bool {
585 false
586 }
587
588 /// Returns true if the dialect supports named arguments of the form `FUN(a => '1', b => '2')`.
589 fn supports_named_fn_args_with_rarrow_operator(&self) -> bool {
590 true
591 }
592
593 /// Returns true if dialect supports argument name as arbitrary expression.
594 /// e.g. `FUN(LOWER('a'):'1', b:'2')`
595 /// Such function arguments are represented in the AST by the `FunctionArg::ExprNamed` variant,
596 /// otherwise use the `FunctionArg::Named` variant (compatible reason).
597 fn supports_named_fn_args_with_expr_name(&self) -> bool {
598 false
599 }
600
601 /// Returns true if the dialect supports identifiers starting with a numeric
602 /// prefix such as tables named `59901_user_login`
603 fn supports_numeric_prefix(&self) -> bool {
604 false
605 }
606
607 /// Returns true if a period directly after an identifier starts a tuple
608 /// element access such as `t.1`, instead of the number `.1`.
609 fn supports_tuple_element_access(&self) -> bool {
610 false
611 }
612
613 /// Returns true if the dialect supports numbers containing underscores, e.g. `10_000_000`
614 fn supports_numeric_literal_underscores(&self) -> bool {
615 false
616 }
617
618 /// Returns true if the dialect supports integer literals in hexadecimal,
619 /// octal and binary, e.g. `0x1F`, `0o17` and `0b101`, which then parse as
620 /// numbers instead of `0x` hexadecimal strings.
621 fn supports_non_decimal_integer_literals(&self) -> bool {
622 false
623 }
624
625 /// Returns true if the dialects supports specifying null treatment
626 /// as part of a window function's parameter list as opposed
627 /// to after the parameter list.
628 ///
629 /// i.e The following syntax returns true
630 /// ```sql
631 /// FIRST_VALUE(a IGNORE NULLS) OVER ()
632 /// ```
633 /// while the following syntax returns false
634 /// ```sql
635 /// FIRST_VALUE(a) IGNORE NULLS OVER ()
636 /// ```
637 fn supports_window_function_null_treatment_arg(&self) -> bool {
638 false
639 }
640
641 /// Returns true if the dialect supports defining structs or objects using a
642 /// syntax like `{'x': 1, 'y': 2, 'z': 3}`.
643 fn supports_dictionary_syntax(&self) -> bool {
644 false
645 }
646
647 /// Returns true if the dialect supports defining object using the
648 /// syntax like `Map {1: 10, 2: 20}`.
649 fn support_map_literal_syntax(&self) -> bool {
650 false
651 }
652
653 /// Returns true if the dialect supports lambda functions, for example:
654 ///
655 /// ```sql
656 /// SELECT transform(array(1, 2, 3), x -> x + 1); -- returns [2,3,4]
657 /// ```
658 ///
659 /// This enables both the `->` spelling above and the `LAMBDA` keyword
660 /// spelling gated by [`Self::supports_lambda_keyword_syntax`]. A dialect
661 /// that uses `->` as a binary operator should override only the latter.
662 fn supports_lambda_functions(&self) -> bool {
663 false
664 }
665
666 /// Returns true if the dialect supports the `LAMBDA` keyword spelling of
667 /// lambda functions, for example:
668 ///
669 /// ```sql
670 /// SELECT list_transform([1, 2, 3], lambda x : x + 1); -- returns [2, 3, 4]
671 /// ```
672 ///
673 /// This spelling does not claim the `->` token, so it can be enabled by
674 /// dialects that already give `->` a different meaning, such as JSON
675 /// member access.
676 ///
677 /// Defaults to [`Self::supports_lambda_functions`], so dialects supporting
678 /// the `->` spelling accept the `LAMBDA` spelling too unless they say
679 /// otherwise.
680 ///
681 /// See <https://duckdb.org/docs/stable/sql/functions/lambda>
682 fn supports_lambda_keyword_syntax(&self) -> bool {
683 self.supports_lambda_functions()
684 }
685
686 /// Returns true if the dialect supports multiple variable assignment
687 /// using parentheses in a `SET` variable declaration.
688 ///
689 /// ```sql
690 /// SET (variable[, ...]) = (expression[, ...]);
691 /// ```
692 fn supports_parenthesized_set_variables(&self) -> bool {
693 false
694 }
695
696 /// Returns true if the dialect supports multiple `SET` statements
697 /// in a single statement.
698 ///
699 /// ```sql
700 /// SET variable = expression [, variable = expression];
701 /// ```
702 fn supports_comma_separated_set_assignments(&self) -> bool {
703 false
704 }
705
706 /// Returns true if the dialect supports `ORDER BY` in `UPDATE` statements.
707 ///
708 /// ```sql
709 /// UPDATE foo SET bar = false WHERE foo = true ORDER BY foo ASC;
710 /// ```
711 /// See <https://dev.mysql.com/doc/refman/8.4/en/update.html>
712 fn supports_update_order_by(&self) -> bool {
713 false
714 }
715
716 /// Returns true if the dialect supports an `EXCEPT` clause following a
717 /// wildcard in a select list.
718 ///
719 /// For example
720 /// ```sql
721 /// SELECT * EXCEPT order_id FROM orders;
722 /// ```
723 fn supports_select_wildcard_except(&self) -> bool {
724 false
725 }
726
727 /// Returns true if the dialect has a CONVERT function which accepts a type first
728 /// and an expression second, e.g. `CONVERT(varchar, 1)`
729 fn convert_type_before_value(&self) -> bool {
730 false
731 }
732
733 /// Returns true if the dialect supports triple quoted string
734 /// e.g. `"""abc"""`
735 fn supports_triple_quoted_string(&self) -> bool {
736 false
737 }
738
739 /// Dialect-specific prefix parser override
740 fn parse_prefix(&self, _parser: &mut Parser) -> Option<Result<Expr, ParserError>> {
741 // return None to fall back to the default behavior
742 None
743 }
744
745 /// Does the dialect support the `APPROXIMATE PERCENTILE_DISC` function syntax?
746 /// See <https://docs.aws.amazon.com/redshift/latest/dg/r_APPROXIMATE_PERCENTILE_DISC.html>
747 fn supports_approximate_percentile_disc(&self) -> bool {
748 false
749 }
750
751 /// Does the dialect support trailing commas around the query?
752 fn supports_trailing_commas(&self) -> bool {
753 false
754 }
755
756 /// Does the dialect support parsing `LIMIT 1, 2` as `LIMIT 2 OFFSET 1`?
757 fn supports_limit_comma(&self) -> bool {
758 false
759 }
760
761 /// Returns true if the dialect supports concatenating of string literal
762 /// Example: `SELECT 'Hello ' "world" => SELECT 'Hello world'`
763 fn supports_string_literal_concatenation(&self) -> bool {
764 false
765 }
766
767 /// Returns true if the dialect supports concatenating string literals with a newline.
768 /// For example, the following statement would return `true`:
769 /// ```sql
770 /// SELECT 'abc' in (
771 /// 'a'
772 /// 'b'
773 /// 'c'
774 /// );
775 /// ```
776 fn supports_string_literal_concatenation_with_newline(&self) -> bool {
777 false
778 }
779
780 /// Does the dialect support trailing commas in the projection list?
781 fn supports_projection_trailing_commas(&self) -> bool {
782 self.supports_trailing_commas()
783 }
784
785 /// Returns true if the dialect supports trailing commas in the `FROM` clause of a `SELECT` statement.
786 /// Example: `SELECT 1 FROM T, U, LIMIT 1`
787 fn supports_from_trailing_commas(&self) -> bool {
788 false
789 }
790
791 /// Returns true if the dialect supports trailing commas in the
792 /// column definitions list of a `CREATE` statement.
793 /// Example: `CREATE TABLE T (x INT, y TEXT,)`
794 fn supports_column_definition_trailing_commas(&self) -> bool {
795 false
796 }
797
798 /// Returns true if the dialect supports double dot notation for object names
799 ///
800 /// Example
801 /// ```sql
802 /// SELECT * FROM db_name..table_name
803 /// ```
804 fn supports_object_name_double_dot_notation(&self) -> bool {
805 false
806 }
807
808 /// Return true if the dialect supports the STRUCT literal
809 ///
810 /// Example
811 /// ```sql
812 /// SELECT STRUCT(1 as one, 'foo' as foo, false)
813 /// ```
814 fn supports_struct_literal(&self) -> bool {
815 false
816 }
817
818 /// Return true if the dialect supports empty projections in SELECT statements
819 ///
820 /// Example
821 /// ```sql
822 /// SELECT from table_name
823 /// ```
824 fn supports_empty_projections(&self) -> bool {
825 false
826 }
827
828 /// Return true if the dialect supports wildcard expansion on
829 /// arbitrary expressions in projections.
830 ///
831 /// Example:
832 /// ```sql
833 /// SELECT STRUCT<STRING>('foo').* FROM T
834 /// ```
835 fn supports_select_expr_star(&self) -> bool {
836 false
837 }
838
839 /// Return true if the dialect supports "FROM-first" selects.
840 ///
841 /// Example:
842 /// ```sql
843 /// FROM table
844 /// SELECT *
845 /// ```
846 fn supports_from_first_select(&self) -> bool {
847 false
848 }
849
850 /// Return true if the dialect supports "FROM-first" inserts.
851 ///
852 /// Example:
853 /// ```sql
854 /// WITH cte AS (SELECT key FROM src)
855 /// FROM cte
856 /// INSERT OVERWRITE table my_table
857 /// SELECT *
858 ///
859 /// See <https://hive.apache.org/docs/latest/language/common-table-expression/>
860 /// ```
861 fn supports_from_first_insert(&self) -> bool {
862 false
863 }
864
865 /// Return true if the dialect supports pipe operator.
866 ///
867 /// Example:
868 /// ```sql
869 /// SELECT *
870 /// FROM table
871 /// |> limit 1
872 /// ```
873 ///
874 /// See <https://cloud.google.com/bigquery/docs/pipe-syntax-guide#basic_syntax>
875 fn supports_pipe_operator(&self) -> bool {
876 false
877 }
878
879 /// Does the dialect support MySQL-style `'user'@'host'` grantee syntax?
880 fn supports_user_host_grantee(&self) -> bool {
881 false
882 }
883
884 /// Does the dialect support the `MATCH() AGAINST()` syntax?
885 fn supports_match_against(&self) -> bool {
886 false
887 }
888
889 /// Returns true if the dialect supports an exclude option
890 /// following a wildcard in the projection section. For example:
891 /// `SELECT * EXCLUDE col1 FROM tbl`.
892 ///
893 /// [Redshift](https://docs.aws.amazon.com/redshift/latest/dg/r_EXCLUDE_list.html)
894 /// [Snowflake](https://docs.snowflake.com/en/sql-reference/sql/select)
895 fn supports_select_wildcard_exclude(&self) -> bool {
896 false
897 }
898
899 /// Returns true if the dialect supports an exclude option
900 /// as the last item in the projection section, not necessarily
901 /// after a wildcard. For example:
902 /// `SELECT *, c1, c2 EXCLUDE c3 FROM tbl`
903 ///
904 /// [Redshift](https://docs.aws.amazon.com/redshift/latest/dg/r_EXCLUDE_list.html)
905 fn supports_select_exclude(&self) -> bool {
906 false
907 }
908
909 /// Returns true if the dialect supports specifying multiple options
910 /// in a `CREATE TABLE` statement for the structure of the new table. For example:
911 /// `CREATE TABLE t (a INT, b INT) AS SELECT 1 AS b, 2 AS a`
912 fn supports_create_table_multi_schema_info_sources(&self) -> bool {
913 false
914 }
915
916 /// Returns true if the dialect supports MySQL-specific SELECT modifiers
917 /// like `HIGH_PRIORITY`, `STRAIGHT_JOIN`, `SQL_SMALL_RESULT`, etc.
918 ///
919 /// For example:
920 /// ```sql
921 /// SELECT HIGH_PRIORITY STRAIGHT_JOIN SQL_SMALL_RESULT * FROM t1 JOIN t2 ON ...
922 /// ```
923 ///
924 /// [MySQL](https://dev.mysql.com/doc/refman/8.4/en/select.html)
925 fn supports_select_modifiers(&self) -> bool {
926 false
927 }
928
929 /// Dialect-specific infix parser override
930 ///
931 /// This method is called to parse the next infix expression.
932 ///
933 /// If `None` is returned, falls back to the default behavior.
934 fn parse_infix(
935 &self,
936 _parser: &mut Parser,
937 _expr: &Expr,
938 _precedence: u8,
939 ) -> Option<Result<Expr, ParserError>> {
940 // return None to fall back to the default behavior
941 None
942 }
943
944 /// Dialect-specific precedence override
945 ///
946 /// This method is called to get the precedence of the next token.
947 ///
948 /// If `None` is returned, falls back to the default behavior.
949 fn get_next_precedence(&self, _parser: &Parser) -> Option<Result<u8, ParserError>> {
950 // return None to fall back to the default behavior
951 None
952 }
953
954 /// Get the precedence of the next token, looking at the full token stream.
955 ///
956 /// A higher number => higher precedence
957 ///
958 /// See [`Self::get_next_precedence`] to override the behavior for just the
959 /// next token.
960 ///
961 /// The default implementation is used for many dialects, but can be
962 /// overridden to provide dialect-specific behavior.
963 fn get_next_precedence_default(&self, parser: &Parser) -> Result<u8, ParserError> {
964 if let Some(precedence) = self.get_next_precedence(parser) {
965 return precedence;
966 }
967 macro_rules! p {
968 ($precedence:ident) => {
969 self.prec_value(Precedence::$precedence)
970 };
971 }
972
973 let token = parser.peek_token_ref();
974 debug!("get_next_precedence_full() {token:?}");
975 match &token.token {
976 Token::Word(w) if w.keyword == Keyword::OR => Ok(p!(Or)),
977 Token::Word(w) if w.keyword == Keyword::AND => Ok(p!(And)),
978 Token::Word(w) if w.keyword == Keyword::XOR => Ok(p!(Xor)),
979
980 Token::Word(w) if w.keyword == Keyword::AT => {
981 match (
982 &parser.peek_nth_token_ref(1).token,
983 &parser.peek_nth_token_ref(2).token,
984 ) {
985 (Token::Word(w), Token::Word(w2))
986 if w.keyword == Keyword::TIME && w2.keyword == Keyword::ZONE =>
987 {
988 Ok(p!(AtTz))
989 }
990 _ => Ok(self.prec_unknown()),
991 }
992 }
993
994 Token::Word(w) if w.keyword == Keyword::NOT => {
995 match &parser.peek_nth_token_ref(1).token {
996 // The precedence of NOT varies depending on keyword that
997 // follows it. If it is followed by IN, BETWEEN, or LIKE,
998 // it takes on the precedence of those tokens. Otherwise, it
999 // is not an infix operator, and therefore has zero
1000 // precedence.
1001 Token::Word(w) if w.keyword == Keyword::IN => Ok(p!(Between)),
1002 Token::Word(w) if w.keyword == Keyword::BETWEEN => Ok(p!(Between)),
1003 Token::Word(w) if w.keyword == Keyword::LIKE => Ok(p!(Like)),
1004 Token::Word(w) if w.keyword == Keyword::ILIKE => Ok(p!(Like)),
1005 Token::Word(w) if w.keyword == Keyword::RLIKE => Ok(p!(Like)),
1006 Token::Word(w) if w.keyword == Keyword::REGEXP => Ok(p!(Like)),
1007 Token::Word(w) if w.keyword == Keyword::MATCH => Ok(p!(Like)),
1008 Token::Word(w) if w.keyword == Keyword::GLOB => Ok(p!(Like)),
1009 Token::Word(w) if w.keyword == Keyword::SIMILAR => Ok(p!(Like)),
1010 Token::Word(w) if w.keyword == Keyword::MEMBER => Ok(p!(Like)),
1011 Token::Word(w)
1012 if w.keyword == Keyword::NULL && !parser.in_column_definition_state() =>
1013 {
1014 Ok(p!(Is))
1015 }
1016 _ => Ok(self.prec_unknown()),
1017 }
1018 }
1019 Token::Word(w) if w.keyword == Keyword::NOTNULL && self.supports_notnull_operator() => {
1020 Ok(p!(Is))
1021 }
1022 Token::Word(w) if w.keyword == Keyword::IS => Ok(p!(Is)),
1023 Token::Word(w) if w.keyword == Keyword::GLOBAL && self.supports_global_in() => {
1024 match (
1025 &parser.peek_nth_token_ref(1).token,
1026 &parser.peek_nth_token_ref(2).token,
1027 ) {
1028 (Token::Word(w), _) if w.keyword == Keyword::IN => Ok(p!(Between)),
1029 (Token::Word(w), Token::Word(w2))
1030 if w.keyword == Keyword::NOT && w2.keyword == Keyword::IN =>
1031 {
1032 Ok(p!(Between))
1033 }
1034 _ => Ok(self.prec_unknown()),
1035 }
1036 }
1037 Token::Word(w) if w.keyword == Keyword::IN => Ok(p!(Between)),
1038 Token::Word(w) if w.keyword == Keyword::BETWEEN => Ok(p!(Between)),
1039 Token::Word(w) if w.keyword == Keyword::OVERLAPS => Ok(p!(Between)),
1040 Token::Word(w) if w.keyword == Keyword::LIKE => Ok(p!(Like)),
1041 Token::Word(w) if w.keyword == Keyword::ILIKE => Ok(p!(Like)),
1042 Token::Word(w) if w.keyword == Keyword::RLIKE => Ok(p!(Like)),
1043 Token::Word(w) if w.keyword == Keyword::REGEXP => Ok(p!(Like)),
1044 Token::Word(w) if w.keyword == Keyword::MATCH => Ok(p!(Like)),
1045 Token::Word(w) if w.keyword == Keyword::GLOB => Ok(p!(Like)),
1046 Token::Word(w) if w.keyword == Keyword::SIMILAR => Ok(p!(Like)),
1047 Token::Word(w) if w.keyword == Keyword::MEMBER => Ok(p!(Like)),
1048 Token::Word(w) if w.keyword == Keyword::OPERATOR => Ok(p!(Between)),
1049 Token::Word(w) if w.keyword == Keyword::DIV => Ok(p!(MulDivModOp)),
1050 Token::Period => Ok(p!(Period)),
1051 Token::Assignment
1052 | Token::Eq
1053 | Token::Lt
1054 | Token::LtEq
1055 | Token::Neq
1056 | Token::Gt
1057 | Token::GtEq
1058 | Token::DoubleEq
1059 | Token::Tilde
1060 | Token::TildeAsterisk
1061 | Token::ExclamationMarkTilde
1062 | Token::ExclamationMarkTildeAsterisk
1063 | Token::DoubleTilde
1064 | Token::DoubleTildeAsterisk
1065 | Token::ExclamationMarkDoubleTilde
1066 | Token::ExclamationMarkDoubleTildeAsterisk
1067 | Token::Spaceship => Ok(p!(Eq)),
1068 Token::Pipe
1069 | Token::QuestionMarkDash
1070 | Token::DoubleSharp
1071 | Token::Overlap
1072 | Token::AmpersandLeftAngleBracket
1073 | Token::AmpersandRightAngleBracket
1074 | Token::QuestionMarkDashVerticalBar
1075 | Token::AmpersandLeftAngleBracketVerticalBar
1076 | Token::VerticalBarAmpersandRightAngleBracket
1077 | Token::TwoWayArrow
1078 | Token::LeftAngleBracketCaret
1079 | Token::RightAngleBracketCaret
1080 | Token::QuestionMarkSharp
1081 | Token::QuestionMarkDoubleVerticalBar
1082 | Token::QuestionPipe
1083 | Token::TildeEqual
1084 | Token::AtSign
1085 | Token::ShiftLeftVerticalBar
1086 | Token::VerticalBarShiftRight => Ok(p!(Pipe)),
1087 Token::Caret | Token::Sharp | Token::ShiftRight | Token::ShiftLeft => Ok(p!(Caret)),
1088 Token::Ampersand => Ok(p!(Ampersand)),
1089 Token::Plus | Token::Minus => Ok(p!(PlusMinus)),
1090 Token::Mul | Token::Div | Token::DuckIntDiv | Token::Mod | Token::StringConcat => {
1091 Ok(p!(MulDivModOp))
1092 }
1093 Token::DoubleColon | Token::ExclamationMark | Token::LBracket | Token::CaretAt => {
1094 Ok(p!(DoubleColon))
1095 }
1096 Token::Colon => match &parser.peek_nth_token_ref(1).token {
1097 // When colon is followed by a string or a number, it's usually in MAP syntax.
1098 Token::SingleQuotedString(_) | Token::Number(_, _) => Ok(self.prec_unknown()),
1099 // In other cases, it's used in semi-structured data traversal like in variant or JSON
1100 // string columns. See `JsonAccess`.
1101 _ => Ok(p!(Colon)),
1102 },
1103 Token::Arrow
1104 | Token::LongArrow
1105 | Token::HashArrow
1106 | Token::HashLongArrow
1107 | Token::AtArrow
1108 | Token::ArrowAt
1109 | Token::HashMinus
1110 | Token::AtQuestion
1111 | Token::AtAt
1112 | Token::Question
1113 | Token::QuestionAnd
1114 | Token::CustomBinaryOperator(_) => Ok(p!(PgOther)),
1115 _ => Ok(self.prec_unknown()),
1116 }
1117 }
1118
1119 /// Dialect-specific statement parser override
1120 ///
1121 /// This method is called to parse the next statement.
1122 ///
1123 /// If `None` is returned, falls back to the default behavior.
1124 fn parse_statement(&self, _parser: &mut Parser) -> Option<Result<Statement, ParserError>> {
1125 // return None to fall back to the default behavior
1126 None
1127 }
1128
1129 /// Parses a dialect-specific type, leaving the cursor unchanged on `None` to use standard parsing.
1130 fn parse_data_type(&self, _parser: &mut Parser) -> Option<Result<DataType, ParserError>> {
1131 None
1132 }
1133
1134 /// Dialect-specific column option parser override
1135 ///
1136 /// This method is called to parse the next column option.
1137 ///
1138 /// If `None` is returned, falls back to the default behavior.
1139 fn parse_column_option(
1140 &self,
1141 _parser: &mut Parser,
1142 ) -> Result<Option<Result<Option<ColumnOption>, ParserError>>, ParserError> {
1143 // return None to fall back to the default behavior
1144 Ok(None)
1145 }
1146
1147 /// Decide the lexical Precedence of operators.
1148 ///
1149 /// Uses (APPROXIMATELY) <https://www.postgresql.org/docs/7.0/operators.htm#AEN2026> as a reference
1150 fn prec_value(&self, prec: Precedence) -> u8 {
1151 match prec {
1152 Precedence::Period => 100,
1153 Precedence::DoubleColon => 50,
1154 Precedence::AtTz => 41,
1155 Precedence::MulDivModOp => 40,
1156 Precedence::PlusMinus => 30,
1157 Precedence::Xor => 24,
1158 Precedence::Ampersand => 23,
1159 Precedence::Caret => 22,
1160 Precedence::Pipe => 21,
1161 Precedence::Colon => 21,
1162 // "any other operator" -- `->`, `@>`, custom operators. PostgreSQL
1163 // places this row above `BETWEEN` / `LIKE` and below `+` / `-`
1164 // (`%left Op OPERATOR RIGHT_ARROW '|'` in gram.y), so it must bind
1165 // more tightly than `IS`, whose right operand would otherwise stop
1166 // short of it.
1167 Precedence::PgOther => 21,
1168 Precedence::Between => 20,
1169 Precedence::Eq => 20,
1170 Precedence::Like => 19,
1171 Precedence::Is => 17,
1172 Precedence::UnaryNot => 15,
1173 Precedence::And => 10,
1174 Precedence::Or => 5,
1175 }
1176 }
1177
1178 /// Returns the precedence when the precedence is otherwise unknown
1179 fn prec_unknown(&self) -> u8 {
1180 0
1181 }
1182
1183 /// Precedence used to stop parsing the low bound expression of a BETWEEN predicate.
1184 fn between_low_bound_precedence(&self) -> u8 {
1185 self.prec_value(Precedence::Between)
1186 }
1187
1188 /// Returns true if the low bound of a `BETWEEN` predicate may end with one comparison,
1189 /// as in `a BETWEEN b > 1 AND c`, while `IS`, `LIKE` and `BETWEEN` still end the bound.
1190 ///
1191 /// The low bound is a `b_expr` in the
1192 /// [PostgreSQL grammar](https://github.com/postgres/postgres/blob/master/src/backend/parser/gram.y)
1193 /// and a `valueExpression` in the
1194 /// [Spark grammar](https://github.com/apache/spark/blob/master/sql/api/src/main/antlr4/org/apache/spark/sql/catalyst/parser/SqlBaseParser.g4).
1195 fn supports_comparison_in_between_low_bound(&self) -> bool {
1196 false
1197 }
1198
1199 /// Returns true if this dialect requires the `TABLE` keyword after `DESCRIBE`
1200 ///
1201 /// Defaults to false.
1202 ///
1203 /// If true, the following statement is valid: `DESCRIBE TABLE my_table`
1204 /// If false, the following statements are valid: `DESCRIBE my_table` and `DESCRIBE table`
1205 fn describe_requires_table_keyword(&self) -> bool {
1206 false
1207 }
1208
1209 /// Returns true if this dialect allows the `EXTRACT` function to words other than [`Keyword`].
1210 fn allow_extract_custom(&self) -> bool {
1211 false
1212 }
1213
1214 /// Returns true if this dialect allows the `EXTRACT` function to use single quotes in the part being extracted.
1215 fn allow_extract_single_quotes(&self) -> bool {
1216 false
1217 }
1218
1219 /// Returns true if this dialect supports the `EXTRACT` function
1220 /// with a comma separator instead of `FROM`.
1221 ///
1222 /// Example:
1223 /// ```sql
1224 /// SELECT EXTRACT(YEAR, date_column) FROM table;
1225 /// ```
1226 ///
1227 /// [Snowflake](https://docs.snowflake.com/en/sql-reference/functions/extract)
1228 fn supports_extract_comma_syntax(&self) -> bool {
1229 false
1230 }
1231
1232 /// Returns true if this dialect supports a subquery passed to a function
1233 /// as the only argument without enclosing parentheses.
1234 ///
1235 /// Example:
1236 /// ```sql
1237 /// SELECT FLATTEN(SELECT * FROM tbl);
1238 /// ```
1239 ///
1240 /// [Snowflake](https://docs.snowflake.com/en/sql-reference/functions/flatten)
1241 fn supports_subquery_as_function_arg(&self) -> bool {
1242 false
1243 }
1244
1245 /// Returns true if this dialect supports the `COMMENT` clause in
1246 /// `CREATE VIEW` statements using the `COMMENT = 'comment'` syntax.
1247 ///
1248 /// Example:
1249 /// ```sql
1250 /// CREATE VIEW v COMMENT = 'my comment' AS SELECT 1;
1251 /// ```
1252 ///
1253 /// [Snowflake](https://docs.snowflake.com/en/sql-reference/sql/create-view#optional-parameters)
1254 fn supports_create_view_comment_syntax(&self) -> bool {
1255 false
1256 }
1257
1258 /// Returns true if a data type can carry a collation, including inside a
1259 /// nested type such as `MAP<STRING COLLATE UTF8_BINARY, STRING>`.
1260 fn supports_data_type_collation(&self) -> bool {
1261 false
1262 }
1263
1264 /// Returns true if this dialect supports the `ARRAY` type without
1265 /// specifying an element type.
1266 ///
1267 /// Example:
1268 /// ```sql
1269 /// CREATE TABLE t (a ARRAY);
1270 /// ```
1271 ///
1272 /// [Snowflake](https://docs.snowflake.com/en/sql-reference/data-types-semistructured#array)
1273 fn supports_array_typedef_without_element_type(&self) -> bool {
1274 false
1275 }
1276
1277 /// Returns true if this dialect supports the `ARRAY(element_type)` syntax.
1278 ///
1279 /// Example:
1280 /// ```sql
1281 /// CREATE TABLE t (a ARRAY(VARCHAR));
1282 /// ```
1283 fn supports_array_typedef_with_parentheses(&self) -> bool {
1284 false
1285 }
1286
1287 /// Returns true if this dialect supports `NOT NULL` on an element type in
1288 /// an `ARRAY(element_type)` definition.
1289 fn supports_array_element_not_null(&self) -> bool {
1290 false
1291 }
1292
1293 /// Returns true if this dialect supports the `MAP(key_type, value_type)` syntax.
1294 fn supports_map_typedef_with_parentheses(&self) -> bool {
1295 false
1296 }
1297
1298 /// Returns true if this dialect supports `NOT NULL` on the value type in
1299 /// a `MAP(key_type, value_type)` definition.
1300 fn supports_map_value_not_null(&self) -> bool {
1301 false
1302 }
1303
1304 /// Returns true if this dialect supports extra parentheses around
1305 /// lone table names or derived tables in the `FROM` clause.
1306 ///
1307 /// Example:
1308 /// ```sql
1309 /// SELECT * FROM (mytable);
1310 /// SELECT * FROM ((SELECT 1));
1311 /// SELECT * FROM (mytable) AS alias;
1312 /// ```
1313 ///
1314 /// [Snowflake](https://docs.snowflake.com/en/sql-reference/constructs/from),
1315 /// [SQLite](https://www.sqlite.org/syntax/table-or-subquery.html)
1316 fn supports_parens_around_table_factor(&self) -> bool {
1317 false
1318 }
1319
1320 /// Returns true if this dialect supports `VALUES` as a table factor
1321 /// without requiring parentheses around the entire clause.
1322 ///
1323 /// Example:
1324 /// ```sql
1325 /// SELECT * FROM VALUES (1, 'a'), (2, 'b') AS t (col1, col2);
1326 /// ```
1327 ///
1328 /// [Snowflake](https://docs.snowflake.com/en/sql-reference/constructs/values)
1329 /// [Databricks](https://docs.databricks.com/en/sql/language-manual/sql-ref-syntax-qry-select-values.html)
1330 fn supports_values_as_table_factor(&self) -> bool {
1331 false
1332 }
1333
1334 /// Enables SQLite `$` placeholders containing `$` characters and disables dollar-quoted strings.
1335 fn supports_dollar_placeholder(&self) -> bool {
1336 false
1337 }
1338
1339 /// Returns true if this dialect supports `$` as a prefix for money literals
1340 /// e.g. `SELECT $123.45` (SQL Server)
1341 fn supports_dollar_as_money_prefix(&self) -> bool {
1342 false
1343 }
1344
1345 /// Does the dialect support with clause in create index statement?
1346 /// e.g. `CREATE INDEX idx ON t WITH (key = value, key2)`
1347 fn supports_create_index_with_clause(&self) -> bool {
1348 false
1349 }
1350
1351 /// Does the dialect accept an option named without a value,
1352 /// e.g. `CREATE VIEW v WITH (security_barrier) AS SELECT 1`?
1353 ///
1354 /// [PostgreSQL](https://www.postgresql.org/docs/current/sql-createtable.html#SQL-CREATETABLE-STORAGE-PARAMETERS)
1355 fn supports_sql_option_without_value(&self) -> bool {
1356 false
1357 }
1358
1359 /// Whether `INTERVAL` expressions require units (called "qualifiers" in the ANSI SQL spec) to be specified,
1360 /// e.g. `INTERVAL 1 DAY` vs `INTERVAL 1`.
1361 ///
1362 /// Expressions within intervals (e.g. `INTERVAL '1' + '1' DAY`) are only allowed when units are required.
1363 ///
1364 /// See <https://github.com/sqlparser-rs/sqlparser-rs/pull/1398> for more information.
1365 ///
1366 /// When `true`:
1367 /// * `INTERVAL '1' DAY` is VALID
1368 /// * `INTERVAL 1 + 1 DAY` is VALID
1369 /// * `INTERVAL '1' + '1' DAY` is VALID
1370 /// * `INTERVAL '1'` is INVALID
1371 ///
1372 /// When `false`:
1373 /// * `INTERVAL '1'` is VALID
1374 /// * `INTERVAL '1' DAY` is VALID — unit is not required, but still allowed
1375 /// * `INTERVAL 1 + 1 DAY` is INVALID
1376 fn require_interval_qualifier(&self) -> bool {
1377 false
1378 }
1379
1380 /// Returns true if `kw` can start the qualifier of an `INTERVAL` value, e.g. `DAY` in `INTERVAL '1' DAY`.
1381 fn is_interval_qualifier(&self, kw: Keyword) -> bool {
1382 matches!(
1383 kw,
1384 Keyword::YEAR
1385 | Keyword::YEARS
1386 | Keyword::MONTH
1387 | Keyword::MONTHS
1388 | Keyword::WEEK
1389 | Keyword::WEEKS
1390 | Keyword::DAY
1391 | Keyword::DAYS
1392 | Keyword::HOUR
1393 | Keyword::HOURS
1394 | Keyword::MINUTE
1395 | Keyword::MINUTES
1396 | Keyword::SECOND
1397 | Keyword::SECONDS
1398 | Keyword::CENTURY
1399 | Keyword::DECADE
1400 | Keyword::DOW
1401 | Keyword::DOY
1402 | Keyword::EPOCH
1403 | Keyword::ISODOW
1404 | Keyword::ISOYEAR
1405 | Keyword::JULIAN
1406 | Keyword::MICROSECOND
1407 | Keyword::MICROSECONDS
1408 | Keyword::MILLENIUM
1409 | Keyword::MILLENNIUM
1410 | Keyword::MILLISECOND
1411 | Keyword::MILLISECONDS
1412 | Keyword::NANOSECOND
1413 | Keyword::NANOSECONDS
1414 | Keyword::QUARTER
1415 | Keyword::TIMEZONE
1416 | Keyword::TIMEZONE_HOUR
1417 | Keyword::TIMEZONE_MINUTE
1418 )
1419 }
1420
1421 /// Returns true if the dialect supports `EXPLAIN` statements with utility options
1422 /// e.g. `EXPLAIN (ANALYZE TRUE, BUFFERS TRUE) SELECT * FROM tbl;`
1423 fn supports_explain_with_utility_options(&self) -> bool {
1424 false
1425 }
1426
1427 /// Returns true if the dialect supports `ASC` and `DESC` in column definitions
1428 /// e.g. `CREATE TABLE t (a INT ASC, b INT DESC);`
1429 fn supports_asc_desc_in_column_definition(&self) -> bool {
1430 false
1431 }
1432
1433 /// Returns true if the dialect allows string literals as column names in `CREATE TABLE`.
1434 /// SQLite's grammar rule `nm ::= id | STRING | JOIN_KW` permits this.
1435 fn supports_string_literal_column_names(&self) -> bool {
1436 false
1437 }
1438
1439 /// Returns true if the dialect supports `a!` expressions
1440 fn supports_factorial_operator(&self) -> bool {
1441 false
1442 }
1443
1444 /// Returns true if the dialect supports `<<` and `>>` shift operators.
1445 fn supports_bitwise_shift_operators(&self) -> bool {
1446 false
1447 }
1448
1449 /// Returns true if the dialect supports nested comments
1450 /// e.g. `/* /* nested */ */`
1451 fn supports_nested_comments(&self) -> bool {
1452 false
1453 }
1454
1455 /// Returns true if the dialect supports `#` as the start of a single line comment,
1456 /// e.g. `SELECT 1 # comment`
1457 fn supports_hash_comment(&self) -> bool {
1458 false
1459 }
1460
1461 /// Returns true if the dialect supports inline data for
1462 /// `COPY ... FROM STDIN`, captured verbatim by the tokenizer.
1463 fn supports_copy_from_stdin_data(&self) -> bool {
1464 false
1465 }
1466
1467 /// Returns true if `#` starts a single line comment only when followed by an ASCII
1468 /// space or `!`, so `# comment` and `#! comment` are comments but `#comment` is not.
1469 fn requires_hash_comment_space(&self) -> bool {
1470 false
1471 }
1472
1473 /// Returns true if the dialect supports optimizer hints in multiline comments
1474 /// e.g. `/*!50110 KEY_BLOCK_SIZE = 1024*/`
1475 fn supports_multiline_comment_hints(&self) -> bool {
1476 false
1477 }
1478
1479 /// Returns true if the dialect accepts an unterminated block comment at end of input
1480 /// e.g. `SELECT 1 /* comment`
1481 ///
1482 /// [SQLite](https://www.sqlite.org/lang_comment.html)
1483 fn supports_unterminated_block_comments(&self) -> bool {
1484 false
1485 }
1486
1487 /// Returns true if this dialect supports treating the equals operator `=` within a `SelectItem`
1488 /// as an alias assignment operator, rather than a boolean expression.
1489 /// For example: the following statements are equivalent for such a dialect:
1490 /// ```sql
1491 /// SELECT col_alias = col FROM tbl;
1492 /// SELECT col_alias AS col FROM tbl;
1493 /// ```
1494 fn supports_eq_alias_assignment(&self) -> bool {
1495 false
1496 }
1497
1498 /// Returns true if this dialect supports the `TRY_CONVERT` function
1499 fn supports_try_convert(&self) -> bool {
1500 false
1501 }
1502
1503 /// Returns true if the dialect supports `!a` syntax for boolean `NOT` expressions.
1504 fn supports_bang_not_operator(&self) -> bool {
1505 false
1506 }
1507
1508 /// Returns true if the dialect supports the `LISTEN`, `UNLISTEN` and `NOTIFY` statements
1509 fn supports_listen_notify(&self) -> bool {
1510 false
1511 }
1512
1513 /// Returns true if the dialect supports `EXCLUDE` table constraints, e.g.
1514 /// `EXCLUDE USING gist (c WITH &&)` in `CREATE TABLE`/`ALTER TABLE`.
1515 /// See <https://www.postgresql.org/docs/current/sql-createtable.html#SQL-CREATETABLE-EXCLUDE>.
1516 fn supports_exclude_constraint(&self) -> bool {
1517 false
1518 }
1519
1520 /// Returns true if the dialect supports the `LOAD DATA` statement
1521 fn supports_load_data(&self) -> bool {
1522 false
1523 }
1524
1525 /// Returns true if the dialect supports the `LOAD extension` statement
1526 fn supports_load_extension(&self) -> bool {
1527 false
1528 }
1529
1530 /// Returns true if this dialect expects the `TOP` option
1531 /// before the `ALL`/`DISTINCT` options in a `SELECT` statement.
1532 fn supports_top_before_distinct(&self) -> bool {
1533 false
1534 }
1535
1536 /// Returns true if the dialect supports boolean literals (`true` and `false`).
1537 /// For example, in MSSQL these are treated as identifiers rather than boolean literals.
1538 fn supports_boolean_literals(&self) -> bool {
1539 true
1540 }
1541
1542 /// Returns true if this dialect supports the `LIKE 'pattern'` option in
1543 /// a `SHOW` statement before the `IN` option
1544 fn supports_show_like_before_in(&self) -> bool {
1545 false
1546 }
1547
1548 /// Returns true if this dialect supports the `COMMENT` statement
1549 fn supports_comment_on(&self) -> bool {
1550 false
1551 }
1552
1553 /// Returns true if the dialect supports the `CREATE TABLE SELECT` statement
1554 fn supports_create_table_select(&self) -> bool {
1555 false
1556 }
1557
1558 /// Returns true if this dialect supports `PROC` as an abbreviation for
1559 /// `PROCEDURE` in a `CREATE` statement.
1560 fn supports_create_proc_syntax(&self) -> bool {
1561 false
1562 }
1563
1564 /// Returns true if the dialect accepts a comma-separated list of table-level
1565 /// options placed between the table name and the column-list parenthesis, e.g.
1566 ///
1567 /// ```sql
1568 /// CREATE TABLE foo, NO FALLBACK, NO BEFORE JOURNAL (col INTEGER)
1569 /// ```
1570 fn supports_leading_comma_before_table_options(&self) -> bool {
1571 false
1572 }
1573
1574 /// Returns true if the dialect supports PartiQL for querying semi-structured data
1575 /// <https://partiql.org/index.html>
1576 fn supports_partiql(&self) -> bool {
1577 false
1578 }
1579
1580 /// Returns true if the dialect supports object-unpivot table factors in the FROM clause.
1581 ///
1582 /// Syntax:
1583 /// ```sql
1584 /// SELECT * FROM T UNPIVOT expression AS value_alias [AT attribute_alias]
1585 /// ```
1586 fn supports_unpivot_expr(&self) -> bool {
1587 false
1588 }
1589
1590 /// Returns true if the dialect supports the `CONSTRAINT` keyword without a name
1591 /// in table constraint definitions.
1592 ///
1593 /// Example:
1594 /// ```sql
1595 /// CREATE TABLE t (a INT, CONSTRAINT CHECK (a > 0))
1596 /// ```
1597 ///
1598 /// This is a MySQL extension; the SQL standard requires a name after `CONSTRAINT`.
1599 /// When the name is omitted, the output normalizes to just the constraint type
1600 /// without the `CONSTRAINT` keyword (e.g., `CHECK (a > 0)`).
1601 ///
1602 /// <https://dev.mysql.com/doc/refman/8.4/en/create-table.html>
1603 fn supports_constraint_keyword_without_name(&self) -> bool {
1604 false
1605 }
1606
1607 /// Returns true if the dialect supports the `KEY` keyword as part of
1608 /// column-level constraints in a `CREATE TABLE` statement.
1609 ///
1610 /// When enabled, the parser accepts these MySQL-specific column options:
1611 /// - `UNIQUE [KEY]` — optional `KEY` after `UNIQUE`
1612 /// - `[PRIMARY] KEY` — standalone `KEY` as shorthand for `PRIMARY KEY`
1613 ///
1614 /// <https://dev.mysql.com/doc/refman/8.4/en/create-table.html>
1615 fn supports_key_column_option(&self) -> bool {
1616 false
1617 }
1618
1619 /// Returns true if the dialect supports attaching a table as a partition with
1620 /// `ALTER TABLE ... ATTACH PARTITION name { FOR VALUES ... | DEFAULT }`.
1621 ///
1622 /// <https://www.postgresql.org/docs/current/sql-altertable.html>
1623 fn supports_attach_partition_of(&self) -> bool {
1624 false
1625 }
1626
1627 /// Returns true if the dialect supports detaching a partition with
1628 /// `ALTER TABLE ... DETACH PARTITION name [ CONCURRENTLY | FINALIZE ]`.
1629 ///
1630 /// <https://www.postgresql.org/docs/current/sql-altertable.html>
1631 fn supports_detach_partition_of(&self) -> bool {
1632 false
1633 }
1634
1635 /// Returns true if the dialect supports `OPTIONS ( option 'value' [, ...] )`
1636 /// in a column definition.
1637 ///
1638 /// <https://www.postgresql.org/docs/current/sql-createforeigntable.html>
1639 fn supports_column_generic_options(&self) -> bool {
1640 false
1641 }
1642 /// Returns true if the specified keyword is reserved and cannot be
1643 /// used as an identifier without special handling like quoting.
1644 fn is_reserved_for_identifier(&self, kw: Keyword) -> bool {
1645 keywords::RESERVED_FOR_IDENTIFIER.contains(&kw)
1646 }
1647
1648 /// Returns reserved keywords that may prefix a select item expression
1649 /// e.g. `SELECT CONNECT_BY_ROOT name FROM Tbl2` (Snowflake)
1650 fn get_reserved_keywords_for_select_item_operator(&self) -> &[Keyword] {
1651 &[]
1652 }
1653
1654 /// Returns grantee types that should be treated as identifiers
1655 fn get_reserved_grantees_types(&self) -> &[GranteesType] {
1656 &[]
1657 }
1658
1659 /// Returns true if this dialect supports the `TABLESAMPLE` option
1660 /// before the table alias option. For example:
1661 ///
1662 /// Table sample before alias: `SELECT * FROM tbl AS t TABLESAMPLE (10)`
1663 /// Table sample after alias: `SELECT * FROM tbl TABLESAMPLE (10) AS t`
1664 ///
1665 /// <https://jakewheat.github.io/sql-overview/sql-2016-foundation-grammar.html#_7_6_table_reference>
1666 fn supports_table_sample_before_alias(&self) -> bool {
1667 false
1668 }
1669
1670 /// Returns true if this dialect supports the `INSERT INTO ... SET col1 = 1, ...` syntax.
1671 ///
1672 /// MySQL: <https://dev.mysql.com/doc/refman/8.4/en/insert.html>
1673 fn supports_insert_set(&self) -> bool {
1674 false
1675 }
1676
1677 /// Does the dialect support table function in insertion?
1678 fn supports_insert_table_function(&self) -> bool {
1679 false
1680 }
1681
1682 /// Does the dialect support table queries in insertion?
1683 ///
1684 /// e.g. `SELECT INTO (<query>) ...`
1685 fn supports_insert_table_query(&self) -> bool {
1686 false
1687 }
1688
1689 /// Does the dialect support insert formats, e.g. `INSERT INTO ... FORMAT <format>`
1690 fn supports_insert_format(&self) -> bool {
1691 false
1692 }
1693
1694 /// Returns true if this dialect supports `INSERT INTO t [[AS] alias] ...`.
1695 fn supports_insert_table_alias(&self) -> bool {
1696 false
1697 }
1698
1699 /// Returns true if the dialect accepts `VALUE` as a synonym of `VALUES`.
1700 ///
1701 /// [MySQL](https://dev.mysql.com/doc/refman/8.4/en/insert.html)
1702 fn supports_singular_value_keyword(&self) -> bool {
1703 false
1704 }
1705
1706 /// Returns true if this dialect supports `SET` statements without an explicit
1707 /// assignment operator such as `=`. For example: `SET SHOWPLAN_XML ON`.
1708 fn supports_set_stmt_without_operator(&self) -> bool {
1709 false
1710 }
1711
1712 /// Returns true if the specified keyword should be parsed as a column identifier.
1713 /// See [keywords::RESERVED_FOR_COLUMN_ALIAS]
1714 fn is_column_alias(&self, kw: &Keyword, _parser: &mut Parser) -> bool {
1715 !keywords::RESERVED_FOR_COLUMN_ALIAS.contains(kw)
1716 }
1717
1718 /// Returns true if the specified keyword should be parsed as a select item alias.
1719 /// When explicit is true, the keyword is preceded by an `AS` word. Parser is provided
1720 /// to enable looking ahead if needed.
1721 fn is_select_item_alias(&self, explicit: bool, kw: &Keyword, parser: &mut Parser) -> bool {
1722 explicit || self.is_column_alias(kw, parser)
1723 }
1724
1725 /// Returns true if `OVER` without a following `(` or plain-identifier window name
1726 /// may be used as an implicit column alias rather than starting a window clause.
1727 ///
1728 /// SQLite reads `OVER` as a keyword only when `(` or a name follows, see
1729 /// `analyzeOverKeyword` in [tokenize.c](https://sqlite.org/src/file?name=src/tokenize.c)
1730 fn supports_over_keyword_as_column_alias(&self) -> bool {
1731 false
1732 }
1733
1734 /// Returns true if the specified keyword should be parsed as a table factor identifier.
1735 /// See [keywords::RESERVED_FOR_TABLE_FACTOR]
1736 fn is_table_factor(&self, kw: &Keyword, _parser: &mut Parser) -> bool {
1737 !keywords::RESERVED_FOR_TABLE_FACTOR.contains(kw)
1738 }
1739
1740 /// Returns true if the specified keyword should be parsed as a table factor alias.
1741 /// See [keywords::RESERVED_FOR_TABLE_ALIAS]
1742 fn is_table_alias(&self, kw: &Keyword, _parser: &mut Parser) -> bool {
1743 !keywords::RESERVED_FOR_TABLE_ALIAS.contains(kw)
1744 }
1745
1746 /// Returns true if the specified keyword should be parsed as a table factor alias.
1747 /// When explicit is true, the keyword is preceded by an `AS` word. Parser is provided
1748 /// to enable looking ahead if needed.
1749 fn is_table_factor_alias(&self, explicit: bool, kw: &Keyword, parser: &mut Parser) -> bool {
1750 explicit || self.is_table_alias(kw, parser)
1751 }
1752
1753 /// Returns true if a single-quoted string can name a select item, as in `SELECT 1 AS 'x'`.
1754 /// `explicit` is true when the alias follows `AS`.
1755 ///
1756 /// [MySQL](https://dev.mysql.com/doc/refman/8.4/en/problems-with-alias.html),
1757 /// [SQLite](https://www.sqlite.org/lang_keywords.html)
1758 fn supports_string_literal_column_alias(&self, _explicit: bool) -> bool {
1759 true
1760 }
1761
1762 /// Returns true if a single-quoted string can name a table, as in `FROM t AS 'x'`.
1763 /// `explicit` is true when the alias follows `AS`.
1764 ///
1765 /// [SQLite](https://www.sqlite.org/lang_keywords.html)
1766 fn supports_string_literal_table_alias(&self, _explicit: bool) -> bool {
1767 true
1768 }
1769
1770 /// Returns true if this dialect supports querying historical table data
1771 /// by specifying which version of the data to query.
1772 fn supports_table_versioning(&self) -> bool {
1773 false
1774 }
1775
1776 /// Returns true if this dialect supports the E'...' syntax for string literals
1777 ///
1778 /// Postgres: <https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-STRINGS-ESCAPE>
1779 fn supports_string_escape_constant(&self) -> bool {
1780 false
1781 }
1782
1783 /// Returns true if the dialect supports the table hints in the `FROM` clause.
1784 fn supports_table_hints(&self) -> bool {
1785 false
1786 }
1787
1788 /// Returns true if the dialect supports SQLite's `INDEXED BY` and `NOT INDEXED` index-selection clauses.
1789 ///
1790 /// See <https://www.sqlite.org/lang_indexedby.html>
1791 fn supports_indexed_by(&self) -> bool {
1792 false
1793 }
1794
1795 /// Returns true if this dialect requires a whitespace character after `--` to start a single line comment.
1796 ///
1797 /// MySQL: <https://dev.mysql.com/doc/refman/8.4/en/ansi-diff-comments.html>
1798 /// e.g. UPDATE account SET balance=balance--1
1799 // WHERE account_id=5752 ^^^ will be interpreted as two minus signs instead of a comment
1800 fn requires_single_line_comment_whitespace(&self) -> bool {
1801 false
1802 }
1803
1804 /// Returns true if the dialect supports array type definition with brackets with
1805 /// an optional size. For example:
1806 /// ```CREATE TABLE my_table (arr1 INT[], arr2 INT[3])```
1807 /// ```SELECT x::INT[]```
1808 fn supports_array_typedef_with_brackets(&self) -> bool {
1809 false
1810 }
1811 /// Returns true if the dialect supports geometric types.
1812 ///
1813 /// Postgres: <https://www.postgresql.org/docs/9.5/functions-geometry.html>
1814 /// e.g. @@ circle '((0,0),10)'
1815 fn supports_geometric_types(&self) -> bool {
1816 false
1817 }
1818
1819 /// Returns true if the dialect tokenizes `~~`, `~~*`, `!~~` and `!~~*` as
1820 /// `LIKE`, `ILIKE`, `NOT LIKE` and `NOT ILIKE` pattern-match operators.
1821 ///
1822 /// When false, `~~` is two `~` tokens, e.g. two bitwise-NOT prefixes.
1823 ///
1824 /// [PostgreSQL](https://www.postgresql.org/docs/current/functions-matching.html#FUNCTIONS-LIKE),
1825 /// [Redshift](https://docs.aws.amazon.com/redshift/latest/dg/r_patternmatching_condition_like.html),
1826 /// [DuckDB](https://duckdb.org/docs/current/sql/functions/pattern_matching)
1827 fn supports_tilde_like_match_operator(&self) -> bool {
1828 false
1829 }
1830
1831 /// Returns true if the dialect supports `ORDER BY ALL`.
1832 /// `ALL` which means all columns of the SELECT clause.
1833 ///
1834 /// For example: ```SELECT * FROM addresses ORDER BY ALL;```.
1835 fn supports_order_by_all(&self) -> bool {
1836 false
1837 }
1838
1839 /// Returns true if the dialect supports PostgreSQL-style ordering operators:
1840 /// `ORDER BY expr USING <operator>`.
1841 ///
1842 /// For example: `SELECT * FROM t ORDER BY a USING <`.
1843 fn supports_order_by_using_operator(&self) -> bool {
1844 false
1845 }
1846
1847 /// Returns true if the dialect supports `SET NAMES <charset_name> [COLLATE <collation_name>]`.
1848 ///
1849 /// - [MySQL](https://dev.mysql.com/doc/refman/8.4/en/set-names.html)
1850 /// - [PostgreSQL](https://www.postgresql.org/docs/17/sql-set.html)
1851 ///
1852 /// Note: Postgres doesn't support the `COLLATE` clause, but we permissively parse it anyway.
1853 fn supports_set_names(&self) -> bool {
1854 false
1855 }
1856
1857 /// Returns true if the dialect supports space-separated column options
1858 /// in a `CREATE TABLE` statement. For example:
1859 /// ```sql
1860 /// CREATE TABLE tbl (
1861 /// col INT NOT NULL DEFAULT 0
1862 /// );
1863 /// ```
1864 fn supports_space_separated_column_options(&self) -> bool {
1865 false
1866 }
1867
1868 /// Returns true if the dialect supports the `USING` clause in an `ALTER COLUMN` statement.
1869 /// Example:
1870 /// ```sql
1871 /// ALTER TABLE tbl ALTER COLUMN col SET DATA TYPE <type> USING <exp>`
1872 /// ```
1873 fn supports_alter_column_type_using(&self) -> bool {
1874 false
1875 }
1876
1877 /// Returns true if the dialect supports `ALTER TABLE tbl DROP COLUMN c1, ..., cn`
1878 fn supports_comma_separated_drop_column_list(&self) -> bool {
1879 false
1880 }
1881
1882 /// Returns true if the dialect supports a `FIRST` or `AFTER col` column
1883 /// position in `ALTER TABLE ... ADD | CHANGE | MODIFY COLUMN`.
1884 /// Example:
1885 /// ```sql
1886 /// ALTER TABLE tbl ADD COLUMN c INT AFTER b
1887 /// ```
1888 fn supports_alter_column_position(&self) -> bool {
1889 false
1890 }
1891
1892 /// Returns true if the dialect supports `ALTER TABLE ... ADD [COLUMN] IF NOT EXISTS <col>`.
1893 /// Example:
1894 /// ```sql
1895 /// ALTER TABLE tbl ADD COLUMN IF NOT EXISTS c INT
1896 /// ```
1897 fn supports_add_column_if_not_exists(&self) -> bool {
1898 false
1899 }
1900
1901 /// Returns true if the dialect considers the specified ident as a function
1902 /// that returns an identifier. Typically used to generate identifiers
1903 /// programmatically.
1904 ///
1905 /// - [Snowflake](https://docs.snowflake.com/en/sql-reference/identifier-literal)
1906 fn is_identifier_generating_function_name(
1907 &self,
1908 _ident: &Ident,
1909 _name_parts: &[ObjectNamePart],
1910 ) -> bool {
1911 false
1912 }
1913
1914 /// Returns true if the dialect supports the `x NOTNULL`
1915 /// operator expression.
1916 fn supports_notnull_operator(&self) -> bool {
1917 false
1918 }
1919
1920 /// Returns true if the dialect supports binary `IS` and `IS NOT` operators.
1921 ///
1922 /// Their right operand is any expression, so `IS UNKNOWN`, `IS JSON` and
1923 /// `IS NORMALIZED` are not parsed as predicates.
1924 fn supports_is_operator(&self) -> bool {
1925 false
1926 }
1927
1928 /// Returns true if this dialect allows an optional `SIGNED` suffix after integer data types.
1929 ///
1930 /// Example:
1931 /// ```sql
1932 /// CREATE TABLE t (i INT(20) SIGNED);
1933 /// ```
1934 ///
1935 /// Note that this is canonicalized to `INT(20)`.
1936 fn supports_data_type_signed_suffix(&self) -> bool {
1937 false
1938 }
1939
1940 /// Returns true if this dialect allows an optional `ZEROFILL` suffix after numeric data types.
1941 ///
1942 /// Example:
1943 /// ```sql
1944 /// CREATE TABLE t (i INT(10) UNSIGNED ZEROFILL);
1945 /// ```
1946 ///
1947 /// <https://dev.mysql.com/doc/refman/8.4/en/numeric-type-syntax.html>
1948 fn supports_data_type_zerofill_suffix(&self) -> bool {
1949 false
1950 }
1951
1952 /// Returns true if the dialect supports the `INTERVAL` data type with [Postgres]-style options.
1953 ///
1954 /// Examples:
1955 /// ```sql
1956 /// CREATE TABLE t (i INTERVAL YEAR TO MONTH);
1957 /// SELECT '1 second'::INTERVAL HOUR TO SECOND(3);
1958 /// ```
1959 ///
1960 /// See [`crate::ast::DataType::Interval`] and [`crate::ast::IntervalFields`].
1961 ///
1962 /// [Postgres]: https://www.postgresql.org/docs/17/datatype-datetime.html
1963 fn supports_interval_options(&self) -> bool {
1964 false
1965 }
1966
1967 /// Returns true if the dialect supports specifying which table to copy
1968 /// the schema from inside parenthesis.
1969 ///
1970 /// Not parenthesized:
1971 /// '''sql
1972 /// CREATE TABLE new LIKE old ...
1973 /// '''
1974 /// [Snowflake](https://docs.snowflake.com/en/sql-reference/sql/create-table#label-create-table-like)
1975 /// [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/data-definition-language#create_table_like)
1976 ///
1977 /// Parenthesized:
1978 /// '''sql
1979 /// CREATE TABLE new (LIKE old ...)
1980 /// '''
1981 /// [Redshift](https://docs.aws.amazon.com/redshift/latest/dg/r_CREATE_TABLE_NEW.html)
1982 fn supports_create_table_like_parenthesized(&self) -> bool {
1983 false
1984 }
1985
1986 /// Returns true if the dialect supports `SEMANTIC_VIEW()` table functions.
1987 ///
1988 /// ```sql
1989 /// SELECT * FROM SEMANTIC_VIEW(
1990 /// model_name
1991 /// DIMENSIONS customer.name, customer.region
1992 /// METRICS orders.revenue, orders.count
1993 /// WHERE customer.active = true
1994 /// )
1995 /// ```
1996 fn supports_semantic_view_table_factor(&self) -> bool {
1997 false
1998 }
1999
2000 /// Returns true if this dialect supports Snowflake-style stages in table factors (e.g. `@stage`).
2001 ///
2002 /// [Snowflake](https://docs.snowflake.com/en/user-guide/querying-stage)
2003 fn supports_stages(&self) -> bool {
2004 false
2005 }
2006
2007 /// Support quote delimited string literals, e.g. `Q'{...}'`
2008 ///
2009 /// [Oracle](https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/Literals.html#GUID-1824CBAA-6E16-4921-B2A6-112FB02248DA)
2010 fn supports_quote_delimited_string(&self) -> bool {
2011 false
2012 }
2013
2014 /// Returns `true` if the dialect supports query optimizer hints in the
2015 /// format of single and multi line comments immediately following a
2016 /// `SELECT`, `INSERT`, `REPLACE`, `DELETE`, or `MERGE` keyword.
2017 ///
2018 /// [MySQL](https://dev.mysql.com/doc/refman/8.4/en/optimizer-hints.html)
2019 /// [Oracle](https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/Comments.html#SQLRF-GUID-D316D545-89E2-4D54-977F-FC97815CD62E)
2020 fn supports_comment_optimizer_hint(&self) -> bool {
2021 false
2022 }
2023
2024 /// Returns true if the dialect considers the `&&` operator as a boolean AND operator.
2025 fn supports_double_ampersand_operator(&self) -> bool {
2026 false
2027 }
2028
2029 /// Returns true if the dialect supports casting an expression to a binary type
2030 /// using the `BINARY <expr>` syntax.
2031 fn supports_binary_kw_as_cast(&self) -> bool {
2032 false
2033 }
2034
2035 /// Returns true if this dialect supports the `REPLACE` option in a
2036 /// `SELECT *` wildcard expression.
2037 ///
2038 /// Example:
2039 /// ```sql
2040 /// SELECT * REPLACE (col1 AS col1_alias) FROM table;
2041 /// ```
2042 ///
2043 /// [BigQuery](https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#select_replace)
2044 /// [ClickHouse](https://clickhouse.com/docs/sql-reference/statements/select#replace)
2045 /// [DuckDB](https://duckdb.org/docs/sql/query_syntax/select#replace-clause)
2046 /// [Snowflake](https://docs.snowflake.com/en/sql-reference/sql/select#parameters)
2047 fn supports_select_wildcard_replace(&self) -> bool {
2048 false
2049 }
2050
2051 /// Returns true if this dialect supports the `ILIKE` option in a
2052 /// `SELECT *` wildcard expression.
2053 ///
2054 /// Example:
2055 /// ```sql
2056 /// SELECT * ILIKE '%pattern%' FROM table;
2057 /// ```
2058 ///
2059 /// [Snowflake](https://docs.snowflake.com/en/sql-reference/sql/select#parameters)
2060 fn supports_select_wildcard_ilike(&self) -> bool {
2061 false
2062 }
2063
2064 /// Returns true if this dialect supports the `RENAME` option in a
2065 /// `SELECT *` wildcard expression.
2066 ///
2067 /// Example:
2068 /// ```sql
2069 /// SELECT * RENAME col1 AS col1_alias FROM table;
2070 /// ```
2071 ///
2072 /// [Snowflake](https://docs.snowflake.com/en/sql-reference/sql/select#parameters)
2073 fn supports_select_wildcard_rename(&self) -> bool {
2074 false
2075 }
2076
2077 /// Returns true if this dialect supports aliasing a wildcard select item.
2078 ///
2079 /// Example:
2080 /// ```sql
2081 /// SELECT t.* alias FROM t
2082 /// SELECT t.* AS alias FROM t
2083 /// ```
2084 fn supports_select_wildcard_with_alias(&self) -> bool {
2085 false
2086 }
2087
2088 /// Returns true if this dialect supports the `OPTIMIZE TABLE` statement.
2089 ///
2090 /// Example:
2091 /// ```sql
2092 /// OPTIMIZE TABLE table_name;
2093 /// ```
2094 ///
2095 /// [ClickHouse](https://clickhouse.com/docs/en/sql-reference/statements/optimize)
2096 fn supports_optimize_table(&self) -> bool {
2097 false
2098 }
2099
2100 /// Returns true if this dialect supports the `INSTALL` statement.
2101 ///
2102 /// Example:
2103 /// ```sql
2104 /// INSTALL extension_name;
2105 /// ```
2106 ///
2107 /// [DuckDB](https://duckdb.org/docs/extensions/overview)
2108 fn supports_install(&self) -> bool {
2109 false
2110 }
2111
2112 /// Returns true if this dialect supports the `DETACH` statement.
2113 ///
2114 /// Example:
2115 /// ```sql
2116 /// DETACH DATABASE db_name;
2117 /// ```
2118 ///
2119 /// [DuckDB](https://duckdb.org/docs/sql/statements/attach#detach-syntax)
2120 fn supports_detach(&self) -> bool {
2121 false
2122 }
2123
2124 /// Returns true if this dialect supports the `PREWHERE` clause
2125 /// in `SELECT` statements.
2126 ///
2127 /// Example:
2128 /// ```sql
2129 /// SELECT * FROM table PREWHERE col > 0 WHERE col < 100;
2130 /// ```
2131 ///
2132 /// [ClickHouse](https://clickhouse.com/docs/en/sql-reference/statements/select/prewhere)
2133 fn supports_prewhere(&self) -> bool {
2134 false
2135 }
2136
2137 /// Returns true if this dialect supports the `WITH FILL` clause
2138 /// in `ORDER BY` expressions.
2139 ///
2140 /// Example:
2141 /// ```sql
2142 /// SELECT * FROM table ORDER BY col WITH FILL FROM 1 TO 10 STEP 1;
2143 /// ```
2144 ///
2145 /// [ClickHouse](https://clickhouse.com/docs/en/sql-reference/statements/select/order-by#order-by-expr-with-fill-modifier)
2146 fn supports_with_fill(&self) -> bool {
2147 false
2148 }
2149
2150 /// Returns true if this dialect supports the `LIMIT BY` clause.
2151 ///
2152 /// Example:
2153 /// ```sql
2154 /// SELECT * FROM table LIMIT 10 BY col;
2155 /// ```
2156 ///
2157 /// [ClickHouse](https://clickhouse.com/docs/en/sql-reference/statements/select/limit-by)
2158 fn supports_limit_by(&self) -> bool {
2159 false
2160 }
2161
2162 /// Returns true if this dialect supports the `INTERPOLATE` clause
2163 /// in `ORDER BY` expressions.
2164 ///
2165 /// Example:
2166 /// ```sql
2167 /// SELECT * FROM table ORDER BY col WITH FILL INTERPOLATE (col2 AS col2 + 1);
2168 /// ```
2169 ///
2170 /// [ClickHouse](https://clickhouse.com/docs/en/sql-reference/statements/select/order-by#order-by-expr-with-fill-modifier)
2171 fn supports_interpolate(&self) -> bool {
2172 false
2173 }
2174
2175 /// Returns true if this dialect supports the `SETTINGS` clause.
2176 ///
2177 /// Example:
2178 /// ```sql
2179 /// SELECT * FROM table SETTINGS max_threads = 4;
2180 /// ```
2181 ///
2182 /// [ClickHouse](https://clickhouse.com/docs/en/sql-reference/statements/select#settings-in-select-query)
2183 fn supports_settings(&self) -> bool {
2184 false
2185 }
2186
2187 /// Returns true if this dialect supports the `PARTITION` clause on a table factor,
2188 /// restricting a query to an explicit list of partitions.
2189 ///
2190 /// Example:
2191 /// ```sql
2192 /// SELECT * FROM employees PARTITION (p0, p1)
2193 /// ```
2194 ///
2195 /// [MySQL](https://dev.mysql.com/doc/refman/8.4/en/partitioning-selection.html)
2196 fn supports_table_partitions(&self) -> bool {
2197 false
2198 }
2199
2200 /// Returns true if this dialect supports the `ONLY` and `*` table
2201 /// inheritance markers on a table factor.
2202 ///
2203 /// Example:
2204 /// ```sql
2205 /// SELECT * FROM ONLY parent;
2206 /// SELECT * FROM parent *;
2207 /// ```
2208 ///
2209 /// [PostgreSQL](https://www.postgresql.org/docs/current/sql-select.html#SQL-FROM)
2210 fn supports_table_inheritance_markers(&self) -> bool {
2211 false
2212 }
2213
2214 /// Returns true if this dialect supports the `FORMAT` clause in `SELECT` statements.
2215 ///
2216 /// Example:
2217 /// ```sql
2218 /// SELECT * FROM table FORMAT JSON;
2219 /// ```
2220 ///
2221 /// [ClickHouse](https://clickhouse.com/docs/en/sql-reference/statements/select/format)
2222 fn supports_select_format(&self) -> bool {
2223 false
2224 }
2225
2226 /// Returns true if the dialect supports the two-argument comma-separated
2227 /// form of the `TRIM` function: `TRIM(expr, characters)`.
2228 fn supports_comma_separated_trim(&self) -> bool {
2229 false
2230 }
2231
2232 /// Returns true if the dialect supports the `AS` keyword being
2233 /// optional in a CTE definition. For example:
2234 /// ```sql
2235 /// WITH cte_name (SELECT ...)
2236 /// ```
2237 ///
2238 /// [Databricks](https://docs.databricks.com/aws/en/sql/language-manual/sql-ref-syntax-qry-select-cte)
2239 fn supports_cte_without_as(&self) -> bool {
2240 false
2241 }
2242
2243 /// Returns true if the dialect supports parenthesized multi-column
2244 /// aliases in SELECT items. For example:
2245 /// ```sql
2246 /// SELECT stack(2, 'a', 'b') AS (col1, col2)
2247 /// ```
2248 ///
2249 /// [Spark SQL](https://spark.apache.org/docs/latest/sql-ref-syntax-qry-select.html)
2250 fn supports_select_item_multi_column_alias(&self) -> bool {
2251 false
2252 }
2253
2254 /// Returns true if the dialect supports XML-related expressions
2255 /// such as `xml '<foo/>'` typed strings, XML functions like
2256 /// `XMLCONCAT`, `XMLELEMENT`, etc.
2257 ///
2258 /// When this returns false, `xml` is treated as a regular identifier.
2259 ///
2260 /// [PostgreSQL](https://www.postgresql.org/docs/current/functions-xml.html)
2261 fn supports_xml_expressions(&self) -> bool {
2262 false
2263 }
2264
2265 /// Whether a custom type name may introduce a typed string.
2266 fn is_custom_type_typed_string(&self, _first_keyword: Keyword, _qualified: bool) -> bool {
2267 false
2268 }
2269
2270 /// Returns true if the dialect supports aliased function arguments,
2271 /// e.g. `XMLFOREST(a AS x)` in PostgreSQL.
2272 fn supports_aliased_function_args(&self) -> bool {
2273 false
2274 }
2275
2276 /// Returns true if the dialect supports `USING <format>` in `CREATE TABLE`.
2277 ///
2278 /// Example:
2279 /// ```sql
2280 /// CREATE TABLE t (i INT) USING PARQUET
2281 /// ```
2282 ///
2283 /// [Spark SQL](https://spark.apache.org/docs/latest/sql-ref-syntax-ddl-create-table-datasource.html)
2284 fn supports_create_table_using(&self) -> bool {
2285 false
2286 }
2287
2288 /// Returns true if the dialect treats `LONG` as an alias for `BIGINT`.
2289 ///
2290 /// Example:
2291 /// ```sql
2292 /// CREATE TABLE t (id LONG)
2293 /// ```
2294 ///
2295 /// [Spark SQL](https://spark.apache.org/docs/latest/sql-ref-datatypes.html)
2296 fn supports_long_type_as_bigint(&self) -> bool {
2297 false
2298 }
2299
2300 /// Returns true if the dialect supports `MAP<K, V>` angle-bracket syntax for the MAP data type.
2301 ///
2302 /// Example:
2303 /// ```sql
2304 /// CREATE TABLE t (m MAP<STRING, INT>)
2305 /// ```
2306 ///
2307 /// [Spark SQL](https://spark.apache.org/docs/latest/sql-ref-datatypes.html)
2308 fn supports_map_literal_with_angle_brackets(&self) -> bool {
2309 false
2310 }
2311
2312 /// Returns true if the dialect accepts `==` as an alternative to `=` in `UPDATE SET` assignments.
2313 ///
2314 /// See <https://www.sqlite.org/lang_update.html>
2315 fn supports_double_eq_assignment(&self) -> bool {
2316 false
2317 }
2318
2319 /// Returns true if the dialect supports `CAST(expr AS)` with an empty type name.
2320 ///
2321 /// Example:
2322 /// ```sql
2323 /// SELECT CAST(a AS)
2324 /// ```
2325 ///
2326 /// [SQLite](https://www.sqlite.org/lang_expr.html)
2327 fn supports_cast_empty_data_type_to_unspecified(&self) -> bool {
2328 false
2329 }
2330
2331 /// Returns true if the dialect allows an `ORDER BY` clause inside an aggregate function
2332 /// call with no preceding arguments, e.g. `count(ORDER BY a)`.
2333 ///
2334 /// [SQLite](https://www.sqlite.org/lang_aggfunc.html#aggorderby),
2335 /// [DuckDB](https://duckdb.org/docs/current/sql/functions/aggregates#order-by-clause-in-aggregate-functions)
2336 fn supports_aggregate_order_by_with_empty_args(&self) -> bool {
2337 false
2338 }
2339}
2340
2341/// Operators for which precedence must be defined.
2342///
2343/// Higher number -> higher precedence.
2344/// See expression parsing for how these values are used.
2345#[derive(Debug, Clone, Copy)]
2346pub enum Precedence {
2347 /// Member access operator `.` (highest precedence).
2348 Period,
2349 /// Postgres style type cast `::`.
2350 DoubleColon,
2351 /// Timezone operator (e.g. `AT TIME ZONE`).
2352 AtTz,
2353 /// Multiplication / Division / Modulo operators (`*`, `/`, `%`).
2354 MulDivModOp,
2355 /// Addition / Subtraction (`+`, `-`).
2356 PlusMinus,
2357 /// Bitwise `XOR` operator (`^`).
2358 Xor,
2359 /// Bitwise `AND` operator (`&`).
2360 Ampersand,
2361 /// Bitwise `CARET` (^) for some dialects.
2362 Caret,
2363 /// Bitwise `OR` / pipe operator (`|`).
2364 Pipe,
2365 /// `:` operator for json/variant access.
2366 Colon,
2367 /// `BETWEEN` operator.
2368 Between,
2369 /// Equality operator (`=`).
2370 Eq,
2371 /// Pattern matching (`LIKE`).
2372 Like,
2373 /// `IS` operator (e.g. `IS NULL`).
2374 Is,
2375 /// Other Postgres-specific operators.
2376 PgOther,
2377 /// Unary `NOT`.
2378 UnaryNot,
2379 /// Logical `AND`.
2380 And,
2381 /// Logical `OR` (lowest precedence).
2382 Or,
2383}
2384
2385impl dyn Dialect {
2386 /// Returns true if `self` is the concrete dialect `T`.
2387 #[inline]
2388 pub fn is<T: Dialect>(&self) -> bool {
2389 // borrowed from `Any` implementation
2390 TypeId::of::<T>() == self.dialect()
2391 }
2392}
2393
2394/// Returns the built in [`Dialect`] corresponding to `dialect_name`.
2395///
2396/// See [`Dialect`] documentation for an example.
2397pub fn dialect_from_str(dialect_name: impl AsRef<str>) -> Option<Box<dyn Dialect>> {
2398 let dialect_name = dialect_name.as_ref();
2399 match dialect_name.to_lowercase().as_str() {
2400 "generic" => Some(Box::new(GenericDialect)),
2401 "mysql" => Some(Box::new(MySqlDialect {})),
2402 "postgresql" | "postgres" => Some(Box::new(PostgreSqlDialect {})),
2403 "hive" => Some(Box::new(HiveDialect {})),
2404 "sqlite" => Some(Box::new(SQLiteDialect {})),
2405 "snowflake" => Some(Box::new(SnowflakeDialect)),
2406 "redshift" => Some(Box::new(RedshiftSqlDialect {})),
2407 "mssql" => Some(Box::new(MsSqlDialect {})),
2408 "clickhouse" => Some(Box::new(ClickHouseDialect {})),
2409 "bigquery" => Some(Box::new(BigQueryDialect)),
2410 "ansi" => Some(Box::new(AnsiDialect {})),
2411 "duckdb" => Some(Box::new(DuckDbDialect {})),
2412 "databricks" => Some(Box::new(DatabricksDialect {})),
2413 "spark" | "sparksql" => Some(Box::new(SparkSqlDialect {})),
2414 "oracle" => Some(Box::new(OracleDialect {})),
2415 "teradata" => Some(Box::new(TeradataDialect {})),
2416 _ => None,
2417 }
2418}
2419
2420/// Parse `DIV` using the caller's infix precedence.
2421fn parse_div_infix(
2422 parser: &mut Parser,
2423 expr: &Expr,
2424 precedence: u8,
2425) -> Option<Result<Expr, ParserError>> {
2426 if !parser.parse_keyword(Keyword::DIV) {
2427 return None;
2428 }
2429 Some(
2430 parser
2431 .parse_subexpr(precedence)
2432 .map(|right| Expr::BinaryOp {
2433 left: Box::new(expr.clone()),
2434 op: BinaryOperator::MyIntegerDivide,
2435 right: Box::new(right),
2436 }),
2437 )
2438}
2439
2440#[cfg(test)]
2441mod tests {
2442 use super::*;
2443
2444 struct DialectHolder<'a> {
2445 dialect: &'a dyn Dialect,
2446 }
2447
2448 #[test]
2449 fn test_is_dialect() {
2450 let generic_dialect: &dyn Dialect = &GenericDialect {};
2451 let ansi_dialect: &dyn Dialect = &AnsiDialect {};
2452
2453 let generic_holder = DialectHolder {
2454 dialect: generic_dialect,
2455 };
2456 let ansi_holder = DialectHolder {
2457 dialect: ansi_dialect,
2458 };
2459
2460 assert!(dialect_of!(generic_holder is GenericDialect | AnsiDialect),);
2461 assert!(!dialect_of!(generic_holder is AnsiDialect));
2462 assert!(dialect_of!(ansi_holder is AnsiDialect));
2463 assert!(dialect_of!(ansi_holder is GenericDialect | AnsiDialect));
2464 assert!(!dialect_of!(ansi_holder is GenericDialect | MsSqlDialect));
2465 }
2466
2467 #[test]
2468 fn test_dialect_from_str() {
2469 assert!(parse_dialect("generic").is::<GenericDialect>());
2470 assert!(parse_dialect("mysql").is::<MySqlDialect>());
2471 assert!(parse_dialect("MySql").is::<MySqlDialect>());
2472 assert!(parse_dialect("postgresql").is::<PostgreSqlDialect>());
2473 assert!(parse_dialect("postgres").is::<PostgreSqlDialect>());
2474 assert!(parse_dialect("hive").is::<HiveDialect>());
2475 assert!(parse_dialect("sqlite").is::<SQLiteDialect>());
2476 assert!(parse_dialect("snowflake").is::<SnowflakeDialect>());
2477 assert!(parse_dialect("SnowFlake").is::<SnowflakeDialect>());
2478 assert!(parse_dialect("MsSql").is::<MsSqlDialect>());
2479 assert!(parse_dialect("clickhouse").is::<ClickHouseDialect>());
2480 assert!(parse_dialect("ClickHouse").is::<ClickHouseDialect>());
2481 assert!(parse_dialect("bigquery").is::<BigQueryDialect>());
2482 assert!(parse_dialect("BigQuery").is::<BigQueryDialect>());
2483 assert!(parse_dialect("ansi").is::<AnsiDialect>());
2484 assert!(parse_dialect("ANSI").is::<AnsiDialect>());
2485 assert!(parse_dialect("duckdb").is::<DuckDbDialect>());
2486 assert!(parse_dialect("DuckDb").is::<DuckDbDialect>());
2487 assert!(parse_dialect("DataBricks").is::<DatabricksDialect>());
2488 assert!(parse_dialect("databricks").is::<DatabricksDialect>());
2489 assert!(parse_dialect("teradata").is::<TeradataDialect>());
2490 assert!(parse_dialect("Teradata").is::<TeradataDialect>());
2491
2492 // error cases
2493 assert!(dialect_from_str("Unknown").is_none());
2494 assert!(dialect_from_str("").is_none());
2495 }
2496
2497 fn parse_dialect(v: &str) -> Box<dyn Dialect> {
2498 dialect_from_str(v).unwrap()
2499 }
2500
2501 #[test]
2502 #[cfg(feature = "derive-dialect")]
2503 fn test_dialect_override() {
2504 derive_dialect!(EnhancedGenericDialect, GenericDialect,
2505 preserve_type_id = true,
2506 overrides = {
2507 supports_order_by_all = true,
2508 supports_nested_comments = true,
2509 supports_triple_quoted_string = true,
2510 ordered_bind_placeholder_style = Some(BindPlaceholderStyle::DollarNumbered),
2511 },
2512 );
2513 let dialect = EnhancedGenericDialect::new();
2514
2515 assert!(dialect.supports_order_by_all());
2516 assert!(dialect.supports_nested_comments());
2517 assert!(dialect.supports_triple_quoted_string());
2518 assert_eq!(
2519 dialect.ordered_bind_placeholder_style(),
2520 Some(BindPlaceholderStyle::DollarNumbered)
2521 );
2522
2523 let d: &dyn Dialect = &dialect;
2524 assert!(d.is::<GenericDialect>());
2525 }
2526
2527 #[test]
2528 fn identifier_quote_style() {
2529 let tests: Vec<(&dyn Dialect, &str, Option<char>)> = vec![
2530 (&AnsiDialect {}, "id", Some('"')),
2531 (&BigQueryDialect {}, "id", Some('`')),
2532 (&ClickHouseDialect {}, "id", Some('`')),
2533 (&DatabricksDialect {}, "id", Some('`')),
2534 (&DuckDbDialect {}, "id", Some('"')),
2535 (&GenericDialect {}, "id", None),
2536 (&HiveDialect {}, "id", Some('`')),
2537 (&MsSqlDialect {}, "id", Some('[')),
2538 (&MySqlDialect {}, "id", Some('`')),
2539 (&OracleDialect {}, "id", Some('"')),
2540 (&PostgreSqlDialect {}, "id", Some('"')),
2541 (&RedshiftSqlDialect {}, "id", Some('"')),
2542 (&SnowflakeDialect {}, "id", Some('"')),
2543 (&SQLiteDialect {}, "id", Some('`')),
2544 (&SparkSqlDialect {}, "id", Some('`')),
2545 (&TeradataDialect {}, "id", Some('"')),
2546 ];
2547
2548 for (dialect, ident, expected) in tests {
2549 let actual = dialect.identifier_quote_style(ident);
2550
2551 assert_eq!(actual, expected);
2552 }
2553 }
2554
2555 #[test]
2556 fn ordered_bind_placeholder_style() {
2557 let tests: Vec<(&dyn Dialect, Option<BindPlaceholderStyle>)> = vec![
2558 (&GenericDialect {}, None),
2559 (&MySqlDialect {}, Some(BindPlaceholderStyle::QuestionMark)),
2560 (
2561 &PostgreSqlDialect {},
2562 Some(BindPlaceholderStyle::DollarNumbered),
2563 ),
2564 (
2565 &RedshiftSqlDialect {},
2566 Some(BindPlaceholderStyle::DollarNumbered),
2567 ),
2568 (&SQLiteDialect {}, Some(BindPlaceholderStyle::QuestionMark)),
2569 ];
2570
2571 for (dialect, expected) in tests {
2572 assert_eq!(dialect.ordered_bind_placeholder_style(), expected);
2573 }
2574 }
2575
2576 #[test]
2577 fn parse_with_wrapped_dialect() {
2578 /// Wrapper for a dialect. In a real-world example, this wrapper
2579 /// would tweak the behavior of the dialect. For the test case,
2580 /// it wraps all methods unaltered.
2581 #[derive(Debug)]
2582 struct WrappedDialect(MySqlDialect);
2583
2584 impl Dialect for WrappedDialect {
2585 fn dialect(&self) -> std::any::TypeId {
2586 self.0.dialect()
2587 }
2588
2589 fn is_identifier_start(&self, ch: char) -> bool {
2590 self.0.is_identifier_start(ch)
2591 }
2592
2593 fn is_delimited_identifier_start(&self, ch: char) -> bool {
2594 self.0.is_delimited_identifier_start(ch)
2595 }
2596
2597 fn is_nested_delimited_identifier_start(&self, ch: char) -> bool {
2598 self.0.is_nested_delimited_identifier_start(ch)
2599 }
2600
2601 fn peek_nested_delimited_identifier_quotes(
2602 &self,
2603 chars: std::iter::Peekable<std::str::Chars<'_>>,
2604 ) -> Option<(char, Option<char>)> {
2605 self.0.peek_nested_delimited_identifier_quotes(chars)
2606 }
2607
2608 fn identifier_quote_style(&self, identifier: &str) -> Option<char> {
2609 self.0.identifier_quote_style(identifier)
2610 }
2611
2612 fn ordered_bind_placeholder_style(&self) -> Option<BindPlaceholderStyle> {
2613 self.0.ordered_bind_placeholder_style()
2614 }
2615
2616 fn supports_string_literal_backslash_escape(&self) -> bool {
2617 self.0.supports_string_literal_backslash_escape()
2618 }
2619
2620 fn supports_filter_during_aggregation(&self) -> bool {
2621 self.0.supports_filter_during_aggregation()
2622 }
2623
2624 fn supports_within_after_array_aggregation(&self) -> bool {
2625 self.0.supports_within_after_array_aggregation()
2626 }
2627
2628 fn supports_group_by_expr(&self) -> bool {
2629 self.0.supports_group_by_expr()
2630 }
2631
2632 fn supports_in_empty_list(&self) -> bool {
2633 self.0.supports_in_empty_list()
2634 }
2635
2636 fn supports_in_unparenthesized_expr(&self) -> bool {
2637 self.0.supports_in_unparenthesized_expr()
2638 }
2639
2640 fn convert_type_before_value(&self) -> bool {
2641 self.0.convert_type_before_value()
2642 }
2643
2644 fn parse_prefix(
2645 &self,
2646 parser: &mut sqlparser::parser::Parser,
2647 ) -> Option<Result<Expr, sqlparser::parser::ParserError>> {
2648 self.0.parse_prefix(parser)
2649 }
2650
2651 fn parse_infix(
2652 &self,
2653 parser: &mut sqlparser::parser::Parser,
2654 expr: &Expr,
2655 precedence: u8,
2656 ) -> Option<Result<Expr, sqlparser::parser::ParserError>> {
2657 self.0.parse_infix(parser, expr, precedence)
2658 }
2659
2660 fn get_next_precedence(
2661 &self,
2662 parser: &sqlparser::parser::Parser,
2663 ) -> Option<Result<u8, sqlparser::parser::ParserError>> {
2664 self.0.get_next_precedence(parser)
2665 }
2666
2667 fn parse_statement(
2668 &self,
2669 parser: &mut sqlparser::parser::Parser,
2670 ) -> Option<Result<Statement, sqlparser::parser::ParserError>> {
2671 self.0.parse_statement(parser)
2672 }
2673
2674 fn is_identifier_part(&self, ch: char) -> bool {
2675 self.0.is_identifier_part(ch)
2676 }
2677 }
2678
2679 let statement = r"SELECT 'Wayne\'s World'";
2680 let res1 = Parser::parse_sql(&MySqlDialect {}, statement);
2681 let res2 = Parser::parse_sql(&WrappedDialect(MySqlDialect {}), statement);
2682 assert_eq!(
2683 WrappedDialect(MySqlDialect {}).ordered_bind_placeholder_style(),
2684 Some(BindPlaceholderStyle::QuestionMark)
2685 );
2686 assert_eq!(res1.unwrap(), res2.unwrap());
2687 }
2688}