use std::convert::{From, TryFrom};
use std::fmt::{self, Formatter};
use std::hash::Hash;
use crate::expr::Sort;
use crate::Expr;
use datafusion_common::{plan_err, sql_err, DataFusionError, Result, ScalarValue};
use sqlparser::ast;
use sqlparser::parser::ParserError::ParserError;
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct WindowFrame {
pub units: WindowFrameUnits,
pub start_bound: WindowFrameBound,
pub end_bound: WindowFrameBound,
causal: bool,
}
impl fmt::Display for WindowFrame {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"{} BETWEEN {} AND {}",
self.units, self.start_bound, self.end_bound
)?;
Ok(())
}
}
impl fmt::Debug for WindowFrame {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(
f,
"WindowFrame {{ units: {:?}, start_bound: {:?}, end_bound: {:?} }}",
self.units, self.start_bound, self.end_bound
)?;
Ok(())
}
}
impl TryFrom<ast::WindowFrame> for WindowFrame {
type Error = DataFusionError;
fn try_from(value: ast::WindowFrame) -> Result<Self> {
let start_bound = value.start_bound.try_into()?;
let end_bound = match value.end_bound {
Some(value) => value.try_into()?,
None => WindowFrameBound::CurrentRow,
};
if let WindowFrameBound::Following(val) = &start_bound {
if val.is_null() {
plan_err!(
"Invalid window frame: start bound cannot be UNBOUNDED FOLLOWING"
)?
}
} else if let WindowFrameBound::Preceding(val) = &end_bound {
if val.is_null() {
plan_err!(
"Invalid window frame: end bound cannot be UNBOUNDED PRECEDING"
)?
}
};
let units = value.units.into();
Ok(Self::new_bounds(units, start_bound, end_bound))
}
}
impl WindowFrame {
pub fn new(order_by: Option<bool>) -> Self {
if let Some(strict) = order_by {
Self {
units: if strict {
WindowFrameUnits::Rows
} else {
WindowFrameUnits::Range
},
start_bound: WindowFrameBound::Preceding(ScalarValue::Null),
end_bound: WindowFrameBound::CurrentRow,
causal: strict,
}
} else {
Self {
units: WindowFrameUnits::Rows,
start_bound: WindowFrameBound::Preceding(ScalarValue::UInt64(None)),
end_bound: WindowFrameBound::Following(ScalarValue::UInt64(None)),
causal: false,
}
}
}
pub fn reverse(&self) -> Self {
let start_bound = match &self.end_bound {
WindowFrameBound::Preceding(value) => {
WindowFrameBound::Following(value.clone())
}
WindowFrameBound::Following(value) => {
WindowFrameBound::Preceding(value.clone())
}
WindowFrameBound::CurrentRow => WindowFrameBound::CurrentRow,
};
let end_bound = match &self.start_bound {
WindowFrameBound::Preceding(value) => {
WindowFrameBound::Following(value.clone())
}
WindowFrameBound::Following(value) => {
WindowFrameBound::Preceding(value.clone())
}
WindowFrameBound::CurrentRow => WindowFrameBound::CurrentRow,
};
Self::new_bounds(self.units, start_bound, end_bound)
}
pub fn is_causal(&self) -> bool {
self.causal
}
pub fn new_bounds(
units: WindowFrameUnits,
start_bound: WindowFrameBound,
end_bound: WindowFrameBound,
) -> Self {
let causal = match units {
WindowFrameUnits::Rows => match &end_bound {
WindowFrameBound::Following(value) => {
if value.is_null() {
false
} else {
let zero = ScalarValue::new_zero(&value.data_type());
zero.map(|zero| value.eq(&zero)).unwrap_or(false)
}
}
_ => true,
},
WindowFrameUnits::Range | WindowFrameUnits::Groups => match &end_bound {
WindowFrameBound::Preceding(value) => {
if value.is_null() {
true
} else {
let zero = ScalarValue::new_zero(&value.data_type());
zero.map(|zero| value.gt(&zero)).unwrap_or(false)
}
}
_ => false,
},
};
Self {
units,
start_bound,
end_bound,
causal,
}
}
}
pub fn regularize_window_order_by(
frame: &WindowFrame,
order_by: &mut Vec<Expr>,
) -> Result<()> {
if frame.units == WindowFrameUnits::Range && order_by.len() != 1 {
if (frame.start_bound.is_unbounded()
|| frame.start_bound == WindowFrameBound::CurrentRow)
&& (frame.end_bound == WindowFrameBound::CurrentRow
|| frame.end_bound.is_unbounded())
{
if order_by.is_empty() {
order_by.push(Expr::Sort(Sort::new(
Box::new(Expr::Literal(ScalarValue::UInt64(Some(1)))),
true,
false,
)));
}
}
}
Ok(())
}
pub fn check_window_frame(frame: &WindowFrame, order_bys: usize) -> Result<()> {
if frame.units == WindowFrameUnits::Range && order_bys != 1 {
if !(frame.start_bound.is_unbounded()
|| frame.start_bound == WindowFrameBound::CurrentRow)
|| !(frame.end_bound == WindowFrameBound::CurrentRow
|| frame.end_bound.is_unbounded())
{
plan_err!("RANGE requires exactly one ORDER BY column")?
}
} else if frame.units == WindowFrameUnits::Groups && order_bys == 0 {
plan_err!("GROUPS requires an ORDER BY clause")?
};
Ok(())
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum WindowFrameBound {
Preceding(ScalarValue),
CurrentRow,
Following(ScalarValue),
}
impl WindowFrameBound {
pub fn is_unbounded(&self) -> bool {
match self {
WindowFrameBound::Preceding(elem) => elem.is_null(),
WindowFrameBound::CurrentRow => false,
WindowFrameBound::Following(elem) => elem.is_null(),
}
}
}
impl TryFrom<ast::WindowFrameBound> for WindowFrameBound {
type Error = DataFusionError;
fn try_from(value: ast::WindowFrameBound) -> Result<Self> {
Ok(match value {
ast::WindowFrameBound::Preceding(Some(v)) => {
Self::Preceding(convert_frame_bound_to_scalar_value(*v)?)
}
ast::WindowFrameBound::Preceding(None) => Self::Preceding(ScalarValue::Null),
ast::WindowFrameBound::Following(Some(v)) => {
Self::Following(convert_frame_bound_to_scalar_value(*v)?)
}
ast::WindowFrameBound::Following(None) => Self::Following(ScalarValue::Null),
ast::WindowFrameBound::CurrentRow => Self::CurrentRow,
})
}
}
pub fn convert_frame_bound_to_scalar_value(v: ast::Expr) -> Result<ScalarValue> {
Ok(ScalarValue::Utf8(Some(match v {
ast::Expr::Value(ast::Value::Number(value, false))
| ast::Expr::Value(ast::Value::SingleQuotedString(value)) => value,
ast::Expr::Interval(ast::Interval {
value,
leading_field,
..
}) => {
let result = match *value {
ast::Expr::Value(ast::Value::SingleQuotedString(item)) => item,
e => {
return sql_err!(ParserError(format!(
"INTERVAL expression cannot be {e:?}"
)));
}
};
if let Some(leading_field) = leading_field {
format!("{result} {leading_field}")
} else {
result
}
}
_ => plan_err!(
"Invalid window frame: frame offsets must be non negative integers"
)?,
})))
}
impl fmt::Display for WindowFrameBound {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
WindowFrameBound::Preceding(n) => {
if n.is_null() {
f.write_str("UNBOUNDED PRECEDING")
} else {
write!(f, "{n} PRECEDING")
}
}
WindowFrameBound::CurrentRow => f.write_str("CURRENT ROW"),
WindowFrameBound::Following(n) => {
if n.is_null() {
f.write_str("UNBOUNDED FOLLOWING")
} else {
write!(f, "{n} FOLLOWING")
}
}
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Hash)]
pub enum WindowFrameUnits {
Rows,
Range,
Groups,
}
impl fmt::Display for WindowFrameUnits {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(match self {
WindowFrameUnits::Rows => "ROWS",
WindowFrameUnits::Range => "RANGE",
WindowFrameUnits::Groups => "GROUPS",
})
}
}
impl From<ast::WindowFrameUnits> for WindowFrameUnits {
fn from(value: ast::WindowFrameUnits) -> Self {
match value {
ast::WindowFrameUnits::Range => Self::Range,
ast::WindowFrameUnits::Groups => Self::Groups,
ast::WindowFrameUnits::Rows => Self::Rows,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_window_frame_creation() -> Result<()> {
let window_frame = ast::WindowFrame {
units: ast::WindowFrameUnits::Range,
start_bound: ast::WindowFrameBound::Following(None),
end_bound: None,
};
let err = WindowFrame::try_from(window_frame).unwrap_err();
assert_eq!(
err.strip_backtrace(),
"Error during planning: Invalid window frame: start bound cannot be UNBOUNDED FOLLOWING".to_owned()
);
let window_frame = ast::WindowFrame {
units: ast::WindowFrameUnits::Range,
start_bound: ast::WindowFrameBound::Preceding(None),
end_bound: Some(ast::WindowFrameBound::Preceding(None)),
};
let err = WindowFrame::try_from(window_frame).unwrap_err();
assert_eq!(
err.strip_backtrace(),
"Error during planning: Invalid window frame: end bound cannot be UNBOUNDED PRECEDING".to_owned()
);
let window_frame = ast::WindowFrame {
units: ast::WindowFrameUnits::Rows,
start_bound: ast::WindowFrameBound::Preceding(Some(Box::new(
ast::Expr::Value(ast::Value::Number("2".to_string(), false)),
))),
end_bound: Some(ast::WindowFrameBound::Preceding(Some(Box::new(
ast::Expr::Value(ast::Value::Number("1".to_string(), false)),
)))),
};
let result = WindowFrame::try_from(window_frame);
assert!(result.is_ok());
Ok(())
}
}