-
Notifications
You must be signed in to change notification settings - Fork 752
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
feat: Window func #5401
feat: Window func #5401
Changes from 12 commits
7304180
0d57622
962f50f
e180ef1
9e1ba01
f455a6a
4dee1d1
a121073
3027eef
89a707a
65c3563
f350820
6ca5006
2a284c9
e032aa7
1e60ccb
9701d7c
ebd377f
f6fd723
70b2ed5
be48007
c140682
c00a533
2f88ace
49e68f0
706e19a
dd15974
ce0e752
f358099
5532bc8
e5c8a8d
0b06551
acaf070
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
mod window_frame; | ||
|
||
pub use window_frame::WindowFrame; | ||
pub use window_frame::WindowFrameBound; | ||
pub use window_frame::WindowFrameUnits; |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,223 @@ | ||
// Copyright 2021 Datafuse Labs. | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
use std::cmp::Ordering; | ||
use std::fmt; | ||
use std::hash::Hash; | ||
use std::hash::Hasher; | ||
|
||
use common_exception::ErrorCode; | ||
use sqlparser::ast; | ||
|
||
/// The frame-spec determines which output rows are read by an aggregate window function. | ||
/// | ||
/// The ending frame boundary can be omitted (if the BETWEEN and AND keywords that surround the | ||
/// starting frame boundary are also omitted), in which case the ending frame boundary defaults to | ||
/// CURRENT ROW. | ||
#[derive( | ||
Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Hash, serde::Serialize, serde::Deserialize, | ||
)] | ||
pub struct WindowFrame { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Code in this file is mainly copied from another open source project -- apache/arrow-datafusion. And I'm not sure whether it's proper or if I should add some description on the top of it. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think it's ok. Do we have stateless tests for this pr? Like: https://github.com/datafuselabs/databend/blob/49252766894f3bb5f5d4767037142cb1b10d92bc/tests/suites/0_stateless/03_dml/03_0003_select_group_by.sql There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Please attach their license header in this file with a clear statement, for example: https://github.com/apache/arrow-datafusion/blob/master/datafusion/core/src/prelude.rs#L1-L16 And add descriptions include:
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Thanks for the remind and I'll add some stateless tests then. |
||
/// A frame type - either ROWS, RANGE or GROUPS | ||
pub units: WindowFrameUnits, | ||
/// A starting frame boundary | ||
pub start_bound: WindowFrameBound, | ||
/// An ending frame boundary | ||
pub end_bound: WindowFrameBound, | ||
} | ||
|
||
impl TryFrom<ast::WindowFrame> for WindowFrame { | ||
type Error = ErrorCode; | ||
|
||
fn try_from(value: ast::WindowFrame) -> Result<Self, Self::Error> { | ||
let start_bound = value.start_bound.into(); | ||
let end_bound = value | ||
.end_bound | ||
.map(WindowFrameBound::from) | ||
.unwrap_or(WindowFrameBound::CurrentRow); | ||
|
||
if let WindowFrameBound::Following(None) = start_bound { | ||
Err(ErrorCode::LogicalError( | ||
"Invalid window frame: start bound cannot be unbounded following".to_owned(), | ||
)) | ||
} else if let WindowFrameBound::Preceding(None) = end_bound { | ||
Err(ErrorCode::LogicalError( | ||
"Invalid window frame: end bound cannot be unbounded preceding".to_owned(), | ||
)) | ||
} else if start_bound > end_bound { | ||
Err(ErrorCode::LogicalError(format!( | ||
"Invalid window frame: start bound ({}) cannot be larger than end bound ({})", | ||
start_bound, end_bound | ||
))) | ||
} else { | ||
let units = value.units.into(); | ||
if units == WindowFrameUnits::Range { | ||
for bound in &[start_bound, end_bound] { | ||
match bound { | ||
WindowFrameBound::Preceding(Some(v)) | ||
| WindowFrameBound::Following(Some(v)) | ||
if *v > 0 => | ||
{ | ||
Err(ErrorCode::UnImplement(format!( | ||
"With WindowFrameUnits={}, the bound cannot be {} PRECEDING or FOLLOWING at the moment", | ||
units, v | ||
))) | ||
} | ||
_ => Ok(()), | ||
}?; | ||
} | ||
} | ||
Ok(Self { | ||
units, | ||
start_bound, | ||
end_bound, | ||
}) | ||
} | ||
} | ||
} | ||
|
||
impl Default for WindowFrame { | ||
fn default() -> Self { | ||
WindowFrame { | ||
units: WindowFrameUnits::Range, | ||
start_bound: WindowFrameBound::Preceding(None), | ||
end_bound: WindowFrameBound::CurrentRow, | ||
} | ||
} | ||
} | ||
|
||
/// There are three frame types: ROWS, GROUPS, and RANGE. The frame type determines how the | ||
/// starting and ending boundaries of the frame are measured. | ||
#[derive( | ||
Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Hash, serde::Serialize, serde::Deserialize, | ||
)] | ||
pub enum WindowFrameUnits { | ||
/// The RANGE frame type requires that the ORDER BY clause of the window have exactly one | ||
/// term. Call that term "X". With the RANGE frame type, the elements of the frame are | ||
/// determined by computing the value of expression X for all rows in the partition and framing | ||
/// those rows for which the value of X is within a certain range of the value of X for the | ||
/// current row. | ||
Range, | ||
/// The ROWS frame type means that the starting and ending boundaries for the frame are | ||
/// determined by counting individual rows relative to the current row. | ||
Rows, | ||
} | ||
|
||
impl fmt::Display for WindowFrameUnits { | ||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||
f.write_str(match self { | ||
WindowFrameUnits::Range => "RANGE", | ||
WindowFrameUnits::Rows => "ROWS", | ||
}) | ||
} | ||
} | ||
|
||
impl From<ast::WindowFrameUnits> for WindowFrameUnits { | ||
fn from(value: ast::WindowFrameUnits) -> Self { | ||
match value { | ||
ast::WindowFrameUnits::Range => Self::Range, | ||
ast::WindowFrameUnits::Rows => Self::Rows, | ||
_ => unimplemented!(), | ||
} | ||
} | ||
} | ||
|
||
#[derive(Debug, Clone, Copy, Eq, serde::Serialize, serde::Deserialize)] | ||
pub enum WindowFrameBound { | ||
/// 1. UNBOUNDED PRECEDING | ||
/// The frame boundary is the first row in the partition. | ||
/// | ||
/// 2. <expr> PRECEDING | ||
/// <expr> must be a non-negative constant numeric expression. The boundary is a row that | ||
/// is <expr> "units" prior to the current row. | ||
Preceding(Option<u64>), | ||
/// 3. The current row. | ||
/// | ||
/// For RANGE and GROUPS frame types, peers of the current row are also | ||
/// included in the frame, unless specifically excluded by the EXCLUDE clause. | ||
/// This is true regardless of whether CURRENT ROW is used as the starting or ending frame | ||
/// boundary. | ||
CurrentRow, | ||
/// 4. This is the same as "<expr> PRECEDING" except that the boundary is <expr> units after the | ||
/// current rather than before the current row. | ||
/// | ||
/// 5. UNBOUNDED FOLLOWING | ||
/// The frame boundary is the last row in the partition. | ||
Following(Option<u64>), | ||
} | ||
|
||
impl WindowFrameBound { | ||
/// get the rank of this window frame bound. | ||
/// | ||
/// the rank is a tuple of (u8, u64) because we'll firstly compare the kind and then the value | ||
/// which requires special handling e.g. with preceding the larger the value the smaller the | ||
/// rank and also for 0 preceding / following it is the same as current row | ||
fn get_rank(&self) -> (u8, u64) { | ||
match self { | ||
WindowFrameBound::Preceding(None) => (0, 0), | ||
WindowFrameBound::Following(None) => (4, 0), | ||
WindowFrameBound::Preceding(Some(0)) | ||
| WindowFrameBound::CurrentRow | ||
| WindowFrameBound::Following(Some(0)) => (2, 0), | ||
WindowFrameBound::Preceding(Some(v)) => (1, u64::MAX - *v), | ||
WindowFrameBound::Following(Some(v)) => (3, *v), | ||
} | ||
} | ||
} | ||
|
||
impl From<ast::WindowFrameBound> for WindowFrameBound { | ||
fn from(value: ast::WindowFrameBound) -> Self { | ||
match value { | ||
ast::WindowFrameBound::Preceding(v) => Self::Preceding(v), | ||
ast::WindowFrameBound::Following(v) => Self::Following(v), | ||
ast::WindowFrameBound::CurrentRow => Self::CurrentRow, | ||
} | ||
} | ||
} | ||
|
||
impl fmt::Display for WindowFrameBound { | ||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||
match self { | ||
WindowFrameBound::CurrentRow => f.write_str("CURRENT ROW"), | ||
WindowFrameBound::Preceding(None) => f.write_str("UNBOUNDED PRECEDING"), | ||
WindowFrameBound::Following(None) => f.write_str("UNBOUNDED FOLLOWING"), | ||
WindowFrameBound::Preceding(Some(n)) => write!(f, "{} PRECEDING", n), | ||
WindowFrameBound::Following(Some(n)) => write!(f, "{} FOLLOWING", n), | ||
} | ||
} | ||
} | ||
|
||
impl PartialEq for WindowFrameBound { | ||
fn eq(&self, other: &Self) -> bool { | ||
self.cmp(other) == Ordering::Equal | ||
} | ||
} | ||
|
||
impl PartialOrd for WindowFrameBound { | ||
fn partial_cmp(&self, other: &Self) -> Option<Ordering> { | ||
Some(self.cmp(other)) | ||
} | ||
} | ||
|
||
impl Ord for WindowFrameBound { | ||
fn cmp(&self, other: &Self) -> Ordering { | ||
self.get_rank().cmp(&other.get_rank()) | ||
} | ||
} | ||
|
||
impl Hash for WindowFrameBound { | ||
fn hash<H: Hasher>(&self, state: &mut H) { | ||
self.get_rank().hash(state) | ||
} | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hmm, need a license header to make the lint happy :)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks, I'll fix it then. And this pr's far away from ready for reviews 😂.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
A great start! Welcome asking at discussions if you have any questions 💌