Skip to main content

sqlparser/dialect/
postgresql.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18// Licensed under the Apache License, Version 2.0 (the "License");
19// you may not use this file except in compliance with the License.
20// You may obtain a copy of the License at
21//
22// http://www.apache.org/licenses/LICENSE-2.0
23//
24// Unless required by applicable law or agreed to in writing, software
25// distributed under the License is distributed on an "AS IS" BASIS,
26// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
27// See the License for the specific language governing permissions and
28// limitations under the License.
29use log::debug;
30
31use crate::dialect::{BindPlaceholderStyle, Dialect, Precedence};
32use crate::keywords::Keyword;
33use crate::parser::{Parser, ParserError};
34use crate::tokenizer::Token;
35
36use super::keywords::{self, RESERVED_FOR_IDENTIFIER};
37
38/// Keywords in [`keywords::RESERVED_FOR_TABLE_ALIAS`] because of other dialects, yet are safe for aliasing in PostgreSQL.
39/// See <https://www.postgresql.org/docs/current/sql-keywords-appendix.html>.
40const RESERVED_EXCLUSIONS_FOR_TABLE_ALIAS: &[Keyword] = &[
41    Keyword::CLUSTER,
42    Keyword::DISTRIBUTE,
43    Keyword::EXPLAIN,
44    Keyword::MINUS,
45    Keyword::SAMPLE,
46    Keyword::SORT,
47    Keyword::START,
48    Keyword::TOP,
49    Keyword::VIEW,
50];
51
52const RESERVED_TYPE_NAME_KEYWORDS: &[Keyword] = &[
53    Keyword::ALL,
54    Keyword::ANALYZE,
55    Keyword::AND,
56    Keyword::ANY,
57    Keyword::ARRAY,
58    Keyword::AS,
59    Keyword::ASC,
60    Keyword::ASYMMETRIC,
61    Keyword::BOTH,
62    Keyword::CASE,
63    Keyword::CAST,
64    Keyword::CHECK,
65    Keyword::COLLATE,
66    Keyword::COLUMN,
67    Keyword::CONSTRAINT,
68    Keyword::CREATE,
69    Keyword::CURRENT_CATALOG,
70    Keyword::CURRENT_DATE,
71    Keyword::CURRENT_ROLE,
72    Keyword::CURRENT_TIME,
73    Keyword::CURRENT_TIMESTAMP,
74    Keyword::CURRENT_USER,
75    Keyword::DEFAULT,
76    Keyword::DEFERRABLE,
77    Keyword::DESC,
78    Keyword::DISTINCT,
79    Keyword::DO,
80    Keyword::ELSE,
81    Keyword::END,
82    Keyword::EXCEPT,
83    Keyword::FALSE,
84    Keyword::FETCH,
85    Keyword::FOR,
86    Keyword::FOREIGN,
87    Keyword::FROM,
88    Keyword::GRANT,
89    Keyword::GROUP,
90    Keyword::HAVING,
91    Keyword::IN,
92    Keyword::INITIALLY,
93    Keyword::INTERSECT,
94    Keyword::INTO,
95    Keyword::LATERAL,
96    Keyword::LEADING,
97    Keyword::LIMIT,
98    Keyword::LOCALTIME,
99    Keyword::LOCALTIMESTAMP,
100    Keyword::NOT,
101    Keyword::NULL,
102    Keyword::OFFSET,
103    Keyword::ON,
104    Keyword::ONLY,
105    Keyword::OR,
106    Keyword::ORDER,
107    Keyword::PLACING,
108    Keyword::PRIMARY,
109    Keyword::REFERENCES,
110    Keyword::RETURNING,
111    Keyword::SELECT,
112    Keyword::SESSION_USER,
113    Keyword::SOME,
114    Keyword::SYMMETRIC,
115    Keyword::SYSTEM_USER,
116    Keyword::TABLE,
117    Keyword::THEN,
118    Keyword::TO,
119    Keyword::TRAILING,
120    Keyword::TRUE,
121    Keyword::UNION,
122    Keyword::UNIQUE,
123    Keyword::USER,
124    Keyword::USING,
125    Keyword::VARIADIC,
126    Keyword::WHEN,
127    Keyword::WHERE,
128    Keyword::WINDOW,
129    Keyword::WITH,
130];
131
132const COL_NAME_KEYWORDS: &[Keyword] = &[
133    Keyword::BETWEEN,
134    Keyword::BIGINT,
135    Keyword::BIT,
136    Keyword::BOOLEAN,
137    Keyword::CHAR,
138    Keyword::CHARACTER,
139    Keyword::COALESCE,
140    Keyword::DEC,
141    Keyword::DECIMAL,
142    Keyword::EXISTS,
143    Keyword::EXTRACT,
144    Keyword::FLOAT,
145    Keyword::GROUPING,
146    Keyword::INOUT,
147    Keyword::INT,
148    Keyword::INTEGER,
149    Keyword::INTERVAL,
150    Keyword::JSON,
151    Keyword::JSON_TABLE,
152    Keyword::LEAST,
153    Keyword::NATIONAL,
154    Keyword::NCHAR,
155    Keyword::NONE,
156    Keyword::NORMALIZE,
157    Keyword::NULLIF,
158    Keyword::NUMERIC,
159    Keyword::OUT,
160    Keyword::OVERLAY,
161    Keyword::POSITION,
162    Keyword::PRECISION,
163    Keyword::REAL,
164    Keyword::ROW,
165    Keyword::SETOF,
166    Keyword::SMALLINT,
167    Keyword::SUBSTRING,
168    Keyword::TIME,
169    Keyword::TIMESTAMP,
170    Keyword::TREAT,
171    Keyword::TRIM,
172    Keyword::VALUES,
173    Keyword::VARCHAR,
174    Keyword::XMLNAMESPACES,
175    Keyword::XMLTABLE,
176];
177
178const TYPE_FUNC_NAME_KEYWORDS: &[Keyword] = &[
179    Keyword::AUTHORIZATION,
180    Keyword::BINARY,
181    Keyword::COLLATION,
182    Keyword::CONCURRENTLY,
183    Keyword::CROSS,
184    Keyword::CURRENT_SCHEMA,
185    Keyword::FREEZE,
186    Keyword::FULL,
187    Keyword::ILIKE,
188    Keyword::INNER,
189    Keyword::IS,
190    Keyword::JOIN,
191    Keyword::LEFT,
192    Keyword::LIKE,
193    Keyword::NATURAL,
194    Keyword::NOTNULL,
195    Keyword::OUTER,
196    Keyword::OVERLAPS,
197    Keyword::RIGHT,
198    Keyword::SIMILAR,
199    Keyword::TABLESAMPLE,
200    Keyword::VERBOSE,
201];
202
203/// A [`Dialect`] for [PostgreSQL](https://www.postgresql.org/)
204#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
205#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
206pub struct PostgreSqlDialect {}
207
208const PERIOD_PREC: u8 = 200;
209const DOUBLE_COLON_PREC: u8 = 140;
210const BRACKET_PREC: u8 = 130;
211const COLLATE_PREC: u8 = 120;
212const AT_TZ_PREC: u8 = 110;
213const CARET_PREC: u8 = 100;
214const MUL_DIV_MOD_OP_PREC: u8 = 90;
215const PLUS_MINUS_PREC: u8 = 80;
216// there's no XOR operator in PostgreSQL, but support it here to avoid breaking tests
217const XOR_PREC: u8 = 75;
218const PG_OTHER_PREC: u8 = 70;
219const BETWEEN_LIKE_PREC: u8 = 60;
220const EQ_PREC: u8 = 50;
221const IS_PREC: u8 = 40;
222const NOT_PREC: u8 = 30;
223const AND_PREC: u8 = 20;
224const OR_PREC: u8 = 10;
225
226impl Dialect for PostgreSqlDialect {
227    fn supports_cte_materialization(&self) -> bool {
228        true
229    }
230
231    fn identifier_quote_style(&self, _identifier: &str) -> Option<char> {
232        Some('"')
233    }
234
235    fn ordered_bind_placeholder_style(&self) -> Option<BindPlaceholderStyle> {
236        Some(BindPlaceholderStyle::DollarNumbered)
237    }
238
239    fn is_delimited_identifier_start(&self, ch: char) -> bool {
240        ch == '"' // Postgres does not support backticks to quote identifiers
241    }
242
243    fn is_identifier_start(&self, ch: char) -> bool {
244        ch.is_alphabetic() || ch == '_' ||
245        // PostgreSQL implements Unicode characters in identifiers.
246        !ch.is_ascii()
247    }
248
249    fn is_identifier_part(&self, ch: char) -> bool {
250        ch.is_alphabetic() || ch.is_ascii_digit() || ch == '$' || ch == '_'  ||
251        // PostgreSQL implements Unicode characters in identifiers.
252        !ch.is_ascii()
253    }
254
255    fn supports_unicode_string_literal(&self) -> bool {
256        true
257    }
258
259    fn is_reserved_for_identifier(&self, kw: Keyword) -> bool {
260        if matches!(kw, Keyword::INTERVAL) {
261            false
262        } else {
263            RESERVED_FOR_IDENTIFIER.contains(&kw)
264        }
265    }
266
267    fn is_table_alias(&self, kw: &Keyword, _parser: &mut Parser) -> bool {
268        !keywords::RESERVED_FOR_TABLE_ALIAS.contains(kw)
269            || RESERVED_EXCLUSIONS_FOR_TABLE_ALIAS.contains(kw)
270    }
271
272    /// Aliases are identifiers, see `output_name` and `alias` in
273    /// <https://www.postgresql.org/docs/current/sql-select.html>
274    fn supports_string_literal_column_alias(&self, _explicit: bool) -> bool {
275        false
276    }
277
278    /// Aliases are identifiers, see `alias` in
279    /// <https://www.postgresql.org/docs/current/sql-select.html>
280    fn supports_string_literal_table_alias(&self, _explicit: bool) -> bool {
281        false
282    }
283
284    /// See <https://www.postgresql.org/docs/current/sql-createoperator.html>
285    fn is_custom_operator_part(&self, ch: char) -> bool {
286        matches!(
287            ch,
288            '+' | '-'
289                | '*'
290                | '/'
291                | '<'
292                | '>'
293                | '='
294                | '~'
295                | '!'
296                | '@'
297                | '#'
298                | '%'
299                | '^'
300                | '&'
301                | '|'
302                | '`'
303                | '?'
304        )
305    }
306
307    fn get_next_precedence(&self, parser: &Parser) -> Option<Result<u8, ParserError>> {
308        let token = parser.peek_token_ref();
309        debug!("get_next_precedence() {token:?}");
310
311        // we only return some custom value here when the behaviour (not merely the numeric value) differs
312        // from the default implementation
313        match &token.token {
314            Token::Word(w)
315                if w.keyword == Keyword::COLLATE && !parser.in_column_definition_state() =>
316            {
317                Some(Ok(COLLATE_PREC))
318            }
319            Token::LBracket => Some(Ok(BRACKET_PREC)),
320            Token::Arrow
321            | Token::LongArrow
322            | Token::HashArrow
323            | Token::HashLongArrow
324            | Token::AtArrow
325            | Token::ArrowAt
326            | Token::HashMinus
327            | Token::AtQuestion
328            | Token::AtAt
329            | Token::Question
330            | Token::QuestionAnd
331            | Token::QuestionPipe
332            | Token::ExclamationMark
333            | Token::Overlap
334            | Token::CaretAt
335            | Token::StringConcat
336            | Token::Sharp
337            | Token::ShiftRight
338            | Token::ShiftLeft
339            | Token::CustomBinaryOperator(_) => Some(Ok(PG_OTHER_PREC)),
340            // lowest prec to prevent it from turning into a binary op
341            Token::Colon | Token::Assignment => Some(Ok(self.prec_unknown())),
342            _ => None,
343        }
344    }
345
346    fn supports_filter_during_aggregation(&self) -> bool {
347        true
348    }
349
350    fn supports_group_by_expr(&self) -> bool {
351        true
352    }
353
354    fn supports_drop_group(&self) -> bool {
355        true
356    }
357
358    fn supports_alter_user_as_alter_role(&self) -> bool {
359        true
360    }
361
362    fn supports_create_group(&self) -> bool {
363        true
364    }
365
366    fn supports_create_role_if_not_exists(&self) -> bool {
367        false
368    }
369
370    fn prec_value(&self, prec: Precedence) -> u8 {
371        match prec {
372            Precedence::Period => PERIOD_PREC,
373            Precedence::DoubleColon => DOUBLE_COLON_PREC,
374            Precedence::AtTz => AT_TZ_PREC,
375            Precedence::MulDivModOp => MUL_DIV_MOD_OP_PREC,
376            Precedence::PlusMinus => PLUS_MINUS_PREC,
377            Precedence::Xor => XOR_PREC,
378            Precedence::Ampersand => PG_OTHER_PREC,
379            Precedence::Caret => CARET_PREC,
380            Precedence::Pipe => PG_OTHER_PREC,
381            Precedence::Colon => PG_OTHER_PREC,
382            Precedence::Between => BETWEEN_LIKE_PREC,
383            Precedence::Eq => EQ_PREC,
384            Precedence::Like => BETWEEN_LIKE_PREC,
385            Precedence::Is => IS_PREC,
386            Precedence::PgOther => PG_OTHER_PREC,
387            Precedence::UnaryNot => NOT_PREC,
388            Precedence::And => AND_PREC,
389            Precedence::Or => OR_PREC,
390        }
391    }
392
393    fn allow_extract_custom(&self) -> bool {
394        true
395    }
396
397    fn allow_extract_single_quotes(&self) -> bool {
398        true
399    }
400
401    fn supports_create_index_with_clause(&self) -> bool {
402        true
403    }
404
405    fn supports_sql_option_without_value(&self) -> bool {
406        true
407    }
408
409    /// see <https://www.postgresql.org/docs/current/sql-explain.html>
410    fn supports_explain_with_utility_options(&self) -> bool {
411        true
412    }
413
414    /// see <https://www.postgresql.org/docs/current/sql-listen.html>
415    /// see <https://www.postgresql.org/docs/current/sql-unlisten.html>
416    /// see <https://www.postgresql.org/docs/current/sql-notify.html>
417    fn supports_listen_notify(&self) -> bool {
418        true
419    }
420
421    /// see <https://www.postgresql.org/docs/current/sql-createtable.html#SQL-CREATETABLE-EXCLUDE>
422    fn supports_exclude_constraint(&self) -> bool {
423        true
424    }
425
426    /// see <https://www.postgresql.org/docs/13/functions-math.html>
427    fn supports_factorial_operator(&self) -> bool {
428        true
429    }
430
431    fn supports_bitwise_shift_operators(&self) -> bool {
432        true
433    }
434
435    fn supports_tilde_like_match_operator(&self) -> bool {
436        true
437    }
438
439    fn supports_comparison_in_between_low_bound(&self) -> bool {
440        true
441    }
442
443    /// see <https://www.postgresql.org/docs/current/sql-comment.html>
444    fn supports_comment_on(&self) -> bool {
445        true
446    }
447
448    /// See <https://www.postgresql.org/docs/current/sql-load.html>
449    fn supports_load_extension(&self) -> bool {
450        true
451    }
452
453    /// See <https://www.postgresql.org/docs/current/functions-json.html>
454    ///
455    /// Required to support the colon in:
456    /// ```sql
457    /// SELECT json_object('a': 'b')
458    /// ```
459    fn supports_named_fn_args_with_colon_operator(&self) -> bool {
460        true
461    }
462
463    /// See <https://www.postgresql.org/docs/current/functions-json.html>
464    ///
465    /// Required to support the label in:
466    /// ```sql
467    /// SELECT json_object('label': 'value')
468    /// ```
469    fn supports_named_fn_args_with_expr_name(&self) -> bool {
470        true
471    }
472
473    /// See <https://www.postgresql.org/docs/current/sql-syntax-calling-funcs.html#SQL-SYNTAX-CALLING-FUNCS-NAMED>
474    fn supports_named_fn_args_with_assignment_operator(&self) -> bool {
475        true
476    }
477
478    /// Return true if the dialect supports empty projections in SELECT statements
479    ///
480    /// Example
481    /// ```sql
482    /// SELECT from table_name
483    /// ```
484    ///
485    /// The target list is optional in <https://www.postgresql.org/docs/current/sql-select.html>
486    fn supports_empty_projections(&self) -> bool {
487        true
488    }
489
490    fn supports_nested_comments(&self) -> bool {
491        true
492    }
493
494    fn supports_copy_from_stdin_data(&self) -> bool {
495        true
496    }
497
498    fn supports_string_escape_constant(&self) -> bool {
499        true
500    }
501
502    fn supports_numeric_literal_underscores(&self) -> bool {
503        true
504    }
505
506    /// See: <https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-CONSTANTS-NUMERIC>
507    fn supports_non_decimal_integer_literals(&self) -> bool {
508        true
509    }
510
511    /// See: <https://www.postgresql.org/docs/current/arrays.html#ARRAYS-DECLARATION>
512    fn supports_array_typedef_with_brackets(&self) -> bool {
513        true
514    }
515
516    fn supports_geometric_types(&self) -> bool {
517        true
518    }
519
520    fn supports_order_by_using_operator(&self) -> bool {
521        true
522    }
523
524    fn supports_set_names(&self) -> bool {
525        true
526    }
527
528    fn supports_alter_column_type_using(&self) -> bool {
529        true
530    }
531
532    /// PostgreSQL supports right-deep join chains: `t0 JOIN t1 JOIN t2 ON c1 ON c2`
533    /// See: <https://www.postgresql.org/docs/current/queries-table-expressions.html#QUERIES-JOIN>
534    fn supports_left_associative_joins_without_parens(&self) -> bool {
535        false
536    }
537
538    /// Postgres supports `NOTNULL` as an alias for `IS NOT NULL`
539    /// See: <https://www.postgresql.org/docs/17/functions-comparison.html>
540    fn supports_notnull_operator(&self) -> bool {
541        true
542    }
543
544    /// [Postgres] supports optional field and precision options for `INTERVAL` data type.
545    ///
546    /// [Postgres]: https://www.postgresql.org/docs/17/datatype-datetime.html
547    fn supports_interval_options(&self) -> bool {
548        true
549    }
550
551    /// See `opt_interval` in <https://github.com/postgres/postgres/blob/master/src/backend/parser/gram.y>
552    fn is_interval_qualifier(&self, kw: Keyword) -> bool {
553        matches!(
554            kw,
555            Keyword::YEAR
556                | Keyword::MONTH
557                | Keyword::DAY
558                | Keyword::HOUR
559                | Keyword::MINUTE
560                | Keyword::SECOND
561        )
562    }
563
564    fn supports_insert_table_alias(&self) -> bool {
565        true
566    }
567
568    fn supports_create_table_like_parenthesized(&self) -> bool {
569        true
570    }
571
572    fn supports_select_wildcard_with_alias(&self) -> bool {
573        true
574    }
575
576    fn supports_comma_separated_trim(&self) -> bool {
577        true
578    }
579
580    fn supports_xml_expressions(&self) -> bool {
581        true
582    }
583
584    /// See <https://www.postgresql.org/docs/current/sql-keywords-appendix.html>.
585    fn is_custom_type_typed_string(&self, first_keyword: Keyword, qualified: bool) -> bool {
586        let not_a_type_name = if qualified {
587            TYPE_FUNC_NAME_KEYWORDS
588        } else {
589            COL_NAME_KEYWORDS
590        };
591        !RESERVED_TYPE_NAME_KEYWORDS.contains(&first_keyword)
592            && !not_a_type_name.contains(&first_keyword)
593    }
594
595    fn supports_aliased_function_args(&self) -> bool {
596        true
597    }
598
599    /// Postgres supports query optimizer hints via the `pg_hint_plan` extension,
600    /// using the same comment-prefixed-with-`+` syntax as MySQL and Oracle.
601    ///
602    /// See <https://github.com/ossc-db/pg_hint_plan>
603    fn supports_comment_optimizer_hint(&self) -> bool {
604        true
605    }
606
607    /// See <https://www.postgresql.org/docs/current/sql-altertable.html>
608    fn supports_add_column_if_not_exists(&self) -> bool {
609        true
610    }
611
612    /// See <https://www.postgresql.org/docs/current/sql-altertable.html>
613    fn supports_attach_partition_of(&self) -> bool {
614        true
615    }
616
617    /// See <https://www.postgresql.org/docs/current/sql-altertable.html>
618    fn supports_detach_partition_of(&self) -> bool {
619        true
620    }
621
622    /// See <https://www.postgresql.org/docs/current/sql-select.html#SQL-FROM>
623    fn supports_table_inheritance_markers(&self) -> bool {
624        true
625    }
626
627    /// See <https://www.postgresql.org/docs/current/sql-createforeigntable.html>
628    fn supports_column_generic_options(&self) -> bool {
629        true
630    }
631}