PostgreSQL: Parse nested ROLLUP, CUBE and GROUPING SETS inside GROUPING SETS
diff --git a/src/ast/mod.rs b/src/ast/mod.rs index 653a358..0bf7598 100644 --- a/src/ast/mod.rs +++ b/src/ast/mod.rs
@@ -2141,7 +2141,18 @@ for set in sets { write!(f, "{sep}")?; sep = ", "; - write!(f, "({})", display_comma_separated(set))?; + if set.len() == 1 + && matches!( + &set[0], + Expr::Rollup(_) | Expr::Cube(_) | Expr::GroupingSets(_) + ) + { + // A nested construct is a grouping set on its own, unlike the + // parenthesized expression lists it may contain + write!(f, "{}", set[0])?; + } else { + write!(f, "({})", display_comma_separated(set))?; + } } write!(f, ")") }
diff --git a/src/parser/mod.rs b/src/parser/mod.rs index 1b35306..bc58033 100644 --- a/src/parser/mod.rs +++ b/src/parser/mod.rs
@@ -2808,12 +2808,43 @@ } } + /// Parse one element of a `GROUPING SETS` list. + /// + /// An element is a parenthesized expression list, a nested `ROLLUP`, `CUBE`, or + /// `GROUPING SETS` construct, or a single bare expression. + fn parse_grouping_set_element(&mut self) -> Result<Vec<Expr>, ParserError> { + if self.peek_token_ref().token == Token::LParen { + self.parse_tuple(true, true) + } else if self.dialect.supports_group_by_expr() && self.peek_grouping_set_construct() { + Ok(vec![self.parse_group_by_expr()?]) + } else { + Ok(vec![self.parse_expr()?]) + } + } + + /// Returns true when the next tokens start a nested `ROLLUP`, `CUBE`, or `GROUPING SETS` construct. + fn peek_grouping_set_construct(&self) -> bool { + let Token::Word(word) = &self.peek_token_ref().token else { + return false; + }; + match word.keyword { + // Without the open paren, `rollup` and `cube` are unreserved + // identifiers in PostgreSQL, e.g. `GROUP BY GROUPING SETS (rollup)` + Keyword::ROLLUP | Keyword::CUBE => self.peek_nth_token_ref(1).token == Token::LParen, + Keyword::GROUPING => matches!( + &self.peek_nth_token_ref(1).token, + Token::Word(next) if next.keyword == Keyword::SETS + ), + _ => false, + } + } + /// Parse a group by expr. Group by expr can be one of group sets, roll up, cube, or simple expr. fn parse_group_by_expr(&mut self) -> Result<Expr, ParserError> { if self.dialect.supports_group_by_expr() { if self.parse_keywords(&[Keyword::GROUPING, Keyword::SETS]) { self.expect_token(&Token::LParen)?; - let result = self.parse_comma_separated(|p| p.parse_tuple(true, true))?; + let result = self.parse_comma_separated(Parser::parse_grouping_set_element)?; self.expect_token(&Token::RParen)?; Ok(Expr::GroupingSets(result)) } else if self.parse_keyword(Keyword::CUBE) { @@ -14186,13 +14217,7 @@ } if self.parse_keywords(&[Keyword::GROUPING, Keyword::SETS]) { self.expect_token(&Token::LParen)?; - let result = self.parse_comma_separated(|p| { - if p.peek_token_ref().token == Token::LParen { - p.parse_tuple(true, true) - } else { - Ok(vec![p.parse_expr()?]) - } - })?; + let result = self.parse_comma_separated(Parser::parse_grouping_set_element)?; self.expect_token(&Token::RParen)?; modifiers.push(GroupByWithModifier::GroupingSets(Expr::GroupingSets( result,
diff --git a/tests/sqlparser_common.rs b/tests/sqlparser_common.rs index db7786d..3f71fbc 100644 --- a/tests/sqlparser_common.rs +++ b/tests/sqlparser_common.rs
@@ -22908,3 +22908,68 @@ ); } } + +#[test] +fn test_group_by_grouping_sets_nested_constructs() { + all_dialects_where(|d| d.supports_group_by_expr()).one_statement_parses_to( + "SELECT a, b FROM t GROUP BY GROUPING SETS (rollup(a, b), a)", + "SELECT a, b FROM t GROUP BY GROUPING SETS (ROLLUP (a, b), (a))", + ); + + all_dialects_where(|d| d.supports_group_by_expr()).one_statement_parses_to( + "SELECT a, b FROM t GROUP BY GROUPING SETS (cube(a), (a))", + "SELECT a, b FROM t GROUP BY GROUPING SETS (CUBE (a), (a))", + ); + + all_dialects_where(|d| d.supports_group_by_expr()).verified_stmt( + "SELECT a, b, c FROM t GROUP BY GROUPING SETS (ROLLUP (a), CUBE (b), GROUPING SETS ((c)))", + ); + + // Without the open paren, `rollup` is an unreserved identifier, not a ROLLUP construct + all_dialects_where(|d| d.supports_group_by_expr()).one_statement_parses_to( + "SELECT a FROM t GROUP BY GROUPING SETS (rollup, (a))", + "SELECT a FROM t GROUP BY GROUPING SETS ((rollup), (a))", + ); +} + +#[test] +fn test_group_by_grouping_sets_nested_constructs_ast() { + let sql = "SELECT a, b FROM t GROUP BY GROUPING SETS (rollup(a, b), (a), ())"; + let canonical = "SELECT a, b FROM t GROUP BY GROUPING SETS (ROLLUP (a, b), (a), ())"; + match all_dialects_where(|d| d.supports_group_by_expr()).one_statement_parses_to(sql, canonical) + { + Statement::Query(query) => { + let group_by = &query.body.as_select().unwrap().group_by; + assert_eq!( + group_by, + &GroupByExpr::Expressions( + vec![Expr::GroupingSets(vec![ + vec![Expr::Rollup(vec![ + vec![Expr::Identifier(Ident::new("a"))], + vec![Expr::Identifier(Ident::new("b"))] + ])], + vec![Expr::Identifier(Ident::new("a"))], + vec![] + ])], + vec![] + ) + ); + } + _ => unreachable!(), + } +} + +#[test] +fn test_group_by_grouping_sets_nested_constructs_errors() { + for sql in [ + "SELECT a FROM t GROUP BY GROUPING SETS (rollup(), (a))", + "SELECT a FROM t GROUP BY GROUPING SETS (cube(), (a))", + ] { + assert!( + all_dialects_where(|d| d.supports_group_by_expr()) + .parse_sql_statements(sql) + .is_err(), + "{sql}" + ); + } +}