diesel 2.3.8

A safe, extensible ORM and Query Builder for PostgreSQL, SQLite, and MySQL
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
use crate::backend::sql_dialect;
use crate::query_builder::{QueryFragment, QueryId};

use super::aggregate_filter::NoFilter;
use super::aggregate_order::{NoOrder, Order};
use super::over_clause::{NoWindow, OverClause, ValidAggregateFilterForWindow};
use super::partition_by::NoPartition;
use super::prefix::NoPrefix;
use super::{AggregateExpression, IsWindowFunction};

empty_clause!(NoFrame);

#[derive(QueryId, Copy, Clone, Debug)]
pub struct FrameClause<F>(F);

impl<F, DB> QueryFragment<DB> for FrameClause<F>
where
    F: QueryFragment<DB>,
    DB: crate::backend::Backend,
{
    fn walk_ast<'b>(
        &'b self,
        pass: crate::query_builder::AstPass<'_, 'b, DB>,
    ) -> crate::QueryResult<()> {
        self.0.walk_ast(pass)?;
        Ok(())
    }
}

macro_rules! simple_frame_expr {
    ($(#[doc = $doc: literal])* $name: ident, $kind: expr) => {
        #[derive(QueryId, Clone, Copy, Debug)]
        $(#[doc = $doc])*
        pub struct $name;

        impl<DB> QueryFragment<DB> for $name
        where
            DB: crate::backend::Backend,
        {
            fn walk_ast<'b>(
                &'b self,
                mut pass: crate::query_builder::AstPass<'_, 'b, DB>,
            ) -> crate::QueryResult<()> {
                pass.push_sql($kind);
                Ok(())
            }
        }
    };
}

macro_rules! simple_frame_expr_with_bound {
    ($(#[doc = $doc:literal])* $name: ident, $option: ident, $bound: ty, $kind: expr) => {
        #[derive(QueryId, Clone, Copy, Debug)]
        $(#[doc = $doc])*
        pub struct $name;

        impl<DB> QueryFragment<DB> for $name
        where
            DB: crate::backend::Backend,
            Self: QueryFragment<DB, DB::$option>,
        {
            fn walk_ast<'b>(
                &'b self,
                pass: crate::query_builder::AstPass<'_, 'b, DB>,
            ) -> crate::QueryResult<()> {
                <Self as QueryFragment<DB, DB::$option>>::walk_ast(self, pass)
            }
        }
        impl<DB> QueryFragment<DB, $bound> for $name
        where
            DB: crate::backend::Backend<$option = $bound>,
        {
            fn walk_ast<'b>(
                &'b self,
                mut pass: crate::query_builder::AstPass<'_, 'b, DB>,
            ) -> crate::QueryResult<()> {
                pass.push_sql($kind);
                Ok(())
            }
        }
    };
}

// kinds
simple_frame_expr!(
    /// Range frame mode
    ///
    /// Requires to set a `ORDER BY` clause set via `window_order`
    /// for the current window function call
    Range, " RANGE ");
simple_frame_expr!(
    /// Rows frame mode
    ///
    /// This options specifies that the offset starts/ends
    /// a certain number of rows before/after the current row
    Rows, " ROWS ");
simple_frame_expr_with_bound!(
    /// Groups frame mode
    ///
    /// This options specifies that the offset starts/ends
    /// a certain number of peer groups before or after
    /// the current row. A peer group is a set of rows that are
    /// equivalent in the `ORDER BY` ordering
    ///
    /// There must be a `ORDER BY` clause set via `window_order`
    /// for the current window function call
    Groups,
    WindowFrameClauseGroupSupport,
    sql_dialect::window_frame_clause_group_support::IsoGroupWindowFrameUnit,
    " GROUPS "
);

// start & end
simple_frame_expr!(
    /// A `UNBOUNDED PRECEDING` frame bound
    ///
    /// This bound specifies that the frame starts with
    /// the first row of the partition
    ///
    /// This option can be used as frame start
    UnboundedPreceding, "UNBOUNDED PRECEDING ");
simple_frame_expr!(
    /// A `CURRENT ROW` frame bound
    ///
    /// For the `RANGE` and `GROUP` frame mode this bound
    /// specifies that the current frame starts with the current
    /// rows first peer groups row. A peer group is defined as a
    /// set of rows with an equivalent `ORDER BY` ordering.
    ///
    /// For the `ROWS` mode `CURRENT ROW` simply means the current
    /// row
    ///
    /// This option can be used as frame start and end
    CurrentRow, "CURRENT ROW ");
simple_frame_expr!(
    /// A `UNBOUNDED FOLLOWING` frame bound
    ///
    /// This bound specifies that the frame ends with
    /// the last row of the partition
    ///
    /// This option can be used as frame end
    UnboundedFollowing, "UNBOUNDED FOLLOWING ");

// exclusion
simple_frame_expr_with_bound!(
    /// Exclude the current row from the window frame
    ExcludeCurrentRow,
    WindowFrameExclusionSupport,
    sql_dialect::window_frame_exclusion_support::FrameExclusionSupport,
    "EXCLUDE CURRENT ROW "
);
simple_frame_expr_with_bound!(
    /// Exclude the current peer group from the window frame
    ///
    /// A peer group is a set of rows with an equivalent `ORDER BY`
    /// ordering
    ExcludeGroup,
    WindowFrameExclusionSupport,
    sql_dialect::window_frame_exclusion_support::FrameExclusionSupport,
    "EXCLUDE GROUP "
);
simple_frame_expr_with_bound!(
    /// Exclude any peers, but not the current row from the window frame
    ///
    /// This excludes any row with an equivalent `ORDER BY` ordering
    /// to the current row from the frame window
    ExcludeTies,
    WindowFrameExclusionSupport,
    sql_dialect::window_frame_exclusion_support::FrameExclusionSupport,
    "EXCLUDE TIES "
);
simple_frame_expr_with_bound!(
    /// Exclude no rows from the frame windows
    ///
    /// This is the default behaviour if not specified
    ExcludeNoOthers,
    WindowFrameExclusionSupport,
    sql_dialect::window_frame_exclusion_support::FrameExclusionSupport,
    "EXCLUDE NO OTHERS "
);

/// A preceding frame clause expression with a fixed offset
///
/// Can be constructed via [`FrameBoundDsl::preceding`]
#[derive(Clone, Copy, Debug)]
pub struct OffsetPreceding<T = u64>(T);

// manual impl as the derive makes this dependent on a `T: QueryId` impl
// which is wrong
impl QueryId for OffsetPreceding {
    type QueryId = ();

    const HAS_STATIC_QUERY_ID: bool = true;
}

impl<DB> QueryFragment<DB> for OffsetPreceding
where
    DB: crate::backend::Backend,
{
    fn walk_ast<'b>(
        &'b self,
        mut pass: crate::query_builder::AstPass<'_, 'b, DB>,
    ) -> crate::QueryResult<()> {
        // we cannot use binds here as mysql doesn't support it :(
        // at least it's safe to just insert a number here
        pass.push_sql(&self.0.to_string());
        pass.push_sql(" PRECEDING ");
        Ok(())
    }
}

