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
1 change: 1 addition & 0 deletions fuzz/fuzz_seeds/oracle_aggregate_keep_clause.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
SELECT MAX(c.contact_name) KEEP (DENSE_RANK LAST ORDER BY c.id) AS metric FROM customers c
63 changes: 63 additions & 0 deletions src/ast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8524,6 +8524,15 @@ pub struct Function {
/// <aggregate_function>(expression) WITHIN GROUP (ORDER BY key [ASC | DESC], ...)
/// ```
pub within_group: Vec<OrderByExpr>,
/// The `KEEP (DENSE_RANK FIRST | LAST ORDER BY ...)` clause of an aggregate function.
///
/// Example:
/// ```plaintext
/// MAX(salary) KEEP (DENSE_RANK LAST ORDER BY hire_date)
/// ```
///
/// [Oracle](https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/FIRST.html)
pub keep: Option<Box<KeepClause>>,
/// e.g. `x > 5` in `COUNT(x) FILTER (WHERE x > 5)`
pub filter: Option<Box<Expr>>,
/// Indicates how `NULL`s should be handled in the calculation.
Expand Down Expand Up @@ -8555,6 +8564,10 @@ impl fmt::Display for Function {
)?;
}

if let Some(keep) = &self.keep {
write!(f, " {keep}")?;
}

if let Some(filter_cond) = &self.filter {
write!(f, " FILTER (WHERE {filter_cond})")?;
}
Expand All @@ -8576,6 +8589,56 @@ impl fmt::Display for Function {
}
}

/// The `KEEP` clause of an aggregate function, which restricts the aggregate to
/// the rows that rank first or last by the given ordering.
///
/// Syntax:
/// ```plaintext
/// KEEP (DENSE_RANK { FIRST | LAST } ORDER BY expr [, ...])
/// ```
///
/// [Oracle](https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/FIRST.html)
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub struct KeepClause {
/// Whether the rows ranked `FIRST` or `LAST` are kept.
pub rank: KeepRank,
/// The ordering used to rank the rows.
pub order_by: Vec<OrderByExpr>,
}

impl fmt::Display for KeepClause {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"KEEP (DENSE_RANK {} ORDER BY {})",
self.rank,
display_comma_separated(&self.order_by)
)
}
}

/// Which rows a [KeepClause] keeps.
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub enum KeepRank {
/// `DENSE_RANK FIRST`
First,
/// `DENSE_RANK LAST`
Last,
}

impl fmt::Display for KeepRank {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(match self {
KeepRank::First => "FIRST",
KeepRank::Last => "LAST",
})
}
}

/// The arguments passed to a function call.
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
Expand Down
19 changes: 18 additions & 1 deletion src/ast/spans.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1939,6 +1939,7 @@ impl Spanned for Function {
null_treatment: _, // enum
over: _, // todo
within_group,
keep,
} = self;

union_spans(
Expand All @@ -1948,7 +1949,11 @@ impl Spanned for Function {
.chain(iter::once(args.span()))
.chain(iter::once(parameters.span()))
.chain(filter.iter().map(|i| i.span()))
.chain(within_group.iter().map(|i| i.span())),
.chain(within_group.iter().map(|i| i.span()))
.chain(
keep.iter()
.flat_map(|k| k.order_by.iter().map(|i| i.span())),
),
)
}
}
Expand Down Expand Up @@ -3056,6 +3061,18 @@ pub mod tests {
);
}

#[test]
fn test_function_keep_clause_span() {
let dialect = &GenericDialect;
let mut test = SpanTest::new(dialect, "MAX(a) KEEP (DENSE_RANK LAST ORDER BY b)");
let expr = test.0.parse_expr().unwrap();
// The KEEP ordering extends the span past the argument list
assert_eq!(
test.get_source(expr.span()),
"MAX(a) KEEP (DENSE_RANK LAST ORDER BY b"
);
}

