1use std::fmt::Display;
16
17use FrameBound::{CurrentRow, Following, Preceding, UnboundedFollowing, UnboundedPreceding};
18use enum_as_inner::EnumAsInner;
19use parse_display::Display;
20use risingwave_common::types::DataType;
21use risingwave_common::util::sort_util::OrderType;
22use risingwave_common::{bail, must_match};
23use risingwave_pb::expr::window_frame::{PbBounds, PbExclusion};
24use risingwave_pb::expr::{PbWindowFrame, PbWindowFunction};
25
26use super::{
27 RangeFrameBounds, RowsFrameBound, RowsFrameBounds, SessionFrameBounds, WindowFuncKind,
28};
29use crate::Result;
30use crate::aggregate::AggArgs;
31
32#[derive(Debug, Clone)]
33pub struct WindowFuncCall {
34 pub kind: WindowFuncKind,
35 pub return_type: DataType,
36 pub args: AggArgs,
37 pub ignore_nulls: bool,
38 pub frame: Frame,
39}
40
41impl WindowFuncCall {
42 pub fn from_protobuf(call: &PbWindowFunction) -> Result<Self> {
43 let call = WindowFuncCall {
44 kind: WindowFuncKind::from_protobuf(call.get_type()?)?,
45 return_type: DataType::from(call.get_return_type()?),
46 args: AggArgs::from_protobuf(call.get_args())?,
47 ignore_nulls: call.get_ignore_nulls(),
48 frame: Frame::from_protobuf(call.get_frame()?)?,
49 };
50 Ok(call)
51 }
52}
53
54#[derive(Debug, Clone, Eq, PartialEq, Hash)]
55pub struct Frame {
56 pub bounds: FrameBounds,
57 pub exclusion: FrameExclusion,
58}
59
60impl Display for Frame {
61 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
62 write!(f, "{}", self.bounds)?;
63 if self.exclusion != FrameExclusion::default() {
64 write!(f, " {}", self.exclusion)?;
65 }
66 Ok(())
67 }
68}
69
70impl Frame {
71 pub fn rows(start: RowsFrameBound, end: RowsFrameBound) -> Self {
72 Self {
73 bounds: FrameBounds::Rows(RowsFrameBounds { start, end }),
74 exclusion: FrameExclusion::default(),
75 }
76 }
77
78 pub fn rows_with_exclusion(
79 start: RowsFrameBound,
80 end: RowsFrameBound,
81 exclusion: FrameExclusion,
82 ) -> Self {
83 Self {
84 bounds: FrameBounds::Rows(RowsFrameBounds { start, end }),
85 exclusion,
86 }
87 }
88}
89
90impl Frame {
91 pub fn from_protobuf(frame: &PbWindowFrame) -> Result<Self> {
92 use risingwave_pb::expr::window_frame::PbType;
93 let bounds = match frame.get_type()? {
94 PbType::Unspecified => bail!("unspecified type of `WindowFrame`"),
95 #[expect(deprecated)]
96 PbType::RowsLegacy => {
97 #[expect(deprecated)]
98 {
99 let start = FrameBound::<usize>::from_protobuf_legacy(frame.get_start()?)?;
100 let end = FrameBound::<usize>::from_protobuf_legacy(frame.get_end()?)?;
101 FrameBounds::Rows(RowsFrameBounds { start, end })
102 }
103 }
104 PbType::Rows => {
105 let bounds = must_match!(frame.get_bounds()?, PbBounds::Rows(bounds) => bounds);
106 FrameBounds::Rows(RowsFrameBounds::from_protobuf(bounds)?)
107 }
108 PbType::Range => {
109 let bounds = must_match!(frame.get_bounds()?, PbBounds::Range(bounds) => bounds);
110 FrameBounds::Range(RangeFrameBounds::from_protobuf(bounds)?)
111 }
112 PbType::Session => {
113 let bounds = must_match!(frame.get_bounds()?, PbBounds::Session(bounds) => bounds);
114 FrameBounds::Session(SessionFrameBounds::from_protobuf(bounds)?)
115 }
116 };
117 let exclusion = FrameExclusion::from_protobuf(frame.get_exclusion()?)?;
118 Ok(Self { bounds, exclusion })
119 }
120
121 pub fn to_protobuf(&self) -> PbWindowFrame {
122 use risingwave_pb::expr::window_frame::PbType;
123 let exclusion = self.exclusion.to_protobuf() as _;
124 #[expect(deprecated)] match &self.bounds {
126 FrameBounds::Rows(bounds) => PbWindowFrame {
127 r#type: PbType::Rows as _,
128 start: None, end: None, exclusion,
131 bounds: Some(PbBounds::Rows(bounds.to_protobuf())),
132 },
133 FrameBounds::Range(bounds) => PbWindowFrame {
134 r#type: PbType::Range as _,
135 start: None, end: None, exclusion,
138 bounds: Some(PbBounds::Range(bounds.to_protobuf())),
139 },
140 FrameBounds::Session(bounds) => PbWindowFrame {
141 r#type: PbType::Session as _,
142 start: None, end: None, exclusion,
145 bounds: Some(PbBounds::Session(bounds.to_protobuf())),
146 },
147 }
148 }
149}
150
151#[derive(Display, Debug, Clone, Eq, PartialEq, Hash, EnumAsInner)]
152#[display("{0}")]
153pub enum FrameBounds {
154 Rows(RowsFrameBounds),
155 Range(RangeFrameBounds),
157 Session(SessionFrameBounds),
158}
159
160impl FrameBounds {
161 pub fn validate(&self) -> Result<()> {
162 match self {
163 Self::Rows(bounds) => bounds.validate(),
164 Self::Range(bounds) => bounds.validate(),
165 Self::Session(bounds) => bounds.validate(),
166 }
167 }
168
169 pub fn start_is_unbounded(&self) -> bool {
170 match self {
171 Self::Rows(RowsFrameBounds { start, .. }) => start.is_unbounded_preceding(),
172 Self::Range(RangeFrameBounds { start, .. }) => start.is_unbounded_preceding(),
173 Self::Session(_) => false,
174 }
175 }
176
177 pub fn end_is_unbounded(&self) -> bool {
178 match self {
179 Self::Rows(RowsFrameBounds { end, .. }) => end.is_unbounded_following(),
180 Self::Range(RangeFrameBounds { end, .. }) => end.is_unbounded_following(),
181 Self::Session(_) => false,
182 }
183 }
184
185 pub fn is_unbounded(&self) -> bool {
186 self.start_is_unbounded() || self.end_is_unbounded()
187 }
188
189 pub fn may_include_preceding_rows(&self) -> bool {
191 match self {
192 Self::Rows(RowsFrameBounds { start, .. }) => {
193 start.is_unbounded_preceding() || start.is_preceding()
194 }
195 Self::Range(RangeFrameBounds { start, .. }) => {
196 start.is_unbounded_preceding() || start.is_preceding()
197 }
198 Self::Session(_) => true,
199 }
200 }
201
202 pub fn may_include_following_rows(&self) -> bool {
204 match self {
205 Self::Rows(RowsFrameBounds { end, .. }) => {
206 end.is_unbounded_following() || end.is_following()
207 }
208 Self::Range(RangeFrameBounds { end, .. }) => {
209 end.is_unbounded_following() || end.is_following()
210 }
211 Self::Session(_) => true,
212 }
213 }
214
215 pub fn may_close_by_watermark(&self) -> bool {
219 match self {
220 Self::Rows(_) => false,
221 Self::Range(RangeFrameBounds {
222 order_data_type,
223 end,
224 ..
225 }) => match end {
226 Preceding(offset) => match order_data_type {
227 DataType::Int16
231 | DataType::Int32
232 | DataType::Int64
233 | DataType::Timestamp
234 | DataType::Timestamptz
235 | DataType::Interval => offset.is_zero(),
236 _ => true,
237 },
238 CurrentRow | Following(_) => true,
239 UnboundedFollowing => false,
240 UnboundedPreceding => unreachable!("frame end never be UNBOUNDED PRECEDING"),
241 },
242 Self::Session(_) => true,
243 }
244 }
245}
246
247pub fn can_forward_watermark_on_order_key<'a>(
263 frames: impl IntoIterator<Item = &'a Frame>,
264 first_order_type: OrderType,
265) -> bool {
266 if !first_order_type.nulls_are_largest() {
267 return false;
268 }
269 let mut frames = frames.into_iter();
270 if first_order_type.is_ascending() {
271 frames.all(|frame| !frame.bounds.may_include_following_rows())
272 } else {
273 frames.all(|frame| !frame.bounds.may_include_preceding_rows())
274 }
275}
276
277pub trait FrameBoundsImpl {
278 fn validate(&self) -> Result<()>;
279}
280
281#[derive(Display, Debug, Clone, Eq, PartialEq, Hash, EnumAsInner)]
282#[display(style = "TITLE CASE")]
283pub enum FrameBound<T> {
284 UnboundedPreceding,
285 #[display("{0} PRECEDING")]
286 Preceding(T),
287 CurrentRow,
288 #[display("{0} FOLLOWING")]
289 Following(T),
290 UnboundedFollowing,
291}
292
293impl<T> FrameBound<T> {
294 fn offset_value(&self) -> Option<&T> {
295 match self {
296 UnboundedPreceding | UnboundedFollowing | CurrentRow => None,
297 Preceding(offset) | Following(offset) => Some(offset),
298 }
299 }
300
301 pub(super) fn validate_bounds(
302 start: &Self,
303 end: &Self,
304 offset_checker: impl Fn(&T) -> Result<()>,
305 ) -> Result<()> {
306 match (start, end) {
307 (_, UnboundedPreceding) => bail!("frame end cannot be UNBOUNDED PRECEDING"),
308 (UnboundedFollowing, _) => {
309 bail!("frame start cannot be UNBOUNDED FOLLOWING")
310 }
311 (Following(_), CurrentRow) | (Following(_), Preceding(_)) => {
312 bail!("frame starting from following row cannot have preceding rows")
313 }
314 (CurrentRow, Preceding(_)) => {
315 bail!("frame starting from current row cannot have preceding rows")
316 }
317 _ => {}
318 }
319
320 for bound in [start, end] {
321 if let Some(offset) = bound.offset_value() {
322 offset_checker(offset)?;
323 }
324 }
325
326 Ok(())
327 }
328
329 pub fn map<U>(self, f: impl Fn(T) -> U) -> FrameBound<U> {
330 match self {
331 UnboundedPreceding => UnboundedPreceding,
332 Preceding(offset) => Preceding(f(offset)),
333 CurrentRow => CurrentRow,
334 Following(offset) => Following(f(offset)),
335 UnboundedFollowing => UnboundedFollowing,
336 }
337 }
338}
339
340impl<T> FrameBound<T>
341where
342 T: Copy,
343{
344 pub(super) fn reverse(self) -> FrameBound<T> {
345 match self {
346 UnboundedPreceding => UnboundedFollowing,
347 Preceding(offset) => Following(offset),
348 CurrentRow => CurrentRow,
349 Following(offset) => Preceding(offset),
350 UnboundedFollowing => UnboundedPreceding,
351 }
352 }
353}
354
355#[derive(Display, Debug, Copy, Clone, Eq, PartialEq, Hash, Default, EnumAsInner)]
356#[display("EXCLUDE {}", style = "TITLE CASE")]
357pub enum FrameExclusion {
358 CurrentRow,
359 #[default]
362 NoOthers,
363}
364
365impl FrameExclusion {
366 fn from_protobuf(exclusion: PbExclusion) -> Result<Self> {
367 let excl = match exclusion {
368 PbExclusion::Unspecified => bail!("unspecified type of `FrameExclusion`"),
369 PbExclusion::CurrentRow => Self::CurrentRow,
370 PbExclusion::NoOthers => Self::NoOthers,
371 };
372 Ok(excl)
373 }
374
375 fn to_protobuf(self) -> PbExclusion {
376 match self {
377 Self::CurrentRow => PbExclusion::CurrentRow,
378 Self::NoOthers => PbExclusion::NoOthers,
379 }
380 }
381}
382
383#[cfg(test)]
384mod tests {
385 use risingwave_common::types::{Decimal, Interval, ScalarImpl};
386
387 use super::*;
388 use crate::window_function::{RangeFrameBound, RangeFrameOffset, SessionFrameGap};
389
390 fn rows_frame(start: RowsFrameBound, end: RowsFrameBound) -> Frame {
391 Frame::rows(start, end)
392 }
393
394 fn range_frame(start: FrameBound<i64>, end: FrameBound<i64>, order_type: OrderType) -> Frame {
395 let bound = |bound: FrameBound<i64>| -> RangeFrameBound {
397 bound.map(|offset| RangeFrameOffset::new(ScalarImpl::Int64(offset)))
398 };
399 Frame {
400 bounds: FrameBounds::Range(RangeFrameBounds {
401 order_data_type: DataType::Int64,
402 order_type,
403 offset_data_type: DataType::Int64,
404 start: bound(start),
405 end: bound(end),
406 }),
407 exclusion: FrameExclusion::default(),
408 }
409 }
410
411 fn session_frame(order_type: OrderType) -> Frame {
412 Frame {
413 bounds: FrameBounds::Session(SessionFrameBounds {
414 order_data_type: DataType::Int64,
415 order_type,
416 gap_data_type: DataType::Int64,
417 gap: SessionFrameGap::new(ScalarImpl::Int64(10)),
418 }),
419 exclusion: FrameExclusion::default(),
420 }
421 }
422
423 #[test]
424 fn test_may_close_by_watermark() {
425 let asc = OrderType::ascending();
426 let may_close = |frame: Frame| frame.bounds.may_close_by_watermark();
427
428 assert!(!may_close(rows_frame(Preceding(1), Preceding(1))));
429 assert!(!may_close(rows_frame(CurrentRow, Following(1))));
430 assert!(may_close(range_frame(UnboundedPreceding, CurrentRow, asc)));
431 assert!(may_close(range_frame(CurrentRow, Following(10), asc)));
432 assert!(may_close(range_frame(Preceding(10), Preceding(0), asc)));
433 assert!(!may_close(range_frame(Preceding(10), Preceding(5), asc)));
434 assert!(!may_close(range_frame(CurrentRow, UnboundedFollowing, asc)));
435 assert!(may_close(session_frame(asc)));
436
437 let preceding = |order_data_type: DataType, offset_data_type, offset: ScalarImpl| Frame {
439 bounds: FrameBounds::Range(RangeFrameBounds {
440 order_data_type,
441 order_type: asc,
442 offset_data_type,
443 start: Preceding(RangeFrameOffset::new(offset.clone())),
444 end: Preceding(RangeFrameOffset::new(offset)),
445 }),
446 exclusion: FrameExclusion::default(),
447 };
448 assert!(may_close(preceding(
449 DataType::Float64,
450 DataType::Float64,
451 1.0f64.into()
452 )));
453 assert!(may_close(preceding(
454 DataType::Float32,
455 DataType::Float32,
456 1.0f32.into()
457 )));
458 assert!(may_close(preceding(
459 DataType::Decimal,
460 DataType::Decimal,
461 Decimal::from(1).into()
462 )));
463 assert!(!may_close(preceding(
464 DataType::Timestamp,
465 DataType::Interval,
466 Interval::from_month_day_usec(1, 0, 0).into()
467 )));
468 }
469
470 #[test]
471 fn test_can_forward_watermark_on_order_key() {
472 let asc = OrderType::ascending(); let desc = OrderType::descending(); let can_forward =
475 |frames: &[Frame], order_type| can_forward_watermark_on_order_key(frames, order_type);
476
477 let preceding_only = [
478 rows_frame(UnboundedPreceding, CurrentRow), rows_frame(Preceding(1), Preceding(1)), rows_frame(Preceding(2), CurrentRow),
481 ];
482 let following_only = [
483 rows_frame(CurrentRow, UnboundedFollowing),
484 rows_frame(Following(1), Following(1)), rows_frame(CurrentRow, Following(2)),
486 ];
487 let current_row_only = [rows_frame(CurrentRow, CurrentRow)];
488 let both_sides = [
489 rows_frame(Preceding(1), Following(1)),
490 rows_frame(UnboundedPreceding, UnboundedFollowing),
491 ];
492
493 assert!(can_forward(&preceding_only, asc));
494 assert!(!can_forward(&preceding_only, desc));
495 assert!(!can_forward(&following_only, asc));
496 assert!(can_forward(&following_only, desc));
497 assert!(can_forward(¤t_row_only, asc));
498 assert!(can_forward(¤t_row_only, desc));
499 assert!(!can_forward(&both_sides, asc));
500 assert!(!can_forward(&both_sides, desc));
501
502 let mixed = [
504 rows_frame(Preceding(1), Preceding(1)),
505 rows_frame(Following(1), Following(1)),
506 ];
507 assert!(!can_forward(&mixed, asc));
508 assert!(!can_forward(&mixed, desc));
509
510 for order_type in [asc, desc] {
512 let preceding_only = [range_frame(Preceding(10), CurrentRow, order_type)];
513 let following_only = [range_frame(CurrentRow, Following(10), order_type)];
514 let both_sides = [range_frame(Preceding(10), Following(10), order_type)];
515 assert_eq!(
516 can_forward(&preceding_only, order_type),
517 order_type.is_ascending()
518 );
519 assert_eq!(
520 can_forward(&following_only, order_type),
521 order_type.is_descending()
522 );
523 assert!(!can_forward(&both_sides, order_type));
524 }
525
526 for order_type in [asc, desc] {
528 assert!(!can_forward(&[session_frame(order_type)], order_type));
529 }
530
531 assert!(!can_forward(
533 &preceding_only,
534 OrderType::ascending_nulls_first()
535 ));
536 assert!(!can_forward(
537 &following_only,
538 OrderType::descending_nulls_last()
539 ));
540 assert!(can_forward(
541 &preceding_only,
542 OrderType::ascending_nulls_last()
543 ));
544 assert!(can_forward(
545 &following_only,
546 OrderType::descending_nulls_first()
547 ));
548 }
549}