/// A following frame clause expression with a fixed offset
///
/// Can be constructed via [`FrameBoundDsl::following`]
#[derive(Clone, Copy, Debug)]
pub struct OffsetFollowing<I = u64>(I);

// manual impl as the derive makes this dependent on a `T: QueryId` impl
// which is wrong
impl QueryId for OffsetFollowing {
    type QueryId = ();

    const HAS_STATIC_QUERY_ID: bool = true;
}

impl<DB> QueryFragment<DB> for OffsetFollowing
where
    DB: crate::backend::Backend,
{
    fn walk_ast<'b>(
        &'b self,
        mut pass: crate::query_builder::AstPass<'_, 'b, DB>,
    ) -> crate::QueryResult<()> {
        // we cannot use binds here as mysql doesn't support it :(
        // at least it's safe to just insert a number here
        pass.push_sql(&self.0.to_string());
        pass.push_sql(" FOLLOWING ");
        Ok(())
    }
}

pub trait FrameDsl<F> {
    type Output;

    fn frame(self, expr: F) -> Self::Output;
}

#[diagnostic::on_unimplemented(
    message = "`Groups` frame clauses require a ordered window function",
    note = "call `.window_order(some_column)` first"
)]
pub trait ValidFrameClause<O> {}

impl<O, Kind, Start, End, Exclusion> ValidFrameClause<O>
    for BetweenFrame<Kind, Start, End, Exclusion>
where
    Kind: ValidFrameClause<O>,
{
}
impl<O, Kind, Start, Exclusion> ValidFrameClause<O> for StartFrame<Kind, Start, Exclusion> where
    Kind: ValidFrameClause<O>
{
}
impl<O> ValidFrameClause<O> for Rows {}
impl<O> ValidFrameClause<O> for Range {}
impl<O> ValidFrameClause<Order<O, true>> for Groups {}

impl<E, Fn, Filter, Frame, Partition, Order> FrameDsl<E>
    for AggregateExpression<Fn, NoPrefix, NoOrder, Filter, OverClause<Partition, Order, Frame>>
