Skip to content

Commit

Permalink
Allow to use () as the GROUP BY nothing for PostgreSQL
Browse files Browse the repository at this point in the history
Currently, PostgreSQL supports using `()` as one of the group by elements which
represent the meaning of nothing. Please refer to GROUP BY Clause
section in [PostgreSQL](https://www.postgresql.org/docs/16/sql-select.html).

This PR will close #1092.
  • Loading branch information
git-hulk committed Jul 19, 2024
1 parent 20f7ac5 commit fa9d7d3
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1474,6 +1474,11 @@ impl<'a> Parser<'a> {
let result = self.parse_comma_separated(|p| p.parse_tuple(true, true))?;
self.expect_token(&Token::RParen)?;
Ok(Expr::Rollup(result))
} else if self.consume_tokens(&[Token::LParen, Token::RParen]) {
// PostgreSQL allow to use empty tuple as a group by expression,
// e.g. `GROUP BY (), name`. Please refer to GROUP BY Clause section in
// [PostgreSQL](https://www.postgresql.org/docs/16/sql-select.html)
Ok(Expr::Tuple(vec![]))
} else {
self.parse_expr()
}
Expand Down
26 changes: 26 additions & 0 deletions tests/sqlparser_postgres.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
mod test_utils;
use test_utils::*;

use sqlparser::ast::Expr::Identifier;
use sqlparser::ast::*;
use sqlparser::dialect::{GenericDialect, PostgreSqlDialect};
use sqlparser::parser::ParserError;
Expand Down Expand Up @@ -4441,3 +4442,28 @@ fn test_table_unnest_with_ordinality() {
_ => panic!("Expecting TableFactor::UNNEST with ordinality"),
}
}

#[test]
fn test_group_by_nothing() {
let group_by = pg_and_generic()
.verified_only_select("SELECT count(1) FROM t GROUP BY ()")
.group_by;
assert_eq!(
GroupByExpr::Expressions(vec![Expr::Tuple(vec![])], vec![]),
group_by
);

let group_by = pg_and_generic()
.verified_only_select("SELECT name, count(1) FROM t GROUP BY name, ()")
.group_by;
assert_eq!(
GroupByExpr::Expressions(
vec![
Identifier(Ident::new("name".to_string())),
Expr::Tuple(vec![])
],
vec![]
),
group_by
);
}

0 comments on commit fa9d7d3

Please sign in to comment.