Skip to content

Commit

Permalink
feat: enable empty by in range select (#8)
Browse files Browse the repository at this point in the history
  • Loading branch information
Taylor-lagrange authored Nov 6, 2023
1 parent 602d787 commit 0fbae07
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
24 changes: 21 additions & 3 deletions src/parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ use alloc::{
vec,
vec::Vec,
};
#[cfg(feature = "bigdecimal-sql")]
use bigdecimal::BigDecimal;
use core::fmt;
use std::collections::BTreeSet;

Expand Down Expand Up @@ -5769,9 +5771,25 @@ impl<'a> Parser<'a> {
value.verify_duration()?;
let by = if self.parse_keyword(Keyword::BY) {
self.expect_token(&Token::LParen)?;
let by = self.parse_comma_separated(Parser::parse_expr)?;
self.expect_token(&Token::RParen)?;
by
if self.consume_token(&Token::RParen) {
// for case like `by ()`
// The user explicitly specifies that the aggregation key is empty. In this case, there is no aggregation key.
// All data will be aggregated into a group, which is equivalent to using a random constant as the aggregation key.
// Therefore, in this case, the constant 1 is used directly as the aggregation key.
// `()` == `(1)`
#[cfg(not(feature = "bigdecimal-sql"))]
{
vec![Expr::Value(Value::Number("1".into(), false))]
}
#[cfg(feature = "bigdecimal-sql")]
{
vec![Expr::Value(Value::Number(BigDecimal::from(1), false))]
}
} else {
let by = self.parse_comma_separated(Parser::parse_expr)?;
self.expect_token(&Token::RParen)?;
by
}
} else {
vec![]
};
Expand Down
4 changes: 4 additions & 0 deletions tests/sqlparser_common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7415,6 +7415,10 @@ fn parse_range_select() {
assert_sql("SELECT rate(metrics) RANGE '5m', sum(metrics) RANGE '10m' FILL MAX, sum(metrics) RANGE '10m' FROM t ALIGN '1h' by ((a+1)/2, b) FILL NULL;",
"SELECT range_fn(rate(metrics), '5m', 'NULL', '2', (a + 1) / 2, b, '1h'), range_fn(sum(metrics), '10m', 'MAX', '2', (a + 1) / 2, b, '1h'), range_fn(sum(metrics), '10m', 'NULL', '2', (a + 1) / 2, b, '1h') FROM t GROUP BY a, b");

// explicit empty by
assert_sql("SELECT rate(metrics) RANGE '5m', sum(metrics) RANGE '10m' FILL MAX, sum(metrics) RANGE '10m' FROM t ALIGN '1h' by () FILL NULL;",
"SELECT range_fn(rate(metrics), '5m', 'NULL', '1', 1, '1h'), range_fn(sum(metrics), '10m', 'MAX', '1', 1, '1h'), range_fn(sum(metrics), '10m', 'NULL', '1', 1, '1h') FROM t");

// expression1
assert_sql(
"SELECT avg(a/2 + 1) RANGE '5m' FILL NULL FROM t ALIGN '1h' FILL NULL;",
Expand Down

0 comments on commit 0fbae07

Please sign in to comment.