Skip to content

Named window frames #881

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
May 18, 2023
Merged
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
31 changes: 24 additions & 7 deletions src/ast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use alloc::{
string::{String, ToString},
vec::Vec,
};
use core::fmt;
use core::fmt::{self, Display};

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
Expand All @@ -35,10 +35,10 @@ pub use self::ddl::{
pub use self::operator::{BinaryOperator, UnaryOperator};
pub use self::query::{
Cte, Distinct, ExceptSelectItem, ExcludeSelectItem, Fetch, IdentWithAlias, Join,
JoinConstraint, JoinOperator, LateralView, LockClause, LockType, NonBlock, Offset, OffsetRows,
OrderByExpr, Query, RenameSelectItem, ReplaceSelectElement, ReplaceSelectItem, Select,
SelectInto, SelectItem, SetExpr, SetOperator, SetQuantifier, Table, TableAlias, TableFactor,
TableWithJoins, Top, Values, WildcardAdditionalOptions, With,
JoinConstraint, JoinOperator, LateralView, LockClause, LockType, NamedWindowDefinition,
NonBlock, Offset, OffsetRows, OrderByExpr, Query, RenameSelectItem, ReplaceSelectElement,
ReplaceSelectItem, Select, SelectInto, SelectItem, SetExpr, SetOperator, SetQuantifier, Table,
TableAlias, TableFactor, TableWithJoins, Top, Values, WildcardAdditionalOptions, With,
};
pub use self::value::{
escape_quoted_string, DateTimeField, DollarQuotedString, TrimWhereField, Value,
Expand Down Expand Up @@ -917,6 +917,23 @@ impl fmt::Display for Expr {
}
}

#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub enum WindowType {
WindowSpec(WindowSpec),
NamedWindow(Ident),
}

impl Display for WindowType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
WindowType::WindowSpec(spec) => write!(f, "({})", spec),
WindowType::NamedWindow(name) => write!(f, "{}", name),
}
}
}

/// A window specification (i.e. `OVER (PARTITION BY .. ORDER BY .. etc.)`)
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
Expand Down Expand Up @@ -3343,7 +3360,7 @@ impl fmt::Display for CloseCursor {
pub struct Function {
pub name: ObjectName,
pub args: Vec<FunctionArg>,
pub over: Option<WindowSpec>,
pub over: Option<WindowType>,
// aggregate functions may specify eg `COUNT(DISTINCT x)`
pub distinct: bool,
// Some functions must be called without trailing parentheses, for example Postgres
Expand Down Expand Up @@ -3384,7 +3401,7 @@ impl fmt::Display for Function {
)?;

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

Expand Down
16 changes: 16 additions & 0 deletions src/ast/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,8 @@ pub struct Select {
pub sort_by: Vec<Expr>,
/// HAVING
pub having: Option<Expr>,
/// WINDOW AS
pub named_window: Vec<NamedWindowDefinition>,
/// QUALIFY (Snowflake)
pub qualify: Option<Expr>,
}
Expand Down Expand Up @@ -269,6 +271,9 @@ impl fmt::Display for Select {
if let Some(ref having) = self.having {
write!(f, " HAVING {having}")?;
}
if !self.named_window.is_empty() {
write!(f, " WINDOW {}", display_comma_separated(&self.named_window))?;
}
if let Some(ref qualify) = self.qualify {
write!(f, " QUALIFY {qualify}")?;
}
Expand Down Expand Up @@ -311,6 +316,17 @@ impl fmt::Display for LateralView {
}
}

#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
pub struct NamedWindowDefinition(pub Ident, pub WindowSpec);

impl fmt::Display for NamedWindowDefinition {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} AS ({})", self.0, self.1)
}
}

#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
Expand Down
1 change: 1 addition & 0 deletions src/keywords.rs
Original file line number Diff line number Diff line change
Expand Up @@ -687,6 +687,7 @@ pub const RESERVED_FOR_TABLE_ALIAS: &[Keyword] = &[
Keyword::OUTER,
Keyword::SET,
Keyword::QUALIFY,
Keyword::WINDOW,
];

/// Can't be used as a column alias, so that `SELECT <expr> alias`
Expand Down
70 changes: 45 additions & 25 deletions src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -882,32 +882,12 @@ impl<'a> Parser<'a> {
let distinct = self.parse_all_or_distinct()?.is_some();
let args = self.parse_optional_args()?;
let over = if self.parse_keyword(Keyword::OVER) {
// TBD: support window names (`OVER mywin`) in place of inline specification
self.expect_token(&Token::LParen)?;
let partition_by = if self.parse_keywords(&[Keyword::PARTITION, Keyword::BY]) {
// a list of possibly-qualified column names
self.parse_comma_separated(Parser::parse_expr)?
} else {
vec![]
};
let order_by = if self.parse_keywords(&[Keyword::ORDER, Keyword::BY]) {
self.parse_comma_separated(Parser::parse_order_by_expr)?
} else {
vec![]
};
let window_frame = if !self.consume_token(&Token::RParen) {
let window_frame = self.parse_window_frame()?;
self.expect_token(&Token::RParen)?;
Some(window_frame)
if self.consume_token(&Token::LParen) {
let window_spec = self.parse_window_spec()?;
Some(WindowType::WindowSpec(window_spec))
} else {
None
};

Some(WindowSpec {
partition_by,
order_by,
window_frame,
})
Some(WindowType::NamedWindow(self.parse_identifier()?))
}
} else {
None
};
Expand Down Expand Up @@ -5267,6 +5247,12 @@ impl<'a> Parser<'a> {
None
};

let named_windows = if self.parse_keyword(Keyword::WINDOW) {
self.parse_comma_separated(Parser::parse_named_window)?
} else {
vec![]
};

let qualify = if self.parse_keyword(Keyword::QUALIFY) {
Some(self.parse_expr()?)
} else {
Expand All @@ -5286,6 +5272,7 @@ impl<'a> Parser<'a> {
distribute_by,
sort_by,
having,
named_window: named_windows,
qualify,
})
}
Expand Down Expand Up @@ -6915,6 +6902,39 @@ impl<'a> Parser<'a> {
pub fn index(&self) -> usize {
self.index
}

pub fn parse_named_window(&mut self) -> Result<NamedWindowDefinition, ParserError> {
let ident = self.parse_identifier()?;
self.expect_keyword(Keyword::AS)?;
self.expect_token(&Token::LParen)?;
let window_spec = self.parse_window_spec()?;
Ok(NamedWindowDefinition(ident, window_spec))
}

pub fn parse_window_spec(&mut self) -> Result<WindowSpec, ParserError> {
let partition_by = if self.parse_keywords(&[Keyword::PARTITION, Keyword::BY]) {
self.parse_comma_separated(Parser::parse_expr)?
} else {
vec![]
};
let order_by = if self.parse_keywords(&[Keyword::ORDER, Keyword::BY]) {
self.parse_comma_separated(Parser::parse_order_by_expr)?
} else {
vec![]
};
let window_frame = if !self.consume_token(&Token::RParen) {
let window_frame = self.parse_window_frame()?;
self.expect_token(&Token::RParen)?;
Some(window_frame)
} else {
None
};
Ok(WindowSpec {
partition_by,
order_by,
window_frame,
})
}
}

impl Word {
Expand Down
1 change: 1 addition & 0 deletions tests/sqlparser_clickhouse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ fn parse_map_access_expr() {
distribute_by: vec![],
sort_by: vec![],
having: None,
named_window: vec![],
qualify: None
},
select
Expand Down
Loading