diff --git a/fuzz/fuzz_seeds/postgres_3050_fetch_optional.sql b/fuzz/fuzz_seeds/postgres_3050_fetch_optional.sql new file mode 100644 index 0000000000..301068557e --- /dev/null +++ b/fuzz/fuzz_seeds/postgres_3050_fetch_optional.sql @@ -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 diff --git a/src/parser/mod.rs b/src/parser/mod.rs index 8bed885c8b..731408e8fc 100644 --- a/src/parser/mod.rs +++ b/src/parser/mod.rs @@ -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 { - 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 @@ -8938,19 +8963,18 @@ 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) { @@ -8958,26 +8982,24 @@ impl<'a> Parser<'a> { 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()?; @@ -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, 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 { + 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 { let object_type = if self.parse_keyword(Keyword::ALL) { diff --git a/tests/sqlparser_postgres.rs b/tests/sqlparser_postgres.rs index 1cd2009e89..e59cbe9c41 100644 --- a/tests/sqlparser_postgres.rs +++ b/tests/sqlparser_postgres.rs @@ -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", + "{sql}" + ); + } + assert_eq!( + pg().parse_sql_statements("FETCH ABSOLUTE c") + .unwrap_err() + .to_string(), + "sql parser error: Expected: a concrete value, found: c" + ); +} + +#[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" + ); +}