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
8 changes: 8 additions & 0 deletions fuzz/fuzz_seeds/postgres_3050_fetch_optional.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
FETCH c;
FETCH FROM c;
FETCH IN c;
FETCH NEXT;
FETCH FORWARD c;
FETCH BACKWARD FROM c;
FETCH -1 FROM c;
FETCH RELATIVE +5 c
96 changes: 79 additions & 17 deletions src/parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8926,9 +8926,34 @@ impl<'a> Parser<'a> {
})
}

/// Parse `FETCH [direction] { FROM | IN } cursor INTO target;` statement.
/// Parse `FETCH [direction] [FROM | IN] cursor [INTO target]` statement.
pub fn parse_fetch_statement(&mut self) -> Result<Statement, ParserError> {
let direction = if self.parse_keyword(Keyword::NEXT) {
// Direction keywords other than ALL are unreserved in PostgreSQL, so a
// lone one with nothing after it (`FETCH NEXT;`) is the cursor name.
let direction_is_cursor = matches!(
self.peek_token_ref().token,
Token::Word(Word {
keyword: Keyword::NEXT
| Keyword::PRIOR
| Keyword::FIRST
| Keyword::LAST
| Keyword::ABSOLUTE
| Keyword::RELATIVE
| Keyword::FORWARD
| Keyword::BACKWARD,
..
})
) && matches!(
self.peek_nth_token_ref(1).token,
Token::EOF
| Token::SemiColon
| Token::Word(Word {
keyword: Keyword::INTO,
..
})
);

let direction = if direction_is_cursor || self.parse_keyword(Keyword::NEXT) {
FetchDirection::Next
} else if self.parse_keyword(Keyword::PRIOR) {
FetchDirection::Prior
Expand All @@ -8938,46 +8963,43 @@ impl<'a> Parser<'a> {
FetchDirection::Last
} else if self.parse_keyword(Keyword::ABSOLUTE) {
FetchDirection::Absolute {
limit: self.parse_number_value()?,
limit: self.parse_fetch_count()?,
}
} else if self.parse_keyword(Keyword::RELATIVE) {
FetchDirection::Relative {
limit: self.parse_number_value()?,
limit: self.parse_fetch_count()?,
}
} else if self.parse_keyword(Keyword::FORWARD) {
if self.parse_keyword(Keyword::ALL) {
FetchDirection::ForwardAll
} else {
FetchDirection::Forward {
// TODO: Support optional
limit: Some(self.parse_number_value()?),
limit: self.maybe_parse_fetch_count()?,
}
}
} else if self.parse_keyword(Keyword::BACKWARD) {
if self.parse_keyword(Keyword::ALL) {
FetchDirection::BackwardAll
} else {
FetchDirection::Backward {
// TODO: Support optional
limit: Some(self.parse_number_value()?),
limit: self.maybe_parse_fetch_count()?,
}
}
} else if self.parse_keyword(Keyword::ALL) {
FetchDirection::All
} else if let Some(limit) = self.maybe_parse_fetch_count()? {
FetchDirection::Count { limit }
} else {
FetchDirection::Count {
limit: self.parse_number_value()?,
}
// Omitting the direction is the same as specifying NEXT.
FetchDirection::Next
};

let position = if self.peek_keyword(Keyword::FROM) {
self.expect_keyword(Keyword::FROM)?;
FetchPosition::From
} else if self.peek_keyword(Keyword::IN) {
self.expect_keyword(Keyword::IN)?;
// FROM and IN are interchangeable and may both be omitted.
let position = if self.parse_keyword(Keyword::IN) {
FetchPosition::In
} else {
return parser_err!("Expected FROM or IN", self.peek_token_ref().span.start);
let _ = self.parse_keyword(Keyword::FROM);
FetchPosition::From
};

let name = self.parse_identifier()?;
Expand All @@ -8996,6 +9018,46 @@ impl<'a> Parser<'a> {
})
}

/// Parse the row count of a `FETCH` direction when one follows, such as
/// the `5` in `FETCH FORWARD 5 FROM cursor_name`.
fn maybe_parse_fetch_count(&mut self) -> Result<Option<ValueWithSpan>, ParserError> {
match self.peek_token_ref().token {
Token::Number(..) | Token::Plus | Token::Minus | Token::Placeholder(_) => {
Ok(Some(self.parse_fetch_count()?))
}
_ => Ok(None),
}
}

/// Parse the row count of a `FETCH` direction, which may be signed: a
/// negative count moves the cursor the other way.
fn parse_fetch_count(&mut self) -> Result<ValueWithSpan, ParserError> {
let sign_span = self.peek_token_ref().span;
let negative = self.consume_token(&Token::Minus);
let signed = negative || self.consume_token(&Token::Plus);
let count = self.parse_number_value()?;
if !signed {
return Ok(count);
}
match count.value {
Value::Number(n, long) => {
let value = if negative {
Self::parse(format!("-{n}"), sign_span.start)?
} else {
n
};
Ok(ValueWithSpan {
value: Value::Number(value, long),
span: sign_span.union(&count.span),
})
}
_ => {
self.prev_token();
self.expected_ref("literal number", self.peek_token_ref())
}
}
}

/// Parse a `DISCARD` statement.
pub fn parse_discard(&mut self) -> Result<Statement, ParserError> {
let object_type = if self.parse_keyword(Keyword::ALL) {
Expand Down
98 changes: 98 additions & 0 deletions tests/sqlparser_postgres.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14597,3 +14597,101 @@ fn parse_alter_column_set_storage() {
);
}
}

#[test]
fn parse_fetch_optional_direction_and_position() {
pg_and_generic().one_statement_parses_to("FETCH c", "FETCH NEXT FROM c");
pg_and_generic().one_statement_parses_to("FETCH FROM c", "FETCH NEXT FROM c");
pg_and_generic().one_statement_parses_to("FETCH IN c", "FETCH NEXT IN c");
pg_and_generic().one_statement_parses_to("FETCH NEXT c", "FETCH NEXT FROM c");
pg_and_generic().one_statement_parses_to("FETCH PRIOR c", "FETCH PRIOR FROM c");
pg_and_generic().one_statement_parses_to("FETCH FIRST c", "FETCH FIRST FROM c");
pg_and_generic().one_statement_parses_to("FETCH LAST c", "FETCH LAST FROM c");
pg_and_generic().one_statement_parses_to("FETCH ALL c", "FETCH ALL FROM c");
pg_and_generic().one_statement_parses_to("FETCH 5 c", "FETCH 5 FROM c");
pg_and_generic().one_statement_parses_to("FETCH FORWARD c", "FETCH FORWARD FROM c");
pg_and_generic().one_statement_parses_to("FETCH FORWARD ALL c", "FETCH FORWARD ALL FROM c");
pg_and_generic().one_statement_parses_to("FETCH BACKWARD c", "FETCH BACKWARD FROM c");
pg_and_generic().one_statement_parses_to("FETCH BACKWARD 5 c", "FETCH BACKWARD 5 FROM c");
pg_and_generic().one_statement_parses_to("FETCH BACKWARD ALL c", "FETCH BACKWARD ALL FROM c");
pg_and_generic().one_statement_parses_to(
"FETCH c INTO \"new_table\"",
"FETCH NEXT FROM c INTO \"new_table\"",
);
pg_and_generic().verified_stmt("FETCH FORWARD FROM c");
pg_and_generic().verified_stmt("FETCH BACKWARD IN c");
pg_and_generic().verified_stmt("FETCH $1 FROM c");

// Unreserved direction keywords are valid bare cursor names.
for kw in [
"NEXT", "PRIOR", "FIRST", "LAST", "ABSOLUTE", "RELATIVE", "FORWARD", "BACKWARD",
] {
pg_and_generic()
.one_statement_parses_to(&format!("FETCH {kw}"), &format!("FETCH NEXT FROM {kw}"));
pg_and_generic()
.one_statement_parses_to(&format!("FETCH {kw};"), &format!("FETCH NEXT FROM {kw}"));
}
pg_and_generic().one_statement_parses_to("FETCH NEXT INTO t", "FETCH NEXT FROM NEXT INTO t");
pg_and_generic().one_statement_parses_to("FETCH NEXT NEXT", "FETCH NEXT FROM NEXT");
pg_and_generic().one_statement_parses_to("FETCH FORWARD NEXT", "FETCH FORWARD FROM NEXT");

match pg_and_generic().verified_stmt("FETCH NEXT FROM \"C\"") {
Statement::Fetch { name, .. } => assert_eq!(name, Ident::with_quote('"', "C")),
stmt => panic!("Expected Fetch, got: {stmt:?}"),
}

for sql in [
"FETCH",
"FETCH FROM",
"FETCH IN",
"FETCH ALL",
"FETCH FORWARD ALL",
"FETCH BACKWARD ALL",
] {
assert_eq!(
pg().parse_sql_statements(sql).unwrap_err().to_string(),
"sql parser error: Expected: identifier, found: EOF",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

use the typed error

"{sql}"
);
}
assert_eq!(
pg().parse_sql_statements("FETCH ABSOLUTE c")
.unwrap_err()
.to_string(),
"sql parser error: Expected: a concrete value, found: c"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

use the error type

);
}

#[test]
fn parse_fetch_signed_count() {
pg_and_generic().verified_stmt("FETCH -1 FROM c");
pg_and_generic().verified_stmt("FETCH ABSOLUTE -1 FROM c");
pg_and_generic().verified_stmt("FETCH RELATIVE -5 IN c");
pg_and_generic().verified_stmt("FETCH FORWARD -5 FROM c");
pg_and_generic().verified_stmt("FETCH BACKWARD -5 FROM c");
pg_and_generic().one_statement_parses_to("FETCH +5 FROM c", "FETCH 5 FROM c");
pg_and_generic().one_statement_parses_to("FETCH -1 c", "FETCH -1 FROM c");
pg_and_generic().one_statement_parses_to("FETCH - 5 FROM c", "FETCH -5 FROM c");
pg_and_generic().one_statement_parses_to("FETCH + 5 c", "FETCH 5 FROM c");

match pg_and_generic().verified_stmt("FETCH RELATIVE -5 FROM c") {
Statement::Fetch {
direction: FetchDirection::Relative { limit },
..
} => assert_eq!(limit.value, number("-5")),
stmt => panic!("Expected Fetch, got: {stmt:?}"),
}

assert_eq!(
pg().parse_sql_statements("FETCH - FROM c")
.unwrap_err()
.to_string(),
"sql parser error: Expected: a concrete value, found: FROM"
);
assert_eq!(
pg().parse_sql_statements("FETCH -$1 FROM c")
.unwrap_err()
.to_string(),
"sql parser error: Expected: literal number, found: $1"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

use the typed error, maybe a for loop for these few repeated patterns

);
}
Loading