#[test]
fn test_placeholder_span() {
let sql = "\nSELECT\n :fooBar";
Expand Down
1 change: 1 addition & 0 deletions src/ast/visitor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -696,6 +696,7 @@ where
/// over: None,
/// parameters: FunctionArguments::None,
/// within_group: vec![],
/// keep: None,
/// });
/// }
/// ControlFlow::<()>::Continue(())
Expand Down
4 changes: 4 additions & 0 deletions src/dialect/generic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -281,6 +281,10 @@ impl Dialect for GenericDialect {
true
}

fn supports_aggregate_keep_clause(&self) -> bool {
true
}

fn supports_select_wildcard_exclude(&self) -> bool {
true
}
Expand Down
13 changes: 13 additions & 0 deletions src/dialect/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -386,6 +386,19 @@ pub trait Dialect: Debug + Any {
false
}

/// Returns true if the dialect supports the `KEEP (DENSE_RANK FIRST | LAST ORDER BY ...)`
/// clause after an aggregate function call.
///
/// Example:
/// ```sql
/// SELECT MAX(salary) KEEP (DENSE_RANK LAST ORDER BY hire_date) FROM employees
/// ```
///
/// [Oracle](https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/FIRST.html)
fn supports_aggregate_keep_clause(&self) -> bool {
false
}

/// Returns true if the dialect supports referencing another named window
/// within a window clause declaration.
///
Expand Down
5 changes: 5 additions & 0 deletions src/dialect/oracle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,11 @@ impl Dialect for OracleDialect {
true
}

/// See <https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/FIRST.html>
fn supports_aggregate_keep_clause(&self) -> bool {
true
}

/// See <https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/Aggregate-Functions.html>
fn supports_unique_in_function_args(&self) -> bool {
true
Expand Down
1 change: 1 addition & 0 deletions src/keywords.rs
Original file line number Diff line number Diff line change
Expand Up @@ -588,6 +588,7 @@ define_keywords!(
JSONFILE,
JSON_TABLE,
JULIAN,
KEEP,
KEY,
KEYS,
KEY_BLOCK_SIZE,
Expand Down
31 changes: 31 additions & 0 deletions src/parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1665,6 +1665,7 @@ impl<'a> Parser<'a> {
filter: None,
over: None,
within_group: vec![],
keep: None,
})))
}
Keyword::CURRENT_TIMESTAMP
Expand Down Expand Up @@ -1727,6 +1728,7 @@ impl<'a> Parser<'a> {
null_treatment: None,
over: None,
within_group: vec![],
keep: None,
})))
}
Keyword::NOT => Ok(Some(self.parse_not()?)),
Expand Down Expand Up @@ -2698,6 +2700,7 @@ impl<'a> Parser<'a> {
null_treatment: None,
over: None,
within_group: vec![],
keep: None,
});
}

Expand Down Expand Up @@ -2728,6 +2731,14 @@ impl<'a> Parser<'a> {
vec![]
};

let keep = if self.dialect.supports_aggregate_keep_clause()
&& self.parse_keyword_with_tokens(Keyword::KEEP, &[Token::LParen])
{
Some(Box::new(self.parse_keep_clause()?))
} else {
None
};

let filter = if self.dialect.supports_filter_during_aggregation()
&& self.parse_keyword(Keyword::FILTER)
&& self.consume_token(&Token::LParen)
Expand Down Expand Up @@ -2787,9 +2798,27 @@ impl<'a> Parser<'a> {
filter,
over,
within_group,
keep,
})
}

/// Parses the rest of a `KEEP (DENSE_RANK { FIRST | LAST } ORDER BY ...)` clause,
/// assuming `KEEP (` was already consumed.
fn parse_keep_clause(&mut self) -> Result<KeepClause, ParserError> {
self.expect_keyword_is(Keyword::DENSE_RANK)?;
let rank = if self.parse_keyword(Keyword::FIRST) {
KeepRank::First
} else if self.parse_keyword(Keyword::LAST) {
KeepRank::Last
} else {
return self.expected_ref("FIRST or LAST", self.peek_token_ref());
};
self.expect_keywords(&[Keyword::ORDER, Keyword::BY])?;
let order_by = self.parse_comma_separated(Parser::parse_order_by_expr)?;
self.expect_token(&Token::RParen)?;
Ok(KeepClause { rank, order_by })
}

/// Optionally parses a null treatment clause.
fn parse_null_treatment(&mut self) -> Result<Option<NullTreatment>, ParserError> {
match self.parse_one_of_keywords(&[Keyword::RESPECT, Keyword::IGNORE]) {
Expand Down Expand Up @@ -2822,6 +2851,7 @@ impl<'a> Parser<'a> {
over: None,
null_treatment: None,
within_group: vec![],
keep: None,
}))
}

Expand Down Expand Up @@ -13268,6 +13298,7 @@ impl<'a> Parser<'a> {
filter: None,
null_treatment: None,
within_group: vec![],
keep: None,
}))
}
}
Expand Down
1 change: 1 addition & 0 deletions src/test_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -456,6 +456,7 @@ pub fn call(function: &str, args: impl IntoIterator<Item = Expr>) -> Expr {
null_treatment: None,
over: None,
within_group: vec![],
keep: None,
})
}

Expand Down
1 change: 1 addition & 0 deletions tests/sqlparser_bigquery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2294,6 +2294,7 @@ fn parse_map_access_expr() {
null_treatment: None,
over: None,
within_group: vec![],
keep: None,
uses_odbc_syntax: false,
}),
}),
Expand Down
3 changes: 3 additions & 0 deletions tests/sqlparser_clickhouse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -859,6 +859,7 @@ fn parse_create_table_with_variant_default_expressions() {
filter: None,
over: None,
within_group: vec![],
keep: None,
}))
}],
},
Expand All @@ -880,6 +881,7 @@ fn parse_create_table_with_variant_default_expressions() {
filter: None,
over: None,
within_group: vec![],
keep: None,
})))
}],
},
Expand Down Expand Up @@ -911,6 +913,7 @@ fn parse_create_table_with_variant_default_expressions() {
filter: None,
over: None,
within_group: vec![],
keep: None,
}))
}],
}
Expand Down
Loading
Loading