Skip to content
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

Merged
merged 33 commits into from
Jun 9, 2022
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
7304180
window func expression
doki23 Apr 22, 2022
0d57622
update structure of window function expression
doki23 Apr 22, 2022
962f50f
window plan
doki23 Apr 23, 2022
e180ef1
local commit
doki23 Apr 23, 2022
9e1ba01
Merge branch 'main' of github.com:datafuselabs/databend into window_func
doki23 Apr 28, 2022
f455a6a
window logical plan done
doki23 Apr 30, 2022
4dee1d1
Merge branch 'main' of github.com:datafuselabs/databend into window_func
doki23 Apr 30, 2022
a121073
fix
doki23 Apr 30, 2022
3027eef
Merge branch 'main' of github.com:datafuselabs/databend into window_func
doki23 May 8, 2022
89a707a
temporary commit
doki23 May 12, 2022
65c3563
basic func
doki23 May 16, 2022
f350820
Merge branch 'main' into window_func
mergify[bot] May 16, 2022
6ca5006
Merge branch 'main' of github.com:datafuselabs/databend into window_func
doki23 May 24, 2022
2a284c9
Merge branch 'main' of github.com:datafuselabs/databend into window_func
doki23 May 27, 2022
e032aa7
naive evaluation and rows frame
doki23 May 27, 2022
1e60ccb
Merge branch 'datafuselabs:main' into window_func
doki23 May 27, 2022
9701d7c
stage but with a mock hash function
doki23 May 31, 2022
ebd377f
support multi partition by
doki23 Jun 1, 2022
f6fd723
support range frame
doki23 Jun 1, 2022
70b2ed5
evaluation with segment tree and clean the code
doki23 Jun 6, 2022
be48007
Merge branch 'main' of github.com:datafuselabs/databend into window_func
doki23 Jun 6, 2022
c140682
Merge branch 'main' of github.com:datafuselabs/databend into window_func
doki23 Jun 7, 2022
c00a533
Merge branch 'main' of github.com:datafuselabs/databend into window_func
doki23 Jun 7, 2022
2f88ace
Merge branch 'datafuselabs:main' into window_func
doki23 Jun 7, 2022
49e68f0
Merge branch 'window_func' of https://github.com/doki23/databend into…
doki23 Jun 7, 2022
706e19a
empty partition
doki23 Jun 7, 2022
dd15974
clippy
doki23 Jun 7, 2022
ce0e752
add stateless tests and fix some bugs of range frame current row bound
doki23 Jun 8, 2022
f358099
licenses
doki23 Jun 8, 2022
5532bc8
remove error case
doki23 Jun 8, 2022
e5c8a8d
Merge branch 'main' into window_func
mergify[bot] Jun 8, 2022
0b06551
Merge branch 'main' into window_func
mergify[bot] Jun 8, 2022
acaf070
Merge branch 'main' into window_func
mergify[bot] Jun 9, 2022
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
7 changes: 7 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 9 additions & 0 deletions common/ast/src/udfs/udf_expr_visitor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,15 @@ pub trait UDFExprVisitor: Sized + Send {
};
}

if let Some(over) = &function.over {
for partition_by in &over.partition_by {
UDFExprTraverser::accept(partition_by, self).await?;
}
for order_by in &over.order_by {
UDFExprTraverser::accept(&order_by.expr, self).await?;
}
}

Ok(())
}

Expand Down
1 change: 1 addition & 0 deletions common/functions/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
pub mod aggregates;
pub mod rdoc;
pub mod scalars;
pub mod window;

use aggregates::AggregateFunctionFactory;
use scalars::FunctionFactory;
Expand Down
5 changes: 5 additions & 0 deletions common/functions/src/window/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
mod window_frame;
Copy link
Member

@BohuTANG BohuTANG May 16, 2022

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 :)

Copy link
Contributor Author

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 😂.

Copy link
Member

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 💌


