Skip to main content

risingwave_expr/window_function/
range.rs

1// Copyright 2024 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use 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                // TODO(rc): use decl macro?
111                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                        // for `timestamptz`, we only support offset without `month` and `day` fields
126                        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    /// Get the frame start for a given order column value.
144    ///
145    /// ## Examples
146    ///
147    /// For the following frames:
148    ///
149    /// ```sql
150    /// ORDER BY x ASC RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
151    /// ORDER BY x DESC RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
152    /// ```
153    ///
154    /// For any CURRENT ROW with any order value, the frame start is always the first-most row, which is
155    /// represented by [`Sentinelled::Smallest`].
156    ///
157    /// For the following frame:
158    ///
159    /// ```sql
160    /// ORDER BY x ASC RANGE BETWEEN 10 PRECEDING AND CURRENT ROW
161    /// ```
162    ///
163    /// For CURRENT ROW with order value `100`, the frame start is the **FIRST** row with order value `90`.
164    ///
165    /// For the following frame:
166    ///
167    /// ```sql
168    /// ORDER BY x DESC RANGE BETWEEN 10 PRECEDING AND CURRENT ROW
169    /// ```
170    ///
171    /// For CURRENT ROW with order value `100`, the frame start is the **FIRST** row with order value `110`.
172    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    /// Get the frame end for a given order column value. It's very similar to `frame_start_of`, just with
177    /// everything on the other direction.
178    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    /// Get the order value of the CURRENT ROW of the first frame that includes the given order value.
183    ///
184    /// ## Examples
185    ///
186    /// For the following frames:
187    ///
188    /// ```sql
189    /// ORDER BY x ASC RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
190    /// ORDER BY x DESC RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
191    /// ```
192    ///
193    /// For any given order value, the first CURRENT ROW is always the first-most row, which is
194    /// represented by [`Sentinelled::Smallest`].
195    ///
196    /// For the following frame:
197    ///
198    /// ```sql
199    /// ORDER BY x ASC RANGE BETWEEN CURRENT ROW AND 10 FOLLOWING
200    /// ```
201    ///
202    /// For a given order value `100`, the first CURRENT ROW should have order value `90`.
203    ///
204    /// For the following frame:
205    ///
206    /// ```sql
207    /// ORDER BY x DESC RANGE BETWEEN CURRENT ROW AND 10 FOLLOWING
208    /// ```
209    ///
210    /// For a given order value `100`, the first CURRENT ROW should have order value `110`.
211    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    /// Get the order value of the CURRENT ROW of the last frame that includes the given order value.
219    /// It's very similar to `first_curr_of`, just with everything on the other direction.
220    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/// The wrapper type for [`ScalarImpl`] range frame offset, containing
307/// two expressions to help adding and subtracting the offset.
308#[derive(Debug, Clone, Educe)]
309#[educe(PartialEq, Eq, Hash)]
310pub struct RangeFrameOffset {
311    /// The original offset value.
312    offset: ScalarImpl,
313    /// Built expression for `$0 + offset`.
314    #[educe(PartialEq(ignore), Hash(ignore))]
315    add_expr: Option<Arc<dyn SyncExpression>>,
316    /// Built expression for `$0 - offset`.
317    #[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    /// Built expression for `$0 + offset`.
396    add_expr: &'a dyn SyncExpression,
397    /// Built expression for `$0 - offset`.
398    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                // should SUBTRACT the offset
410                offset.sub_expr
411            }
412            (Following(offset), Direction::Ascending)
413            | (Preceding(offset), Direction::Descending) => {
414                // should ADD the offset
415                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"), // TODO(rc): handle overflow
422        )
423    }
424}