use datafusion_common::{DataFusionError, Result, ScalarValue};
use sqlparser::ast;
use sqlparser::parser::ParserError::ParserError;
use std::convert::{From, TryFrom};
use std::fmt;
use std::hash::Hash;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct WindowFrame {
pub units: WindowFrameUnits,
pub start_bound: WindowFrameBound,
pub end_bound: WindowFrameBound,
}
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 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(ScalarValue::Utf8(None)) = start_bound {
Err(DataFusionError::Execution(
"Invalid window frame: start bound cannot be unbounded following"
.to_owned(),
))
} else if let WindowFrameBound::Preceding(ScalarValue::Utf8(None)) = end_bound {
Err(DataFusionError::Execution(
"Invalid window frame: end bound cannot be unbounded preceding"
.to_owned(),
))
} else {
let units = value.units.into();
Ok(Self {
units,
start_bound,
end_bound,
})
}
}
}
impl Default for WindowFrame {
fn default() -> Self {
WindowFrame {
units: WindowFrameUnits::Range,
start_bound: WindowFrameBound::Preceding(ScalarValue::Utf8(None)),
end_bound: WindowFrameBound::CurrentRow,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum WindowFrameBound {
Preceding(ScalarValue),
CurrentRow,
Following(ScalarValue),
}
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::Utf8(None))
}
ast::WindowFrameBound::Following(Some(v)) => {
Self::Following(convert_frame_bound_to_scalar_value(*v)?)
}
ast::WindowFrameBound::Following(None) => {
Self::Following(ScalarValue::Utf8(None))
}
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 {
value,
leading_field,
..
} => {
let result = match *value {
ast::Expr::Value(ast::Value::SingleQuotedString(item)) => item,
e => {
let msg = format!("INTERVAL expression cannot be {:?}", e);
return Err(DataFusionError::SQL(ParserError(msg)));
}
};
if let Some(leading_field) = leading_field {
format!("{} {}", result, leading_field)
} else {
result
}
}
e => {
let msg = format!("Window frame bound cannot be {:?}", e);
return Err(DataFusionError::Internal(msg));
}
})))
}
impl fmt::Display for WindowFrameBound {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
WindowFrameBound::Preceding(ScalarValue::Utf8(None)) => {
f.write_str("UNBOUNDED PRECEDING")
}
WindowFrameBound::Preceding(n) => write!(f, "{} PRECEDING", n),
WindowFrameBound::CurrentRow => f.write_str("CURRENT ROW"),
WindowFrameBound::Following(ScalarValue::Utf8(None)) => {
f.write_str("UNBOUNDED FOLLOWING")
}
WindowFrameBound::Following(n) => write!(f, "{} FOLLOWING", n),
}
}
}
#[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.to_string(),
"Execution error: 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.to_string(),
"Execution error: 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(())
}
}