pub use window_frame::WindowFrame;
pub use window_frame::WindowFrameBound;
pub use window_frame::WindowFrameUnits;
223 changes: 223 additions & 0 deletions common/functions/src/window/window_frame.rs
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 {
Copy link
Contributor Author

Choose a reason for hiding this comment

The 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.

Copy link
Member

@sundy-li sundy-li Jun 7, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Member

Choose a reason for hiding this comment

The 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:

  • Original Project
  • Link to commits

Copy link
Contributor Author

Choose a reason for hiding this comment

The 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

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)
}
}
4 changes: 4 additions & 0 deletions common/planners/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ mod plan_user_udf_drop;
mod plan_view_alter;
mod plan_view_create;
mod plan_view_drop;
mod plan_window_func;

pub use plan_aggregator_final::AggregatorFinalPlan;
pub use plan_aggregator_partial::AggregatorPartialPlan;
Expand Down Expand Up @@ -127,6 +128,8 @@ pub use plan_expression_common::extract_aliases;
pub use plan_expression_common::find_aggregate_exprs;
pub use plan_expression_common::find_aggregate_exprs_in_expr;
pub use plan_expression_common::find_columns_not_satisfy_exprs;
pub use plan_expression_common::find_window_exprs;
pub use plan_expression_common::find_window_exprs_in_expr;
pub use plan_expression_common::rebase_expr;
pub use plan_expression_common::rebase_expr_from_input;
pub use plan_expression_common::resolve_aliases_to_exprs;
Expand Down Expand Up @@ -224,3 +227,4 @@ pub use plan_user_udf_drop::DropUserUDFPlan;
pub use plan_view_alter::AlterViewPlan;
pub use plan_view_create::CreateViewPlan;
pub use plan_view_drop::DropViewPlan;
pub use plan_window_func::WindowFuncPlan;
64 changes: 64 additions & 0 deletions common/planners/src/plan_expression.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ use common_exception::ErrorCode;
use common_exception::Result;
use common_functions::aggregates::AggregateFunctionFactory;
use common_functions::aggregates::AggregateFunctionRef;
use common_functions::window::WindowFrame;
use once_cell::sync::Lazy;

use crate::plan_expression_common::ExpressionDataTypeVisitor;
Expand Down Expand Up @@ -94,6 +95,22 @@ pub enum Expression {
args: Vec<Expression>,
},

/// WindowFunction
WindowFunction {
/// operation performed
op: String,
/// params
params: Vec<DataValue>,
/// arguments
args: Vec<Expression>,
/// partition by
partition_by: Vec<Expression>,
/// order by
order_by: Vec<Expression>,
/// window frame
window_frame: Option<WindowFrame>,
},

/// A sort expression, that can be used to sort values.
Sort {
/// The expression to sort on
Expand Down Expand Up @@ -421,6 +438,53 @@ impl fmt::Debug for Expression {
Ok(())
}

Expression::WindowFunction {
op,
params,
args,
partition_by,
order_by,
window_frame,
} => {
let args_column_name = args.iter().map(Expression::column_name).collect::<Vec<_>>();
let params_name = params
.iter()
.map(|v| DataValue::custom_display(v, true))
.collect::<Vec<_>>();

if params.is_empty() {
write!(f, "{}", op)?;
} else {
write!(f, "{}({})", op, params_name.join(", "))?;
}

write!(f, "({})", args_column_name.join(","))?;

write!(f, " OVER(")?;
if !partition_by.is_empty() {
write!(f, "PARTITION BY {:?}", partition_by)?;
}
if !order_by.is_empty() {
if !partition_by.is_empty() {
write!(f, " ")?;
}
write!(f, "ORDER BY {:?}", order_by)?;
}
if let Some(window_frame) = window_frame {
if !partition_by.is_empty() || !order_by.is_empty() {
write!(f, " ")?;
}
write!(
f,
"{} BETWEEN {} AND {}",
window_frame.units, window_frame.start_bound, window_frame.end_bound
)?;
}
write!(f, ")")?;

Ok(())
}

Expression::Sort { expr, .. } => write!(f, "{:?}", expr),
Expression::Wildcard => write!(f, "*"),
Expression::Cast {
Expand Down
4 changes: 4 additions & 0 deletions common/planners/src/plan_expression_chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,11 @@ impl ExpressionChain {
"Action must be a non-aggregated function.",
));
}

Expression::WindowFunction { .. } => {}

Expression::Wildcard | Expression::Sort { .. } => {}

Expression::Cast {
expr: sub_expr,
data_type,
Expand Down
Loading