Skip to content
Open
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
18 changes: 16 additions & 2 deletions src/parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15115,7 +15115,8 @@ impl<'a> Parser<'a> {

let mut top_before_distinct = false;
let mut top = None;
if self.dialect.supports_top_before_distinct() && self.parse_keyword(Keyword::TOP) {
if self.dialect.supports_top_before_distinct() && self.peek_top_clause() {
self.expect_keyword(Keyword::TOP)?;
top = Some(self.parse_top()?);
top_before_distinct = true;
}
Expand All @@ -15126,7 +15127,8 @@ impl<'a> Parser<'a> {
self.parse_all_or_distinct()?
};

if !self.dialect.supports_top_before_distinct() && self.parse_keyword(Keyword::TOP) {
if !self.dialect.supports_top_before_distinct() && self.peek_top_clause() {
self.expect_keyword(Keyword::TOP)?;
top = Some(self.parse_top()?);
}

Expand Down Expand Up @@ -19386,6 +19388,18 @@ impl<'a> Parser<'a> {
Ok(InterpolateExpr { column, expr })
}

/// Returns true if the parser is positioned at a `TOP` clause, i.e. the
/// `TOP` keyword followed by `(` or a number. When `TOP` is followed by
/// anything else it is an ordinary identifier (column, alias, or table
/// name), not the row-limit clause parsed by [`Self::parse_top`].
fn peek_top_clause(&self) -> bool {
self.peek_keyword(Keyword::TOP)
&& matches!(
self.peek_nth_token_ref(1).token,
Token::LParen | Token::Number(_, _)
)
}

/// Parse a TOP clause, MSSQL equivalent of LIMIT,
/// that follows after `SELECT [DISTINCT]`.
pub fn parse_top(&mut self) -> Result<Top, ParserError> {
Expand Down
17 changes: 17 additions & 0 deletions tests/sqlparser_common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15376,6 +15376,23 @@ fn test_select_top() {
dialects.verified_stmt("SELECT TOP 3 DISTINCT a, b, c FROM tbl");
}

#[test]
fn parse_top_as_identifier() {
// `TOP` is only the row-limit clause when followed by `(` or a number.
// Otherwise it is an ordinary identifier and must remain usable as a
// column name, alias, or table name. Covers both the `TOP`-before-distinct
// dialects and the general case.
let dialects = all_dialects_where(|d| d.supports_top_before_distinct());
dialects.verified_stmt("SELECT top FROM tbl");
dialects.verified_stmt("SELECT top, bottom FROM tbl");
dialects.verified_stmt("SELECT top.val FROM tbl AS top");

let dialects = all_dialects_where(|d| !d.supports_top_before_distinct());
dialects.verified_stmt("SELECT top FROM tbl");
dialects.verified_stmt("SELECT top, bottom FROM tbl");
dialects.verified_stmt("SELECT top.val FROM tbl AS top");
}

#[test]
fn parse_bang_not() {
let dialects = all_dialects_where(|d| d.supports_bang_not_operator());
Expand Down