1use std::fmt::Display;
16use std::ops::Deref;
17use std::sync::Arc;
18
19use anyhow::Context;
20use educe::Educe;
21use num_traits::Zero;
22use risingwave_common::bail;
23use risingwave_common::row::OwnedRow;
24use risingwave_common::types::{
25 DataType, Datum, IsNegative, ScalarImpl, ScalarRefImpl, Sentinelled, ToOwnedDatum, ToText,
26};
27use risingwave_common::util::sort_util::{Direction, OrderType};
28use risingwave_common::util::value_encoding::{DatumFromProtoExt, DatumToProtoExt};
29use risingwave_pb::expr::window_frame::{PbBoundType, PbRangeFrameBound, PbRangeFrameBounds};
30
31use super::FrameBound::{
32 self, CurrentRow, Following, Preceding, UnboundedFollowing, UnboundedPreceding,
33};
34use super::FrameBoundsImpl;
35use crate::Result;
36use crate::expr::{
37 InputRefExpression, LiteralExpression, SyncExpression, SyncExpressionBoxExt, build_func,
38};
39
40#[derive(Debug, Clone, Eq, PartialEq, Hash)]
41pub struct RangeFrameBounds {
42 pub order_data_type: DataType,
43 pub order_type: OrderType,
44 pub offset_data_type: DataType,
45 pub start: RangeFrameBound,
46 pub end: RangeFrameBound,
47}
48
49impl RangeFrameBounds {
50 pub(super) fn from_protobuf(bounds: &PbRangeFrameBounds) -> Result<Self> {
51 let order_data_type = DataType::from(bounds.get_order_data_type()?);
52 let order_type = OrderType::from_protobuf(bounds.get_order_type()?);
53 let offset_data_type = DataType::from(bounds.get_offset_data_type()?);
54 let start = FrameBound::<RangeFrameOffset>::from_protobuf(
55 bounds.get_start()?,
56 &order_data_type,
57 &offset_data_type,
58 )?;
59 let end = FrameBound::<RangeFrameOffset>::from_protobuf(
60 bounds.get_end()?,
61 &order_data_type,
62 &offset_data_type,
63 )?;
64 Ok(Self {
65 order_data_type,
66 order_type,
67 offset_data_type,
68 start,
69 end,
70 })
71 }
72
73 pub(super) fn to_protobuf(&self) -> PbRangeFrameBounds {
74 PbRangeFrameBounds {
75 start: Some(self.start.to_protobuf()),
76 end: Some(self.end.to_protobuf()),
77 order_data_type: Some(self.order_data_type.to_protobuf()),
78 order_type: Some(self.order_type.to_protobuf()),
79 offset_data_type: Some(self.offset_data_type.to_protobuf()),
80 }
81 }
82}
83
84impl Display for RangeFrameBounds {
85 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
86 write!(
87 f,
88 "RANGE BETWEEN {} AND {}",
89 self.start.for_display(),
90 self.end.for_display()
91 )?;
92 Ok(())
93 }
94}
95
96impl FrameBoundsImpl for RangeFrameBounds {
97 fn validate(&self) -> Result<()> {
98 fn validate_non_negative(val: impl IsNegative + Display) -> Result<()> {
99 if val.is_negative() {
100 bail!(
101 "frame bound offset should be non-negative, but {} is given",
102 val
103 );
104 }
105 Ok(())
106 }
107
108 FrameBound::validate_bounds(&self.start, &self.end, |offset| {
109 match offset.as_scalar_ref_impl() {
110 ScalarRefImpl::Int16(val) => validate_non_negative(val)?,
112 ScalarRefImpl::Int32(val) => validate_non_negative(val)?,
113 ScalarRefImpl::Int64(val) => validate_non_negative(val)?,
114 ScalarRefImpl::Float32(val) => validate_non_negative(val)?,
115 ScalarRefImpl::Float64(val) => validate_non_negative(val)?,
116 ScalarRefImpl::Decimal(val) => validate_non_negative(val)?,
117 ScalarRefImpl::Interval(val) => {
118 if !val.is_never_negative() {
119 bail!(
120 "for frame bound offset of type `interval`, each field should be non-negative, but {} is given",
121 val
122 );
123 }
124 if matches!(self.order_data_type, DataType::Timestamptz) {
125 if val.months() != 0 || val.days() != 0 {
127 bail!(
128 "for frame order column of type `timestamptz`, offset should not have non-zero `month` and `day`",
129 );
130 }
131 }
132 }
133 _ => unreachable!(
134 "other order column data types are not supported and should be banned in frontend"
135 ),
136 }
137 Ok(())
138 })
139 }
140}
141
142impl RangeFrameBounds {
143 pub fn frame_start_of(&self, order_value: impl ToOwnedDatum) -> Sentinelled<Datum> {
173 self.start.for_calc().bound_of(order_value, self.order_type)
174 }
175
176 pub fn frame_end_of(&self, order_value: impl ToOwnedDatum) -> Sentinelled<Datum> {
179 self.end.for_calc().bound_of(order_value, self.order_type)
180 }
181
182 pub fn first_curr_of(&self, order_value: impl ToOwnedDatum) -> Sentinelled<Datum> {
212 self.end
213 .for_calc()
214 .reverse()
215 .bound_of(order_value, self.order_type)
216 }
217
218 pub fn last_curr_of(&self, order_value: impl ToOwnedDatum) -> Sentinelled<Datum> {
221 self.start
222 .for_calc()
223 .reverse()
224 .bound_of(order_value, self.order_type)
225 }
226}
227
228pub type RangeFrameBound = FrameBound<RangeFrameOffset>;
229
230impl RangeFrameBound {
231 fn from_protobuf(
232 bound: &PbRangeFrameBound,
233 order_data_type: &DataType,
234 offset_data_type: &DataType,
235 ) -> Result<Self> {
236 let bound = match bound.get_type()? {
237 PbBoundType::Unspecified => bail!("unspecified type of `RangeFrameBound`"),
238 PbBoundType::UnboundedPreceding => Self::UnboundedPreceding,
239 PbBoundType::CurrentRow => Self::CurrentRow,
240 PbBoundType::UnboundedFollowing => Self::UnboundedFollowing,
241 bound_type @ (PbBoundType::Preceding | PbBoundType::Following) => {
242 let offset_value = Datum::from_protobuf(bound.get_offset()?, offset_data_type)
243 .context("offset `Datum` is not decodable")?
244 .context("offset of `RangeFrameBound` must be non-NULL")?;
245 let mut offset = RangeFrameOffset::new(offset_value);
246 offset.prepare(order_data_type, offset_data_type)?;
247 if bound_type == PbBoundType::Preceding {
248 Self::Preceding(offset)
249 } else {
250 Self::Following(offset)
251 }
252 }
253 };
254 Ok(bound)
255 }
256
257 fn to_protobuf(&self) -> PbRangeFrameBound {
258 let (r#type, offset) = match self {
259 Self::UnboundedPreceding => (PbBoundType::UnboundedPreceding, None),
260 Self::Preceding(offset) => (
261 PbBoundType::Preceding,
262 Some(Some(offset.as_scalar_ref_impl()).to_protobuf()),
263 ),
264 Self::CurrentRow => (PbBoundType::CurrentRow, None),
265 Self::Following(offset) => (
266 PbBoundType::Following,
267 Some(Some(offset.as_scalar_ref_impl()).to_protobuf()),
268 ),
269 Self::UnboundedFollowing => (PbBoundType::UnboundedFollowing, None),
270 };
271 PbRangeFrameBound {
272 r#type: r#type as _,
273 offset,
274 }
275 }
276}
277
278impl RangeFrameBound {
279 fn for_display(&self) -> FrameBound<String> {
280 match self {
281 UnboundedPreceding => UnboundedPreceding,
282 Preceding(offset) => Preceding(offset.as_scalar_ref_impl().to_text()),
283 CurrentRow => CurrentRow,
284 Following(offset) => Following(offset.as_scalar_ref_impl().to_text()),
285 UnboundedFollowing => UnboundedFollowing,
286 }
287 }
288
289 fn for_calc(&self) -> FrameBound<RangeFrameOffsetRef<'_>> {
290 match self {
291 UnboundedPreceding => UnboundedPreceding,
292 Preceding(offset) => Preceding(RangeFrameOffsetRef {
293 add_expr: offset.add_expr.as_ref().unwrap().as_ref(),
294 sub_expr: offset.sub_expr.as_ref().unwrap().as_ref(),
295 }),
296 CurrentRow => CurrentRow,
297 Following(offset) => Following(RangeFrameOffsetRef {
298 add_expr: offset.add_expr.as_ref().unwrap().as_ref(),
299 sub_expr: offset.sub_expr.as_ref().unwrap().as_ref(),
300 }),
301 UnboundedFollowing => UnboundedFollowing,
302 }
303 }
304}
305
306#[derive(Debug, Clone, Educe)]
309#[educe(PartialEq, Eq, Hash)]
310pub struct RangeFrameOffset {
311 offset: ScalarImpl,
313 #[educe(PartialEq(ignore), Hash(ignore))]
315 add_expr: Option<Arc<dyn SyncExpression>>,
316 #[educe(PartialEq(ignore), Hash(ignore))]
318 sub_expr: Option<Arc<dyn SyncExpression>>,
319}
320
321impl RangeFrameOffset {
322 pub fn new(offset: ScalarImpl) -> Self {
323 Self {
324 offset,
325 add_expr: None,
326 sub_expr: None,
327 }
328 }
329
330 pub fn is_zero(&self) -> bool {
331 match self.offset.as_scalar_ref_impl() {
332 ScalarRefImpl::Int16(val) => val == 0,
333 ScalarRefImpl::Int32(val) => val == 0,
334 ScalarRefImpl::Int64(val) => val == 0,
335 ScalarRefImpl::Float32(val) => val.is_zero(),
336 ScalarRefImpl::Float64(val) => val.is_zero(),
337 ScalarRefImpl::Decimal(val) => val.is_zero(),
338 ScalarRefImpl::Interval(val) => val.is_zero(),
339 _ => unreachable!(
340 "other order column data types are not supported and should be banned in frontend"
341 ),
342 }
343 }
344
345 fn prepare(&mut self, order_data_type: &DataType, offset_data_type: &DataType) -> Result<()> {
346 use risingwave_pb::expr::expr_node::PbType as PbExprType;
347
348 let input_expr = InputRefExpression::new(order_data_type.clone(), 0);
349 let offset_expr =
350 LiteralExpression::new(offset_data_type.clone(), Some(self.offset.clone()));
351 let add_expr = build_func(
352 PbExprType::Add,
353 order_data_type.clone(),
354 vec![input_expr.clone().boxed(), offset_expr.clone().boxed()],
355 )?;
356 let crate::expr::BoxedExpression::Sync(add_expr) = add_expr else {
357 bail!("range frame offset add expression must be sync");
358 };
359 self.add_expr = Some(add_expr);
360
361 let sub_expr = build_func(
362 PbExprType::Subtract,
363 order_data_type.clone(),
364 vec![input_expr.boxed(), offset_expr.boxed()],
365 )?;
366 let crate::expr::BoxedExpression::Sync(sub_expr) = sub_expr else {
367 bail!("range frame offset subtract expression must be sync");
368 };
369 self.sub_expr = Some(sub_expr);
370 Ok(())
371 }
372
373 pub fn new_for_test(
374 offset: ScalarImpl,
375 order_data_type: &DataType,
376 offset_data_type: &DataType,
377 ) -> Self {
378 let mut offset = Self::new(offset);
379 offset.prepare(order_data_type, offset_data_type).unwrap();
380 offset
381 }
382}
383
384impl Deref for RangeFrameOffset {
385 type Target = ScalarImpl;
386
387 fn deref(&self) -> &Self::Target {
388 &self.offset
389 }
390}
391
392#[derive(Debug, Educe)]
393#[educe(Clone, Copy)]
394struct RangeFrameOffsetRef<'a> {
395 add_expr: &'a dyn SyncExpression,
397 sub_expr: &'a dyn SyncExpression,
399}
400
401impl FrameBound<RangeFrameOffsetRef<'_>> {
402 fn bound_of(self, order_value: impl ToOwnedDatum, order_type: OrderType) -> Sentinelled<Datum> {
403 let expr = match (self, order_type.direction()) {
404 (UnboundedPreceding, _) => return Sentinelled::Smallest,
405 (UnboundedFollowing, _) => return Sentinelled::Largest,
406 (CurrentRow, _) => return Sentinelled::Normal(order_value.to_owned_datum()),
407 (Preceding(offset), Direction::Ascending)
408 | (Following(offset), Direction::Descending) => {
409 offset.sub_expr
411 }
412 (Following(offset), Direction::Ascending)
413 | (Preceding(offset), Direction::Descending) => {
414 offset.add_expr
416 }
417 };
418 let row = OwnedRow::new(vec![order_value.to_owned_datum()]);
419 Sentinelled::Normal(
420 expr.eval_row(&row)
421 .expect("just simple calculation, should succeed"), )
423 }
424}