where
    E: FrameClauseExpression,
    E: ValidFrameClause<Order>,
    Filter: ValidAggregateFilterForWindow<Fn, OverClause<Partition, Order, FrameClause<E>>>,
{
    type Output = AggregateExpression<
        Fn,
        NoPrefix,
        NoOrder,
        Filter,
        OverClause<Partition, Order, FrameClause<E>>,
    >;

    fn frame(self, expr: E) -> Self::Output {
        AggregateExpression {
            prefix: self.prefix,
            function: self.function,
            order: self.order,
            filter: self.filter,
            window: OverClause {
                partition_by: self.window.partition_by,
                order: self.window.order,
                frame_clause: FrameClause(expr),
            },
        }
    }
}

impl<E, Fn, Filter> FrameDsl<E> for AggregateExpression<Fn, NoPrefix, NoOrder, Filter, NoWindow>
where
    E: FrameClauseExpression,
    E: ValidFrameClause<NoOrder>,
    Filter: ValidAggregateFilterForWindow<Fn, OverClause<NoPartition, NoOrder, FrameClause<E>>>,
{
    type Output = AggregateExpression<
        Fn,
        NoPrefix,
        NoOrder,
        Filter,
        OverClause<NoPartition, NoOrder, FrameClause<E>>,
    >;

    fn frame(self, expr: E) -> Self::Output {
        AggregateExpression {
            prefix: self.prefix,
            function: self.function,
            order: self.order,
            filter: self.filter,
            window: OverClause {
                partition_by: NoPartition,
                order: NoOrder,
                frame_clause: FrameClause(expr),
            },
        }
    }
}

impl<E, Fn> FrameDsl<E> for Fn
where
    Fn: IsWindowFunction,
    E: FrameClauseExpression,
    E: ValidFrameClause<NoOrder>,
{
    type Output = AggregateExpression<
        Fn,
        NoPrefix,
        NoOrder,
        NoFilter,
        OverClause<NoPartition, NoOrder, FrameClause<E>>,
    >;

    fn frame(self, expr: E) -> Self::Output {
        AggregateExpression {
            prefix: NoPrefix,
            function: self,
            order: NoOrder,
            filter: NoFilter,
            window: OverClause {
                partition_by: NoPartition,
                order: NoOrder,
                frame_clause: FrameClause(expr),
            },
        }
    }
}

pub trait FrameClauseExpression {}

/// A marker trait for possible start frame expressions
///
/// See the list of types implementing this trait to understand
/// what can be used in this position
pub trait FrameClauseStartBound: Sealed {}

/// A marker trait for possible end frame expressions
///
/// See the list of types implementing this trait to understand
/// what can be used in this position
pub trait FrameClauseEndBound: Sealed {}

impl FrameClauseEndBound for UnboundedFollowing {}
impl Sealed for UnboundedFollowing {}
impl FrameClauseStartBound for UnboundedPreceding {}
impl Sealed for UnboundedPreceding {}
impl FrameClauseEndBound for CurrentRow {}
impl FrameClauseStartBound for CurrentRow {}
impl Sealed for CurrentRow {}
impl FrameClauseEndBound for OffsetFollowing {}
impl Sealed for OffsetFollowing {}
impl FrameClauseStartBound for OffsetPreceding {}
impl Sealed for OffsetPreceding {}

/// A marker trait for possible frame exclusion expressions
///
/// See the list of types implementing this trait to understand
/// what can be used in this position
pub trait FrameClauseExclusion: Sealed {}

impl FrameClauseExclusion for ExcludeGroup {}
impl Sealed for ExcludeGroup {}
impl FrameClauseExclusion for ExcludeNoOthers {}
impl Sealed for ExcludeNoOthers {}
impl FrameClauseExclusion for ExcludeTies {}
impl Sealed for ExcludeTies {}
impl FrameClauseExclusion for ExcludeCurrentRow {}
impl Sealed for ExcludeCurrentRow {}

/// Construct a frame clause for window functions from an integer
pub trait FrameBoundDsl {
    /// Use the preceding frame clause specification
    fn preceding(self) -> OffsetPreceding;

    /// Use the following frame clause specification
    fn following(self) -> OffsetFollowing;
}

impl FrameBoundDsl for u64 {
    fn preceding(self) -> OffsetPreceding {
        OffsetPreceding(self)
    }

    fn following(self) -> OffsetFollowing {
        OffsetFollowing(self)
    }
}
// TODO: We might want to implement
// it for datetime and date intervals?
// The postgres documentation indicates that
// something like `RANGE BETWEEN '1 day' PRECEDING AND '10 days' FOLLOWING`
// is valid

