Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion src/dialect/postgresql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,21 @@ use crate::keywords::Keyword;
use crate::parser::{Parser, ParserError};
use crate::tokenizer::Token;

use super::keywords::RESERVED_FOR_IDENTIFIER;
use super::keywords::{self, RESERVED_FOR_IDENTIFIER};

/// Keywords in [`keywords::RESERVED_FOR_TABLE_ALIAS`] because of other dialects, yet are safe for aliasing in PostgreSQL.
/// See <https://www.postgresql.org/docs/current/sql-keywords-appendix.html>.
const RESERVED_EXCLUSIONS_FOR_TABLE_ALIAS: &[Keyword] = &[
Keyword::CLUSTER,
Keyword::DISTRIBUTE,
Keyword::EXPLAIN,
Keyword::MINUS,
Keyword::SAMPLE,
Keyword::SORT,
Keyword::START,
Keyword::TOP,
Keyword::VIEW,
];

/// A [`Dialect`] for [PostgreSQL](https://www.postgresql.org/)
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
Expand Down Expand Up @@ -91,6 +105,11 @@ impl Dialect for PostgreSqlDialect {
}
}

fn is_table_alias(&self, kw: &Keyword, _parser: &mut Parser) -> bool {
!keywords::RESERVED_FOR_TABLE_ALIAS.contains(kw)
|| RESERVED_EXCLUSIONS_FOR_TABLE_ALIAS.contains(kw)
}

/// See <https://www.postgresql.org/docs/current/sql-createoperator.html>
fn is_custom_operator_part(&self, ch: char) -> bool {
matches!(
Expand Down
23 changes: 23 additions & 0 deletions tests/sqlparser_postgres.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9852,3 +9852,26 @@ fn parse_alter_table_constraint_check_no_inherit() {
}
pg_and_generic().verified_stmt("ALTER TABLE docs ADD CONSTRAINT c CHECK (id > 0) NO INHERIT");
}

#[test]
fn parse_non_reserved_keywords_as_table_alias() {
// PostgreSQL allows these keywords as explicit table aliases.
for kw in [
"cluster",
"distribute",
"explain",
"minus",
"sample",
"sort",
"start",
"top",
"view",
] {
pg().verified_stmt(&format!(
"SELECT * FROM tbl_name AS {kw} JOIN tbl_name_2 ON {kw}.id = tbl_name_2.id"
));
pg().verified_stmt(&format!(
"SELECT * FROM tbl_name {kw} JOIN tbl_name_2 ON {kw}.id = tbl_name_2.id"
));
}
}
Loading