Skip to main content

sqlparser/dialect/
redshift.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
18use crate::dialect::Dialect;
19use crate::keywords::Keyword;
20use core::iter::Peekable;
21use core::str::Chars;
22
23use super::keywords::RESERVED_FOR_IDENTIFIER;
24use super::PostgreSqlDialect;
25
26/// A [`Dialect`] for [RedShift](https://aws.amazon.com/redshift/)
27#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
28#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
29pub struct RedshiftSqlDialect {}
30
31// In most cases the redshift dialect is identical to [`PostgresSqlDialect`].
32//
33// Notable differences:
34// 1. Redshift treats brackets `[` and `]` differently. For example, `SQL SELECT a[1][2] FROM b`
35// in the Postgres dialect, the query will be parsed as an array, while in the Redshift dialect it will
36// be a json path
37impl Dialect for RedshiftSqlDialect {
38    /// Determine if a character starts a potential nested quoted identifier.
39    /// Example: RedShift supports the following quote styles to all mean the same thing:
40    /// ```sql
41    /// SELECT 1 AS foo;
42    /// SELECT 1 AS "foo";
43    /// SELECT 1 AS [foo];
44    /// SELECT 1 AS ["foo"];
45    /// ```
46    fn is_nested_delimited_identifier_start(&self, ch: char) -> bool {
47        ch == '['
48    }
49
50    /// Only applicable whenever [`Self::is_nested_delimited_identifier_start`] returns true
51    /// If the next sequence of tokens potentially represent a nested identifier, then this method
52    /// returns a tuple containing the outer quote style, and if present, the inner (nested) quote style.
53    ///
54    /// Example (Redshift):
55    /// ```text
56    /// `["foo"]` => Some(`[`, Some(`"`))
57    /// `[foo]` => Some(`[`, None)
58    /// `[0]` => None
59    /// `"foo"` => None
60    /// ```
61    fn peek_nested_delimited_identifier_quotes(
62        &self,
63        mut chars: Peekable<Chars<'_>>,
64    ) -> Option<(char, Option<char>)> {
65        if chars.peek() != Some(&'[') {
66            return None;
67        }
68
69        chars.next();
70
71        let mut not_white_chars = chars.skip_while(|ch| ch.is_whitespace()).peekable();
72
73        if let Some(&ch) = not_white_chars.peek() {
74            if ch == '"' {
75                return Some(('[', Some('"')));
76            }
77            if self.is_identifier_start(ch) {
78                return Some(('[', None));
79            }
80        }
81
82        None
83    }
84
85    fn is_identifier_start(&self, ch: char) -> bool {
86        // UTF-8 multibyte characters are supported in identifiers via the PostgreSqlDialect.
87        // https://docs.aws.amazon.com/redshift/latest/dg/r_names.html
88        PostgreSqlDialect {}.is_identifier_start(ch) || ch == '#'
89    }
90
91    fn is_identifier_part(&self, ch: char) -> bool {
92        // UTF-8 multibyte characters are supported in identifiers via the PostgreSqlDialect.
93        // https://docs.aws.amazon.com/redshift/latest/dg/r_names.html
94        PostgreSqlDialect {}.is_identifier_part(ch) || ch == '#'
95    }
96
97    /// See <https://docs.aws.amazon.com/redshift/latest/dg/r_names.html>
98    fn identifier_quote_style(&self, _identifier: &str) -> Option<char> {
99        Some('"')
100    }
101
102    /// redshift has `CONVERT(type, value)` instead of `CONVERT(value, type)`
103    /// <https://docs.aws.amazon.com/redshift/latest/dg/r_CONVERT_function.html>
104    fn convert_type_before_value(&self) -> bool {
105        true
106    }
107
108    fn supports_connect_by(&self) -> bool {
109        true
110    }
111
112    /// Redshift expects the `TOP` option before the `ALL/DISTINCT` option:
113    /// <https://docs.aws.amazon.com/redshift/latest/dg/r_SELECT_list.html#r_SELECT_list-parameters>
114    fn supports_top_before_distinct(&self) -> bool {
115        true
116    }
117
118    /// Redshift supports PartiQL: <https://docs.aws.amazon.com/redshift/latest/dg/super-overview.html>
119    fn supports_partiql(&self) -> bool {
120        true
121    }
122
123    fn supports_unpivot_expr(&self) -> bool {
124        true
125    }
126
127    fn supports_string_escape_constant(&self) -> bool {
128        true
129    }
130
131    fn supports_geometric_types(&self) -> bool {
132        true
133    }
134
135    fn supports_bitwise_shift_operators(&self) -> bool {
136        true
137    }
138
139    fn supports_array_typedef_with_brackets(&self) -> bool {
140        true
141    }
142
143    fn allow_extract_single_quotes(&self) -> bool {
144        true
145    }
146
147    fn supports_string_literal_backslash_escape(&self) -> bool {
148        true
149    }
150
151    fn supports_select_wildcard_exclude(&self) -> bool {
152        true
153    }
154
155    /// Redshift supports aliasing wildcard expressions:
156    /// <https://docs.aws.amazon.com/redshift/latest/dg/r_SELECT_list.html>
157    fn supports_select_wildcard_with_alias(&self) -> bool {
158        true
159    }
160
161    fn supports_left_associative_joins_without_parens(&self) -> bool {
162        false
163    }
164
165    fn supports_select_exclude(&self) -> bool {
166        true
167    }
168
169    fn supports_create_table_like_parenthesized(&self) -> bool {
170        true
171    }
172
173    fn supports_string_literal_concatenation_with_newline(&self) -> bool {
174        true
175    }
176
177    fn supports_window_function_null_treatment_arg(&self) -> bool {
178        true
179    }
180
181    /// `INTERVAL` is listed as reserved in Redshift docs but the actual parser allows it as an
182    /// identifier, consistent with pgsql.
183    fn is_reserved_for_identifier(&self, kw: Keyword) -> bool {
184        if matches!(kw, Keyword::INTERVAL) {
185            false
186        } else {
187            RESERVED_FOR_IDENTIFIER.contains(&kw)
188        }
189    }
190}