empty_clause!(NoExclusion);

#[derive(QueryId, Copy, Clone, Debug)]
pub struct StartFrame<Kind, Start, Exclusion = NoExclusion> {
    kind: Kind,
    start: Start,
    exclusion: Exclusion,
}

impl<Kind, Start, Exclusion, DB> QueryFragment<DB> for StartFrame<Kind, Start, Exclusion>
where
    Kind: QueryFragment<DB>,
    Start: QueryFragment<DB>,
    Exclusion: QueryFragment<DB>,
    DB: crate::backend::Backend,
{
    fn walk_ast<'b>(
        &'b self,
        mut pass: crate::query_builder::AstPass<'_, 'b, DB>,
    ) -> crate::QueryResult<()> {
        self.kind.walk_ast(pass.reborrow())?;
        self.start.walk_ast(pass.reborrow())?;
        self.exclusion.walk_ast(pass.reborrow())?;
        Ok(())
    }
}

impl<Kind, Start, Exclusion> FrameClauseExpression for StartFrame<Kind, Start, Exclusion> {}

#[derive(QueryId, Copy, Clone, Debug)]
pub struct BetweenFrame<Kind, Start, End, Exclusion = NoExclusion> {
    kind: Kind,
    start: Start,
    end: End,
    exclusion: Exclusion,
}

impl<Kind, Start, End, Exclusion, DB> QueryFragment<DB>
    for BetweenFrame<Kind, Start, End, Exclusion>
where
    Kind: QueryFragment<DB>,
    Start: QueryFragment<DB>,
    End: QueryFragment<DB>,
    Exclusion: QueryFragment<DB>,
    DB: crate::backend::Backend,
{
    fn walk_ast<'b>(
        &'b self,
        mut pass: crate::query_builder::AstPass<'_, 'b, DB>,
    ) -> crate::QueryResult<()> {
        self.kind.walk_ast(pass.reborrow())?;
        pass.push_sql(" BETWEEN ");
        self.start.walk_ast(pass.reborrow())?;
        pass.push_sql(" AND ");
        self.end.walk_ast(pass.reborrow())?;
        self.exclusion.walk_ast(pass.reborrow())?;
        Ok(())
    }
}

impl<Kind, Start, End, Exclusion> FrameClauseExpression
    for BetweenFrame<Kind, Start, End, Exclusion>
{
}

pub trait FrameClauseDslHelper: Sized {}

/// Construct a frame clause for window functions
pub trait FrameClauseDsl: FrameClauseDslHelper {
    /// Construct a frame clause with a starting bound
    fn frame_start_with<E>(self, start: E) -> super::dsl::FrameStartWith<Self, E>
    where
        E: FrameClauseStartBound,
    {
        StartFrame {
            kind: self,
            start,
            exclusion: NoExclusion,
        }
    }

    /// Construct a frame clause with a starting bound and an exclusion condition
    fn frame_start_with_exclusion<E1, E2>(
        self,
        start: E1,
        exclusion: E2,
    ) -> super::dsl::FrameStartWithExclusion<Self, E1, E2>
    where
        E1: FrameClauseStartBound,
        E2: FrameClauseExclusion,
    {
        StartFrame {
            kind: self,
            start,
            exclusion,
        }
    }

    /// Construct a between frame clause with a starting and end bound
    fn frame_between<E1, E2>(self, start: E1, end: E2) -> super::dsl::FrameBetween<Self, E1, E2>
    where
        E1: FrameClauseStartBound,
        E2: FrameClauseEndBound,
    {
        BetweenFrame {
            kind: self,
            start,
            end,
            exclusion: NoExclusion,
        }
    }

    /// Construct a between frame clause with a starting and end bound  with an exclusion condition
    fn frame_between_with_exclusion<E1, E2, E3>(
        self,
        start: E1,
        end: E2,
        exclusion: E3,
    ) -> super::dsl::FrameBetweenWithExclusion<Self, E1, E2, E3>
    where
        E1: FrameClauseStartBound,
        E2: FrameClauseEndBound,
        E3: FrameClauseExclusion,
    {
        BetweenFrame {
            kind: self,
            start,
            end,
            exclusion,
        }
    }
}

impl<T> FrameClauseDsl for T where T: FrameClauseDslHelper {}

impl FrameClauseDslHelper for Range {}
impl FrameClauseDslHelper for Rows {}
impl FrameClauseDslHelper for Groups {}

pub trait Sealed {}