Skip to main content

diesel/expression/functions/aggregate_expressions/
frame_clause.rs

1use super::aggregate_filter::NoFilter;
2use super::aggregate_order::{NoOrder, Order};
3use super::over_clause::{NoWindow, OverClause, ValidAggregateFilterForWindow};
4use super::partition_by::NoPartition;
5use super::prefix::NoPrefix;
6use super::{AggregateExpression, IsWindowFunction};
7use crate::backend::sql_dialect;
8use crate::query_builder::{QueryFragment, QueryId};
9use alloc::string::ToString;
10
11empty_clause!(NoFrame);
12
13#[derive(QueryId, Copy, Clone, Debug)]
14pub struct FrameClause<F>(F);
15
16impl<F, DB> QueryFragment<DB> for FrameClause<F>
17where
18    F: QueryFragment<DB>,
19    DB: crate::backend::Backend,
20{
21    fn walk_ast<'b>(
22        &'b self,
23        pass: crate::query_builder::AstPass<'_, 'b, DB>,
24    ) -> crate::QueryResult<()> {
25        self.0.walk_ast(pass)?;
26        Ok(())
27    }
28}
29
30macro_rules! simple_frame_expr {
31    ($(#[doc = $doc: literal])* $name: ident, $kind: expr_2021) => {
32        #[derive(QueryId, Clone, Copy, Debug)]
33        $(#[doc = $doc])*
34        pub struct $name;
35
36        impl<DB> QueryFragment<DB> for $name
37        where
38            DB: crate::backend::Backend,
39        {
40            fn walk_ast<'b>(
41                &'b self,
42                mut pass: crate::query_builder::AstPass<'_, 'b, DB>,
43            ) -> crate::QueryResult<()> {
44                pass.push_sql($kind);
45                Ok(())
46            }
47        }
48    };
49}
50
51macro_rules! simple_frame_expr_with_bound {
52    ($(#[doc = $doc:literal])* $name: ident, $option: ident, $bound: ty, $kind: expr_2021) => {
53        #[derive(QueryId, Clone, Copy, Debug)]
54        $(#[doc = $doc])*
55        pub struct $name;
56
57        impl<DB> QueryFragment<DB> for $name
58        where
59            DB: crate::backend::Backend,
60            Self: QueryFragment<DB, DB::$option>,
61        {
62            fn walk_ast<'b>(
63                &'b self,
64                pass: crate::query_builder::AstPass<'_, 'b, DB>,
65            ) -> crate::QueryResult<()> {
66                <Self as QueryFragment<DB, DB::$option>>::walk_ast(self, pass)
67            }
68        }
69        impl<DB> QueryFragment<DB, $bound> for $name
70        where
71            DB: crate::backend::Backend<$option = $bound>,
72        {
73            fn walk_ast<'b>(
74                &'b self,
75                mut pass: crate::query_builder::AstPass<'_, 'b, DB>,
76            ) -> crate::QueryResult<()> {
77                pass.push_sql($kind);
78                Ok(())
79            }
80        }
81    };
82}
83
84// kinds
85simple_frame_expr!(
86    /// Range frame mode
87    ///
88    /// Requires to set a `ORDER BY` clause set via `window_order`
89    /// for the current window function call
90    Range,
91    " RANGE "
92);
93simple_frame_expr!(
94    /// Rows frame mode
95    ///
96    /// This options specifies that the offset starts/ends
97    /// a certain number of rows before/after the current row
98    Rows,
99    " ROWS "
100);
101simple_frame_expr_with_bound!(
102    /// Groups frame mode
103    ///
104    /// This options specifies that the offset starts/ends
105    /// a certain number of peer groups before or after
106    /// the current row. A peer group is a set of rows that are
107    /// equivalent in the `ORDER BY` ordering
108    ///
109    /// There must be a `ORDER BY` clause set via `window_order`
110    /// for the current window function call
111    Groups,
112    WindowFrameClauseGroupSupport,
113    sql_dialect::window_frame_clause_group_support::IsoGroupWindowFrameUnit,
114    " GROUPS "
115);
116
117// start & end
118simple_frame_expr!(
119    /// A `UNBOUNDED PRECEDING` frame bound
120    ///
121    /// This bound specifies that the frame starts with
122    /// the first row of the partition
123    ///
124    /// This option can be used as frame start
125    UnboundedPreceding,
126    "UNBOUNDED PRECEDING "
127);
128simple_frame_expr!(
129    /// A `CURRENT ROW` frame bound
130    ///
131    /// For the `RANGE` and `GROUP` frame mode this bound
132    /// specifies that the current frame starts with the current
133    /// rows first peer groups row. A peer group is defined as a
134    /// set of rows with an equivalent `ORDER BY` ordering.
135    ///
136    /// For the `ROWS` mode `CURRENT ROW` simply means the current
137    /// row
138    ///
139    /// This option can be used as frame start and end
140    CurrentRow,
141    "CURRENT ROW "
142);
143simple_frame_expr!(
144    /// A `UNBOUNDED FOLLOWING` frame bound
145    ///
146    /// This bound specifies that the frame ends with
147    /// the last row of the partition
148    ///
149    /// This option can be used as frame end
150    UnboundedFollowing,
151    "UNBOUNDED FOLLOWING "
152);
153
154// exclusion
155simple_frame_expr_with_bound!(
156    /// Exclude the current row from the window frame
157    ExcludeCurrentRow,
158    WindowFrameExclusionSupport,
159    sql_dialect::window_frame_exclusion_support::FrameExclusionSupport,
160    "EXCLUDE CURRENT ROW "
161);
162simple_frame_expr_with_bound!(
163    /// Exclude the current peer group from the window frame
164    ///
165    /// A peer group is a set of rows with an equivalent `ORDER BY`
166    /// ordering
167    ExcludeGroup,
168    WindowFrameExclusionSupport,
169    sql_dialect::window_frame_exclusion_support::FrameExclusionSupport,
170    "EXCLUDE GROUP "
171);
172simple_frame_expr_with_bound!(
173    /// Exclude any peers, but not the current row from the window frame
174    ///
175    /// This excludes any row with an equivalent `ORDER BY` ordering
176    /// to the current row from the frame window
177    ExcludeTies,
178    WindowFrameExclusionSupport,
179    sql_dialect::window_frame_exclusion_support::FrameExclusionSupport,
180    "EXCLUDE TIES "
181);
182simple_frame_expr_with_bound!(
183    /// Exclude no rows from the frame windows
184    ///
185    /// This is the default behaviour if not specified
186    ExcludeNoOthers,
187    WindowFrameExclusionSupport,
188    sql_dialect::window_frame_exclusion_support::FrameExclusionSupport,
189    "EXCLUDE NO OTHERS "
190);
191
192/// A preceding frame clause expression with a fixed offset
193///
194/// Can be constructed via [`FrameBoundDsl::preceding`]
195#[derive(Clone, Copy, Debug)]
196pub struct OffsetPreceding<T = u64>(T);
197
198// manual impl as the derive makes this dependent on a `T: QueryId` impl
199// which is wrong
200impl QueryId for OffsetPreceding {
201    type QueryId = ();
202
203    // it's not safe to cache by type id
204    // as we inline a dynamic value (the offset) directly
205    // into the SQL
206    const HAS_STATIC_QUERY_ID: bool = false;
207}
208
209impl<DB> QueryFragment<DB> for OffsetPreceding
210where
211    DB: crate::backend::Backend,
212{
213    fn walk_ast<'b>(
214        &'b self,
215        mut pass: crate::query_builder::AstPass<'_, 'b, DB>,
216    ) -> crate::QueryResult<()> {
217        // we cannot use binds here as mysql doesn't support it :(
218        // at least it's safe to just insert a number here
219        pass.push_sql(&self.0.to_string());
220        pass.push_sql(" PRECEDING ");
221        Ok(())
222    }
223}
224
225/// A following frame clause expression with a fixed offset
226///
227/// Can be constructed via [`FrameBoundDsl::following`]
228#[derive(Clone, Copy, Debug)]
229pub struct OffsetFollowing<I = u64>(I);
230
231// manual impl as the derive makes this dependent on a `T: QueryId` impl
232// which is wrong
233impl QueryId for OffsetFollowing {
234    type QueryId = ();
235
236    // it's not safe to cache by type id
237    // as we inline a dynamic value (the offset) directly
238    // into the SQL
239    const HAS_STATIC_QUERY_ID: bool = false;
240}
241
242impl<DB> QueryFragment<DB> for OffsetFollowing
243where
244    DB: crate::backend::Backend,
245{
246    fn walk_ast<'b>(
247        &'b self,
248        mut pass: crate::query_builder::AstPass<'_, 'b, DB>,
249    ) -> crate::QueryResult<()> {
250        // we cannot use binds here as mysql doesn't support it :(
251        // at least it's safe to just insert a number here
252        pass.push_sql(&self.0.to_string());
253        pass.push_sql(" FOLLOWING ");
254        Ok(())
255    }
256}
257
258pub trait FrameDsl<F> {
259    type Output;
260
261    fn frame(self, expr: F) -> Self::Output;
262}
263
264#[diagnostic::on_unimplemented(
265    message = "`Groups` frame clauses require a ordered window function",
266    note = "call `.window_order(some_column)` first"
267)]
268pub trait ValidFrameClause<O> {}
269
270impl<O, Kind, Start, End, Exclusion> ValidFrameClause<O>
271    for BetweenFrame<Kind, Start, End, Exclusion>
272where
273    Kind: ValidFrameClause<O>,
274{
275}
276impl<O, Kind, Start, Exclusion> ValidFrameClause<O> for StartFrame<Kind, Start, Exclusion> where
277    Kind: ValidFrameClause<O>
278{
279}
280impl<O> ValidFrameClause<O> for Rows {}
281impl<O> ValidFrameClause<O> for Range {}
282impl<O> ValidFrameClause<Order<O, true>> for Groups {}
283
284impl<E, Fn, Filter, Frame, Partition, Order> FrameDsl<E>
285    for AggregateExpression<Fn, NoPrefix, NoOrder, Filter, OverClause<Partition, Order, Frame>>
286where
287    E: FrameClauseExpression,
288    E: ValidFrameClause<Order>,
289    Filter: ValidAggregateFilterForWindow<Fn, OverClause<Partition, Order, FrameClause<E>>>,
290{
291    type Output = AggregateExpression<
292        Fn,
293        NoPrefix,
294        NoOrder,
295        Filter,
296        OverClause<Partition, Order, FrameClause<E>>,
297    >;
298
299    fn frame(self, expr: E) -> Self::Output {
300        AggregateExpression {
301            prefix: self.prefix,
302            function: self.function,
303            order: self.order,
304            filter: self.filter,
305            window: OverClause {
306                partition_by: self.window.partition_by,
307                order: self.window.order,
308                frame_clause: FrameClause(expr),
309            },
310        }
311    }
312}
313
314impl<E, Fn, Filter> FrameDsl<E> for AggregateExpression<Fn, NoPrefix, NoOrder, Filter, NoWindow>
315where
316    E: FrameClauseExpression,
317    E: ValidFrameClause<NoOrder>,
318    Filter: ValidAggregateFilterForWindow<Fn, OverClause<NoPartition, NoOrder, FrameClause<E>>>,
319{
320    type Output = AggregateExpression<
321        Fn,
322        NoPrefix,
323        NoOrder,
324        Filter,
325        OverClause<NoPartition, NoOrder, FrameClause<E>>,
326    >;
327
328    fn frame(self, expr: E) -> Self::Output {
329        AggregateExpression {
330            prefix: self.prefix,
331            function: self.function,
332            order: self.order,
333            filter: self.filter,
334            window: OverClause {
335                partition_by: NoPartition,
336                order: NoOrder,
337                frame_clause: FrameClause(expr),
338            },
339        }
340    }
341}
342
343impl<E, Fn> FrameDsl<E> for Fn
344where
345    Fn: IsWindowFunction,
346    E: FrameClauseExpression,
347    E: ValidFrameClause<NoOrder>,
348{
349    type Output = AggregateExpression<
350        Fn,
351        NoPrefix,
352        NoOrder,
353        NoFilter,
354        OverClause<NoPartition, NoOrder, FrameClause<E>>,
355    >;
356
357    fn frame(self, expr: E) -> Self::Output {
358        AggregateExpression {
359            prefix: NoPrefix,
360            function: self,
361            order: NoOrder,
362            filter: NoFilter,
363            window: OverClause {
364                partition_by: NoPartition,
365                order: NoOrder,
366                frame_clause: FrameClause(expr),
367            },
368        }
369    }
370}
371
372pub trait FrameClauseExpression {}
373
374/// A marker trait for possible start frame expressions
375///
376/// See the list of types implementing this trait to understand
377/// what can be used in this position
378pub trait FrameClauseStartBound: Sealed {}
379
380/// A marker trait for possible end frame expressions
381///
382/// See the list of types implementing this trait to understand
383/// what can be used in this position
384pub trait FrameClauseEndBound: Sealed {}
385
386impl FrameClauseEndBound for UnboundedFollowing {}
387impl Sealed for UnboundedFollowing {}
388impl FrameClauseStartBound for UnboundedPreceding {}
389impl Sealed for UnboundedPreceding {}
390impl FrameClauseEndBound for CurrentRow {}
391impl FrameClauseStartBound for CurrentRow {}
392impl Sealed for CurrentRow {}
393impl FrameClauseEndBound for OffsetFollowing {}
394impl Sealed for OffsetFollowing {}
395impl FrameClauseStartBound for OffsetPreceding {}
396impl Sealed for OffsetPreceding {}
397
398/// A marker trait for possible frame exclusion expressions
399///
400/// See the list of types implementing this trait to understand
401/// what can be used in this position
402pub trait FrameClauseExclusion: Sealed {}
403
404impl FrameClauseExclusion for ExcludeGroup {}
405impl Sealed for ExcludeGroup {}
406impl FrameClauseExclusion for ExcludeNoOthers {}
407impl Sealed for ExcludeNoOthers {}
408impl FrameClauseExclusion for ExcludeTies {}
409impl Sealed for ExcludeTies {}
410impl FrameClauseExclusion for ExcludeCurrentRow {}
411impl Sealed for ExcludeCurrentRow {}
412
413/// Construct a frame clause for window functions from an integer
414pub trait FrameBoundDsl {
415    /// Use the preceding frame clause specification
416    fn preceding(self) -> OffsetPreceding;
417
418    /// Use the following frame clause specification
419    fn following(self) -> OffsetFollowing;
420}
421
422impl FrameBoundDsl for u64 {
423    fn preceding(self) -> OffsetPreceding {
424        OffsetPreceding(self)
425    }
426
427    fn following(self) -> OffsetFollowing {
428        OffsetFollowing(self)
429    }
430}
431// TODO: We might want to implement
432// it for datetime and date intervals?
433// The postgres documentation indicates that
434// something like `RANGE BETWEEN '1 day' PRECEDING AND '10 days' FOLLOWING`
435// is valid
436
437empty_clause!(NoExclusion);
438
439#[derive(QueryId, Copy, Clone, Debug)]
440pub struct StartFrame<Kind, Start, Exclusion = NoExclusion> {
441    kind: Kind,
442    start: Start,
443    exclusion: Exclusion,
444}
445
446impl<Kind, Start, Exclusion, DB> QueryFragment<DB> for StartFrame<Kind, Start, Exclusion>
447where
448    Kind: QueryFragment<DB>,
449    Start: QueryFragment<DB>,
450    Exclusion: QueryFragment<DB>,
451    DB: crate::backend::Backend,
452{
453    fn walk_ast<'b>(
454        &'b self,
455        mut pass: crate::query_builder::AstPass<'_, 'b, DB>,
456    ) -> crate::QueryResult<()> {
457        self.kind.walk_ast(pass.reborrow())?;
458        self.start.walk_ast(pass.reborrow())?;
459        self.exclusion.walk_ast(pass.reborrow())?;
460        Ok(())
461    }
462}
463
464impl<Kind, Start, Exclusion> FrameClauseExpression for StartFrame<Kind, Start, Exclusion> {}
465
466#[derive(QueryId, Copy, Clone, Debug)]
467pub struct BetweenFrame<Kind, Start, End, Exclusion = NoExclusion> {
468    kind: Kind,
469    start: Start,
470    end: End,
471    exclusion: Exclusion,
472}
473
474impl<Kind, Start, End, Exclusion, DB> QueryFragment<DB>
475    for BetweenFrame<Kind, Start, End, Exclusion>
476where
477    Kind: QueryFragment<DB>,
478    Start: QueryFragment<DB>,
479    End: QueryFragment<DB>,
480    Exclusion: QueryFragment<DB>,
481    DB: crate::backend::Backend,
482{
483    fn walk_ast<'b>(
484        &'b self,
485        mut pass: crate::query_builder::AstPass<'_, 'b, DB>,
486    ) -> crate::QueryResult<()> {
487        self.kind.walk_ast(pass.reborrow())?;
488        pass.push_sql(" BETWEEN ");
489        self.start.walk_ast(pass.reborrow())?;
490        pass.push_sql(" AND ");
491        self.end.walk_ast(pass.reborrow())?;
492        self.exclusion.walk_ast(pass.reborrow())?;
493        Ok(())
494    }
495}
496
497impl<Kind, Start, End, Exclusion> FrameClauseExpression
498    for BetweenFrame<Kind, Start, End, Exclusion>
499{
500}
501
502pub trait FrameClauseDslHelper: Sized {}
503
504/// Construct a frame clause for window functions
505pub trait FrameClauseDsl: FrameClauseDslHelper {
506    /// Construct a frame clause with a starting bound
507    fn frame_start_with<E>(self, start: E) -> super::dsl::FrameStartWith<Self, E>
508    where
509        E: FrameClauseStartBound,
510    {
511        StartFrame {
512            kind: self,
513            start,
514            exclusion: NoExclusion,
515        }
516    }
517
518    /// Construct a frame clause with a starting bound and an exclusion condition
519    fn frame_start_with_exclusion<E1, E2>(
520        self,
521        start: E1,
522        exclusion: E2,
523    ) -> super::dsl::FrameStartWithExclusion<Self, E1, E2>
524    where
525        E1: FrameClauseStartBound,
526        E2: FrameClauseExclusion,
527    {
528        StartFrame {
529            kind: self,
530            start,
531            exclusion,
532        }
533    }
534
535    /// Construct a between frame clause with a starting and end bound
536    fn frame_between<E1, E2>(self, start: E1, end: E2) -> super::dsl::FrameBetween<Self, E1, E2>
537    where
538        E1: FrameClauseStartBound,
539        E2: FrameClauseEndBound,
540    {
541        BetweenFrame {
542            kind: self,
543            start,
544            end,
545            exclusion: NoExclusion,
546        }
547    }
548
549    /// Construct a between frame clause with a starting and end bound  with an exclusion condition
550    fn frame_between_with_exclusion<E1, E2, E3>(
551        self,
552        start: E1,
553        end: E2,
554        exclusion: E3,
555    ) -> super::dsl::FrameBetweenWithExclusion<Self, E1, E2, E3>
556    where
557        E1: FrameClauseStartBound,
558        E2: FrameClauseEndBound,
559        E3: FrameClauseExclusion,
560    {
561        BetweenFrame {
562            kind: self,
563            start,
564            end,
565            exclusion,
566        }
567    }
568}
569
570impl<T> FrameClauseDsl for T where T: FrameClauseDslHelper {}
571
572impl FrameClauseDslHelper for Range {}
573impl FrameClauseDslHelper for Rows {}
574impl FrameClauseDslHelper for Groups {}
575
576pub trait Sealed {}