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::{BindPlaceholderStyle, 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    fn ordered_bind_placeholder_style(&self) -> Option<BindPlaceholderStyle> {
39        Some(BindPlaceholderStyle::DollarNumbered)
40    }
41
42    /// Determine if a character starts a potential nested quoted identifier.
43    /// Example: RedShift supports the following quote styles to all mean the same thing:
44    /// ```sql
45    /// SELECT 1 AS foo;
46    /// SELECT 1 AS "foo";
47    /// SELECT 1 AS [foo];
48    /// SELECT 1 AS ["foo"];
49    /// ```
50    fn is_nested_delimited_identifier_start(&self, ch: char) -> bool {
51        ch == '['
52    }
53
54    /// Only applicable whenever [`Self::is_nested_delimited_identifier_start`] returns true
55    /// If the next sequence of tokens potentially represent a nested identifier, then this method
56    /// returns a tuple containing the outer quote style, and if present, the inner (nested) quote style.
57    ///
58    /// Example (Redshift):
59    /// ```text
60    /// `["foo"]` => Some(`[`, Some(`"`))
61    /// `[foo]` => Some(`[`, None)
62    /// `[0]` => None
63    /// `"foo"` => None
64    /// ```
65    fn peek_nested_delimited_identifier_quotes(
66        &self,
67        mut chars: Peekable<Chars<'_>>,
68    ) -> Option<(char, Option<char>)> {
69        if chars.peek() != Some(&'[') {
70            return None;
71        }
72
73        chars.next();
74
75        let mut not_white_chars = chars.skip_while(|ch| ch.is_whitespace()).peekable();
76
77        if let Some(&ch) = not_white_chars.peek() {
78            if ch == '"' {
79                return Some(('[', Some('"')));
80            }
81            if self.is_identifier_start(ch) {
82                return Some(('[', None));
83            }
84        }
85
86        None
87    }
88
89    fn is_identifier_start(&self, ch: char) -> bool {
90        // UTF-8 multibyte characters are supported in identifiers via the PostgreSqlDialect.
91        // https://docs.aws.amazon.com/redshift/latest/dg/r_names.html
92        PostgreSqlDialect {}.is_identifier_start(ch) || ch == '#'
93    }
94
95    fn is_identifier_part(&self, ch: char) -> bool {
96        // UTF-8 multibyte characters are supported in identifiers via the PostgreSqlDialect.
97        // https://docs.aws.amazon.com/redshift/latest/dg/r_names.html
98        PostgreSqlDialect {}.is_identifier_part(ch) || ch == '#'
99    }
100
101    /// See <https://docs.aws.amazon.com/redshift/latest/dg/r_names.html>
102    fn identifier_quote_style(&self, _identifier: &str) -> Option<char> {
103        Some('"')
104    }
105
106    /// redshift has `CONVERT(type, value)` instead of `CONVERT(value, type)`
107    /// <https://docs.aws.amazon.com/redshift/latest/dg/r_CONVERT_function.html>
108    fn convert_type_before_value(&self) -> bool {
109        true
110    }
111
112    fn supports_connect_by(&self) -> bool {
113        true
114    }
115
116    /// Redshift expects the `TOP` option before the `ALL/DISTINCT` option:
117    /// <https://docs.aws.amazon.com/redshift/latest/dg/r_SELECT_list.html#r_SELECT_list-parameters>
118    fn supports_top_before_distinct(&self) -> bool {
119        true
120    }
121
122    /// Redshift supports PartiQL: <https://docs.aws.amazon.com/redshift/latest/dg/super-overview.html>
123    fn supports_partiql(&self) -> bool {
124        true
125    }
126
127    fn supports_unpivot_expr(&self) -> bool {
128        true
129    }
130
131    fn supports_string_escape_constant(&self) -> bool {
132        true
133    }
134
135    /// See <https://docs.aws.amazon.com/redshift/latest/dg/r_APPROXIMATE_PERCENTILE_DISC.html>
136    fn supports_approximate_percentile_disc(&self) -> bool {
137        true
138    }
139
140    fn supports_geometric_types(&self) -> bool {
141        true
142    }
143
144    fn supports_bitwise_shift_operators(&self) -> bool {
145        true
146    }
147
148    fn supports_tilde_like_match_operator(&self) -> bool {
149        true
150    }
151
152    fn supports_array_typedef_with_brackets(&self) -> bool {
153        true
154    }
155
156    fn allow_extract_single_quotes(&self) -> bool {
157        true
158    }
159
160    fn supports_string_literal_backslash_escape(&self) -> bool {
161        true
162    }
163
164    fn supports_select_wildcard_exclude(&self) -> bool {
165        true
166    }
167
168    /// Redshift supports aliasing wildcard expressions:
169    /// <https://docs.aws.amazon.com/redshift/latest/dg/r_SELECT_list.html>
170    fn supports_select_wildcard_with_alias(&self) -> bool {
171        true
172    }
173
174    fn supports_left_associative_joins_without_parens(&self) -> bool {
175        false
176    }
177
178    fn supports_select_exclude(&self) -> bool {
179        true
180    }
181
182    fn supports_create_table_like_parenthesized(&self) -> bool {
183        true
184    }
185
186    fn supports_string_literal_concatenation_with_newline(&self) -> bool {
187        true
188    }
189
190    fn supports_window_function_null_treatment_arg(&self) -> bool {
191        true
192    }
193
194    /// `INTERVAL` is listed as reserved in Redshift docs but the actual parser allows it as an
195    /// identifier, consistent with pgsql.
196    fn is_reserved_for_identifier(&self, kw: Keyword) -> bool {
197        if matches!(kw, Keyword::INTERVAL) {
198            false
199        } else {
200            RESERVED_FOR_IDENTIFIER.contains(&kw)
201        }
202    }
203}