1use crate::{expr::Sort, lit};
14use std::fmt::{self, Formatter};
15use std::hash::Hash;
16
17use datafusion_common::{Result, ScalarValue, plan_err};
18#[cfg(feature = "sql")]
19use sqlparser::ast::{self, ValueWithSpan};
20
21#[derive(Clone, PartialEq, Eq, PartialOrd, Hash)]
26pub struct WindowFrame {
27 pub units: WindowFrameUnits,
29 pub start_bound: WindowFrameBound,
31 pub end_bound: WindowFrameBound,
33 causal: bool,
80}
81
82impl fmt::Display for WindowFrame {
83 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
84 write!(
85 f,
86 "{} BETWEEN {} AND {}",
87 self.units, self.start_bound, self.end_bound
88 )?;
89 Ok(())
90 }
91}
92
93impl fmt::Debug for WindowFrame {
94 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
95 write!(
96 f,
97 "WindowFrame {{ units: {:?}, start_bound: {:?}, end_bound: {:?}, is_causal: {:?} }}",
98 self.units, self.start_bound, self.end_bound, self.causal
99 )?;
100 Ok(())
101 }
102}
103
104#[cfg(feature = "sql")]
105impl TryFrom<ast::WindowFrame> for WindowFrame {
106 type Error = datafusion_common::error::DataFusionError;
107
108 fn try_from(value: ast::WindowFrame) -> Result<Self> {
109 let start_bound = WindowFrameBound::try_parse(value.start_bound, &value.units)?;
110 let end_bound = match value.end_bound {
111 Some(bound) => WindowFrameBound::try_parse(bound, &value.units)?,
112 None => WindowFrameBound::CurrentRow,
113 };
114
115 if let WindowFrameBound::Following(val) = &start_bound {
116 if val.is_null() {
117 plan_err!(
118 "Invalid window frame: start bound cannot be UNBOUNDED FOLLOWING"
119 )?
120 }
121 } else if let WindowFrameBound::Preceding(val) = &end_bound
122 && val.is_null()
123 {
124 plan_err!("Invalid window frame: end bound cannot be UNBOUNDED PRECEDING")?
125 }
126
127 let units = value.units.into();
128 Ok(Self::new_bounds(units, start_bound, end_bound))
129 }
130}
131
132impl WindowFrame {
133 pub fn new(order_by: Option<bool>) -> Self {
137 if let Some(strict) = order_by {
138 Self {
143 units: if strict {
144 WindowFrameUnits::Rows
145 } else {
146 WindowFrameUnits::Range
147 },
148 start_bound: WindowFrameBound::Preceding(ScalarValue::UInt64(None)),
149 end_bound: WindowFrameBound::CurrentRow,
150 causal: strict,
151 }
152 } else {
153 Self {
157 units: WindowFrameUnits::Rows,
158 start_bound: WindowFrameBound::Preceding(ScalarValue::UInt64(None)),
159 end_bound: WindowFrameBound::Following(ScalarValue::UInt64(None)),
160 causal: false,
161 }
162 }
163 }
164
165 pub fn reverse(&self) -> Self {
169 let start_bound = match &self.end_bound {
170 WindowFrameBound::Preceding(value) => {
171 WindowFrameBound::Following(value.clone())
172 }
173 WindowFrameBound::Following(value) => {
174 WindowFrameBound::Preceding(value.clone())
175 }
176 WindowFrameBound::CurrentRow => WindowFrameBound::CurrentRow,
177 };
178 let end_bound = match &self.start_bound {
179 WindowFrameBound::Preceding(value) => {
180 WindowFrameBound::Following(value.clone())
181 }
182 WindowFrameBound::Following(value) => {
183 WindowFrameBound::Preceding(value.clone())
184 }
185 WindowFrameBound::CurrentRow => WindowFrameBound::CurrentRow,
186 };
187 Self::new_bounds(self.units, start_bound, end_bound)
188 }
189
190 pub fn is_causal(&self) -> bool {
192 self.causal
193 }
194
195 pub fn new_bounds(
197 units: WindowFrameUnits,
198 start_bound: WindowFrameBound,
199 end_bound: WindowFrameBound,
200 ) -> Self {
201 let causal = match units {
202 WindowFrameUnits::Rows => match &end_bound {
203 WindowFrameBound::Following(value) => {
204 if value.is_null() {
205 false
207 } else {
208 let zero = ScalarValue::new_zero(&value.data_type());
209 zero.map(|zero| value.eq(&zero)).unwrap_or(false)
210 }
211 }
212 _ => true,
213 },
214 WindowFrameUnits::Range => matches!(
217 &end_bound,
218 WindowFrameBound::Preceding(value) if value.is_null()
219 ),
220 WindowFrameUnits::Groups => match &end_bound {
221 WindowFrameBound::Preceding(value) => {
222 if value.is_null() {
223 true
225 } else {
226 let zero = ScalarValue::new_zero(&value.data_type());
227 zero.map(|zero| value.gt(&zero)).unwrap_or(false)
228 }
229 }
230 _ => false,
231 },
232 };
233 Self {
234 units,
235 start_bound,
236 end_bound,
237 causal,
238 }
239 }
240
241 pub fn regularize_order_bys(&self, order_by: &mut Vec<Sort>) -> Result<()> {
243 match self.units {
244 WindowFrameUnits::Range if self.free_range() && order_by.is_empty() => {
249 order_by.push(lit(1u64).sort(true, false));
254 }
255 WindowFrameUnits::Range if self.free_range() => {}
256 WindowFrameUnits::Range if order_by.len() != 1 => {
257 return plan_err!("RANGE requires exactly one ORDER BY column");
258 }
259 WindowFrameUnits::Groups if order_by.is_empty() => {
260 return plan_err!("GROUPS requires an ORDER BY clause");
261 }
262 _ => {}
263 }
264 Ok(())
265 }
266
267 pub fn can_accept_multi_orderby(&self) -> bool {
269 match self.units {
270 WindowFrameUnits::Rows => true,
271 WindowFrameUnits::Range => self.free_range(),
272 WindowFrameUnits::Groups => true,
273 }
274 }
275
276 pub fn free_range(&self) -> bool {
285 (self.start_bound.is_unbounded()
286 || self.start_bound == WindowFrameBound::CurrentRow)
287 && (self.end_bound.is_unbounded()
288 || self.end_bound == WindowFrameBound::CurrentRow)
289 }
290
291 pub fn is_ever_expanding(&self) -> bool {
295 self.start_bound.is_unbounded()
296 }
297}
298
299#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
307pub enum WindowFrameBound {
308 Preceding(ScalarValue),
315 CurrentRow,
322 Following(ScalarValue),
328}
329
330impl WindowFrameBound {
331 pub fn is_unbounded(&self) -> bool {
332 match self {
333 WindowFrameBound::Preceding(elem) => elem.is_null(),
334 WindowFrameBound::CurrentRow => false,
335 WindowFrameBound::Following(elem) => elem.is_null(),
336 }
337 }
338}
339
340impl WindowFrameBound {
341 #[cfg(feature = "sql")]
342 fn try_parse(
343 value: ast::WindowFrameBound,
344 units: &ast::WindowFrameUnits,
345 ) -> Result<Self> {
346 Ok(match value {
347 ast::WindowFrameBound::Preceding(Some(v)) => {
348 Self::Preceding(convert_frame_bound_to_scalar_value(*v, units)?)
349 }
350 ast::WindowFrameBound::Preceding(None) => {
351 Self::Preceding(ScalarValue::UInt64(None))
352 }
353 ast::WindowFrameBound::Following(Some(v)) => {
354 Self::Following(convert_frame_bound_to_scalar_value(*v, units)?)
355 }
356 ast::WindowFrameBound::Following(None) => {
357 Self::Following(ScalarValue::UInt64(None))
358 }
359 ast::WindowFrameBound::CurrentRow => Self::CurrentRow,
360 })
361 }
362}
363
364#[cfg(feature = "sql")]
365fn convert_frame_bound_to_scalar_value(
366 v: ast::Expr,
367 units: &ast::WindowFrameUnits,
368) -> Result<ScalarValue> {
369 use arrow::datatypes::DataType;
370 use datafusion_common::exec_err;
371 match units {
372 ast::WindowFrameUnits::Rows | ast::WindowFrameUnits::Groups => match v {
374 ast::Expr::Value(ValueWithSpan {
375 value: ast::Value::Number(value, false),
376 span: _,
377 }) => Ok(ScalarValue::try_from_string(value, &DataType::UInt64)?),
378 ast::Expr::Interval(ast::Interval {
379 value,
380 leading_field: None,
381 leading_precision: None,
382 last_field: None,
383 fractional_seconds_precision: None,
384 }) => {
385 let value = match *value {
386 ast::Expr::Value(ValueWithSpan {
387 value: ast::Value::SingleQuotedString(item),
388 span: _,
389 }) => item,
390 e => {
391 return exec_err!("INTERVAL expression cannot be {e:?}");
392 }
393 };
394 Ok(ScalarValue::try_from_string(value, &DataType::UInt64)?)
395 }
396 _ => plan_err!(
397 "Invalid window frame: frame offsets for ROWS / GROUPS must be non negative integers"
398 ),
399 },
400 ast::WindowFrameUnits::Range => Ok(ScalarValue::Utf8(Some(match v {
403 ast::Expr::Value(ValueWithSpan {
404 value: ast::Value::Number(value, false),
405 span: _,
406 }) => value,
407 ast::Expr::Interval(ast::Interval {
408 value,
409 leading_field,
410 ..
411 }) => {
412 let result = match *value {
413 ast::Expr::Value(ValueWithSpan {
414 value: ast::Value::SingleQuotedString(item),
415 span: _,
416 }) => item,
417 e => {
418 return exec_err!("INTERVAL expression cannot be {e:?}");
419 }
420 };
421 if let Some(leading_field) = leading_field {
422 format!("{result} {leading_field}")
423 } else {
424 result
425 }
426 }
427 _ => plan_err!(
428 "Invalid window frame: frame offsets for RANGE must be either a numeric value, a string value or an interval"
429 )?,
430 }))),
431 }
432}
433
434impl fmt::Display for WindowFrameBound {
435 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
436 match self {
437 WindowFrameBound::Preceding(n) => {
438 if n.is_null() {
439 f.write_str("UNBOUNDED PRECEDING")
440 } else {
441 write!(f, "{n} PRECEDING")
442 }
443 }
444 WindowFrameBound::CurrentRow => f.write_str("CURRENT ROW"),
445 WindowFrameBound::Following(n) => {
446 if n.is_null() {
447 f.write_str("UNBOUNDED FOLLOWING")
448 } else {
449 write!(f, "{n} FOLLOWING")
450 }
451 }
452 }
453 }
454}
455
456#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Hash)]
459pub enum WindowFrameUnits {
460 Rows,
463 Range,
469 Groups,
473}
474
475impl fmt::Display for WindowFrameUnits {
476 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
477 f.write_str(match self {
478 WindowFrameUnits::Rows => "ROWS",
479 WindowFrameUnits::Range => "RANGE",
480 WindowFrameUnits::Groups => "GROUPS",
481 })
482 }
483}
484
485#[cfg(feature = "sql")]
486impl From<ast::WindowFrameUnits> for WindowFrameUnits {
487 fn from(value: ast::WindowFrameUnits) -> Self {
488 match value {
489 ast::WindowFrameUnits::Range => Self::Range,
490 ast::WindowFrameUnits::Groups => Self::Groups,
491 ast::WindowFrameUnits::Rows => Self::Rows,
492 }
493 }
494}
495
496#[cfg(test)]
497mod tests {
498 use super::*;
499
500 #[test]
501 fn test_window_frame_creation() -> Result<()> {
502 let window_frame = ast::WindowFrame {
503 units: ast::WindowFrameUnits::Range,
504 start_bound: ast::WindowFrameBound::Following(None),
505 end_bound: None,
506 };
507 let err = WindowFrame::try_from(window_frame).unwrap_err();
508 assert_eq!(
509 err.strip_backtrace(),
510 "Error during planning: Invalid window frame: start bound cannot be UNBOUNDED FOLLOWING".to_owned()
511 );
512
513 let window_frame = ast::WindowFrame {
514 units: ast::WindowFrameUnits::Range,
515 start_bound: ast::WindowFrameBound::Preceding(None),
516 end_bound: Some(ast::WindowFrameBound::Preceding(None)),
517 };
518 let err = WindowFrame::try_from(window_frame).unwrap_err();
519 assert_eq!(
520 err.strip_backtrace(),
521 "Error during planning: Invalid window frame: end bound cannot be UNBOUNDED PRECEDING".to_owned()
522 );
523
524 let window_frame = ast::WindowFrame {
525 units: ast::WindowFrameUnits::Rows,
526 start_bound: ast::WindowFrameBound::Preceding(Some(Box::new(
527 ast::Expr::value(ast::Value::Number("2".to_string(), false)),
528 ))),
529 end_bound: Some(ast::WindowFrameBound::Preceding(Some(Box::new(
530 ast::Expr::value(ast::Value::Number("1".to_string(), false)),
531 )))),
532 };
533
534 let window_frame = WindowFrame::try_from(window_frame)?;
535 assert_eq!(window_frame.units, WindowFrameUnits::Rows);
536 assert_eq!(
537 window_frame.start_bound,
538 WindowFrameBound::Preceding(ScalarValue::UInt64(Some(2)))
539 );
540 assert_eq!(
541 window_frame.end_bound,
542 WindowFrameBound::Preceding(ScalarValue::UInt64(Some(1)))
543 );
544
545 Ok(())
546 }
547
548 macro_rules! test_bound {
549 ($unit:ident, $value:expr, $expected:expr) => {
550 let preceding = WindowFrameBound::try_parse(
551 ast::WindowFrameBound::Preceding($value),
552 &ast::WindowFrameUnits::$unit,
553 )?;
554 assert_eq!(preceding, WindowFrameBound::Preceding($expected));
555 let following = WindowFrameBound::try_parse(
556 ast::WindowFrameBound::Following($value),
557 &ast::WindowFrameUnits::$unit,
558 )?;
559 assert_eq!(following, WindowFrameBound::Following($expected));
560 };
561 }
562
563 macro_rules! test_bound_err {
564 ($unit:ident, $value:expr, $expected:expr) => {
565 let err = WindowFrameBound::try_parse(
566 ast::WindowFrameBound::Preceding($value),
567 &ast::WindowFrameUnits::$unit,
568 )
569 .unwrap_err();
570 assert_eq!(err.strip_backtrace(), $expected);
571 let err = WindowFrameBound::try_parse(
572 ast::WindowFrameBound::Following($value),
573 &ast::WindowFrameUnits::$unit,
574 )
575 .unwrap_err();
576 assert_eq!(err.strip_backtrace(), $expected);
577 };
578 }
579
580 #[test]
581 fn test_window_frame_bound_creation() -> Result<()> {
582 test_bound!(Rows, None, ScalarValue::UInt64(None));
584 test_bound!(Groups, None, ScalarValue::UInt64(None));
585 test_bound!(Range, None, ScalarValue::UInt64(None));
586
587 let number = Some(Box::new(ast::Expr::Value(
589 ast::Value::Number("42".to_string(), false).into(),
590 )));
591 test_bound!(Rows, number.clone(), ScalarValue::UInt64(Some(42)));
592 test_bound!(Groups, number.clone(), ScalarValue::UInt64(Some(42)));
593 test_bound!(
594 Range,
595 number.clone(),
596 ScalarValue::Utf8(Some("42".to_string()))
597 );
598
599 let number = Some(Box::new(ast::Expr::Interval(ast::Interval {
601 value: Box::new(ast::Expr::Value(
602 ast::Value::SingleQuotedString("1".to_string()).into(),
603 )),
604 leading_field: Some(ast::DateTimeField::Day),
605 fractional_seconds_precision: None,
606 last_field: None,
607 leading_precision: None,
608 })));
609 test_bound_err!(
610 Rows,
611 number.clone(),
612 "Error during planning: Invalid window frame: frame offsets for ROWS / GROUPS must be non negative integers"
613 );
614 test_bound_err!(
615 Groups,
616 number.clone(),
617 "Error during planning: Invalid window frame: frame offsets for ROWS / GROUPS must be non negative integers"
618 );
619 test_bound!(
620 Range,
621 number.clone(),
622 ScalarValue::Utf8(Some("1 DAY".to_string()))
623 );
624
625 Ok(())
626 }
627}