zino_orm/
window.rs

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
use self::WindownFunction::*;
use super::{query::QueryExt, Entity};
use zino_core::model::Query;

/// A windown function.
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
enum WindownFunction<E: Entity> {
    /// The `COUNT` function.
    Count(E::Column),
    /// The `SUM` function.
    Sum(E::Column),
    /// The `AVG` function.
    Avg(E::Column),
    /// The `MIN` function.
    Min(E::Column),
    /// The `MAX` function.
    Max(E::Column),
    /// The `ROW_NUMBER` function.
    RowNumber,
    /// The `RNAK` function.
    Rank,
    /// The `DENSE_RNAK` function.
    DenseRank,
    /// The `PERCENT_RNAK` function.
    PercentRank,
    /// The `CUME_DIST` function.
    CumeDist,
    /// The `NTILE` function.
    Ntile(usize),
    /// The `LAG` function.
    Lag(E::Column, usize),
    /// The `LEAD` function.
    Lead(E::Column, usize),
    /// The `FIRST_VALUE` function.
    FirstValue(E::Column),
    /// The `LAST_VALUE` function.
    LastValue(E::Column),
    /// The `NTH_VALUE` function.
    NthValue(E::Column, usize),
}

/// SQL window functions.
///
/// # Examples
/// ```rust,ignore
/// use crate::model::{User, UserColumn::*};
/// use zino_orm::{QueryBuilder, Schema, Window};
///
/// let rank_window = Window::rank(CurrentLoginIp).order_desc(LoginCount);
/// let query = QueryBuilder::<User>::new()
///     .fields([Id, Name, CurrentLoginIp, LoginCount])
///     .window(rank_window, Some("login_count_rank"))
///     .and_not_in(Status, ["Deleted", "Locked"])
///     .order_desc(UpdatedAt)
///     .limit(10)
///     .build();
/// let users: Vec<Map> = User::find(&query).await?;
/// ```
#[derive(Debug, Clone, Copy)]
pub struct Window<E: Entity> {
    /// The window function.
    function: WindownFunction<E>,
    /// `PARTITION BY` a column.
    partition: E::Column,
    /// An optional `ORDER BY`.
    order: Option<(E::Column, bool)>,
}

impl<E: Entity> Window<E> {
    /// Constructs an instance for the window function `COUNT`.
    #[inline]
    pub fn count(col: E::Column, partition: E::Column) -> Self {
        Self {
            function: Count(col),
            partition,
            order: None,
        }
    }

    /// Constructs an instance for the window function `SUM`.
    #[inline]
    pub fn sum(col: E::Column, partition: E::Column) -> Self {
        Self {
            function: Sum(col),
            partition,
            order: None,
        }
    }

    /// Constructs an instance for the window function `AVG`.
    #[inline]
    pub fn avg(col: E::Column, partition: E::Column) -> Self {
        Self {
            function: Avg(col),
            partition,
            order: None,
        }
    }

    /// Constructs an instance for the window function `MIN`.
    #[inline]
    pub fn min(col: E::Column, partition: E::Column) -> Self {
        Self {
            function: Min(col),
            partition,
            order: None,
        }
    }

    /// Constructs an instance for the window function `MAX`.
    #[inline]
    pub fn max(col: E::Column, partition: E::Column) -> Self {
        Self {
            function: Max(col),
            partition,
            order: None,
        }
    }

    /// Constructs an instance for the window function `DENSE_RANK`.
    #[inline]
    pub fn row_number(partition: E::Column) -> Self {
        Self {
            function: RowNumber,
            partition,
            order: None,
        }
    }

    /// Constructs an instance for the window function `RANK`.
    #[inline]
    pub fn rank(partition: E::Column) -> Self {
        Self {
            function: Rank,
            partition,
            order: None,
        }
    }

    /// Constructs an instance for the window function `DENSE_RANK`.
    #[inline]
    pub fn dense_rank(partition: E::Column) -> Self {
        Self {
            function: DenseRank,
            partition,
            order: None,
        }
    }

    /// Constructs an instance for the window function `PERCENT_RANK`.
    #[inline]
    pub fn percent_rank(partition: E::Column) -> Self {
        Self {
            function: PercentRank,
            partition,
            order: None,
        }
    }

    /// Constructs an instance for the window function `CUME_DIST`.
    #[inline]
    pub fn cume_dist(partition: E::Column) -> Self {
        Self {
            function: CumeDist,
            partition,
            order: None,
        }
    }

    /// Constructs an instance for the window function `NTILE`.
    #[inline]
    pub fn ntile(num_buckets: usize, partition: E::Column) -> Self {
        Self {
            function: Ntile(num_buckets),
            partition,
            order: None,
        }
    }

    /// Constructs an instance for the window function `LAG`.
    #[inline]
    pub fn lag(col: E::Column, offset: usize, partition: E::Column) -> Self {
        Self {
            function: Lag(col, offset),
            partition,
            order: None,
        }
    }

    /// Constructs an instance for the window function `LEAD`.
    #[inline]
    pub fn lead(col: E::Column, offset: usize, partition: E::Column) -> Self {
        Self {
            function: Lead(col, offset),
            partition,
            order: None,
        }
    }

    /// Constructs an instance for the window function `FIRST_VALUE`.
    #[inline]
    pub fn first_value(col: E::Column, partition: E::Column) -> Self {
        Self {
            function: FirstValue(col),
            partition,
            order: None,
        }
    }

    /// Constructs an instance for the window function `LAST_VALUE`.
    #[inline]
    pub fn last_value(col: E::Column, partition: E::Column) -> Self {
        Self {
            function: LastValue(col),
            partition,
            order: None,
        }
    }

    /// Constructs an instance for the window function `NTH_VALUE`.
    #[inline]
    pub fn nth_value(col: E::Column, n: usize, partition: E::Column) -> Self {
        Self {
            function: NthValue(col, n),
            partition,
            order: None,
        }
    }

    /// Sets the sort order.
    #[inline]
    pub fn order_by(mut self, col: E::Column, descending: bool) -> Self {
        self.order = Some((col, descending));
        self
    }

    /// Sets the sort order with an ascending order.
    #[inline]
    pub fn order_asc(mut self, col: E::Column) -> Self {
        self.order = Some((col, false));
        self
    }

    /// Sets the sort order with an descending order.
    #[inline]
    pub fn order_desc(mut self, col: E::Column) -> Self {
        self.order = Some((col, true));
        self
    }

    /// Returns a default alias for the window function.
    pub(super) fn default_alias(&self) -> String {
        match &self.function {
            Count(col) => [col.as_ref(), "_sum"].concat(),
            Sum(col) => [col.as_ref(), "_sum"].concat(),
            Avg(col) => [col.as_ref(), "_avg"].concat(),
            Min(col) => [col.as_ref(), "_min"].concat(),
            Max(col) => [col.as_ref(), "_max"].concat(),
            RowNumber => "row_number".to_owned(),
            Rank => "rank".to_owned(),
            DenseRank => "dense_rank".to_owned(),
            PercentRank => "percent_rank".to_owned(),
            CumeDist => "cume_dist".to_owned(),
            Ntile(_) => "ntile".to_owned(),
            Lag(col, _) => [col.as_ref(), "_prev"].concat(),
            Lead(col, _) => [col.as_ref(), "_next"].concat(),
            FirstValue(col) => [col.as_ref(), "_first"].concat(),
            LastValue(col) => [col.as_ref(), "_last"].concat(),
            NthValue(col, _) => [col.as_ref(), "_nth"].concat(),
        }
    }

    /// Returns the SQL expression.
    pub(super) fn expr(&self) -> String {
        let partition_col_name = E::format_column(&self.partition);
        let partition = Query::format_field(&partition_col_name);
        let sort = self
            .order
            .as_ref()
            .map(|(col, descending)| {
                let col_name = E::format_column(col);
                let sort_field = Query::format_field(&col_name);
                if *descending {
                    format!(" ORDER BY {sort_field} DESC")
                } else {
                    format!(" ORDER BY {sort_field} ASC")
                }
            })
            .unwrap_or_default();
        match &self.function {
            Count(col) => {
                let col_name = E::format_column(col);
                let field = Query::format_field(&col_name);
                format!("count({field}) OVER (PARTITION BY {partition}{sort})")
            }
            Sum(col) => {
                let col_name = E::format_column(col);
                let field = Query::format_field(&col_name);
                format!("sum({field}) OVER (PARTITION BY {partition}{sort})")
            }
            Avg(col) => {
                let col_name = E::format_column(col);
                let field = Query::format_field(&col_name);
                format!("avg({field}) OVER (PARTITION BY {partition}{sort})")
            }
            Min(col) => {
                let col_name = E::format_column(col);
                let field = Query::format_field(&col_name);
                format!("min({field}) OVER (PARTITION BY {partition}{sort})")
            }
            Max(col) => {
                let col_name = E::format_column(col);
                let field = Query::format_field(&col_name);
                format!("max({field}) OVER (PARTITION BY {partition}{sort})")
            }
            RowNumber => {
                format!("row_number() OVER (PARTITION BY {partition}{sort})")
            }
            Rank => {
                format!("rank() OVER (PARTITION BY {partition}{sort})")
            }
            DenseRank => {
                format!("dense_rank() OVER (PARTITION BY {partition}{sort})")
            }
            PercentRank => {
                format!("percent_rank() OVER (PARTITION BY {partition}{sort})")
            }
            CumeDist => {
                format!("cume_dist() OVER (PARTITION BY {partition}{sort})")
            }
            Ntile(n) => {
                format!("ntile({n}) OVER (PARTITION BY {partition}{sort})")
            }
            Lag(col, offset) => {
                let col_name = E::format_column(col);
                let field = Query::format_field(&col_name);
                format!("lag({field}, {offset}) OVER (PARTITION BY {partition}{sort})")
            }
            Lead(col, offset) => {
                let col_name = E::format_column(col);
                let field = Query::format_field(&col_name);
                format!("lead({field}, {offset}) OVER (PARTITION BY {partition}{sort})")
            }
            FirstValue(col) => {
                let col_name = E::format_column(col);
                let field = Query::format_field(&col_name);
                format!("first_value({field}) OVER (PARTITION BY {partition}{sort})")
            }
            LastValue(col) => {
                let col_name = E::format_column(col);
                let field = Query::format_field(&col_name);
                format!("last_value({field}) OVER (PARTITION BY {partition}{sort})")
            }
            NthValue(col, n) => {
                let col_name = E::format_column(col);
                let field = Query::format_field(&col_name);
                format!("nth_value({field}, {n}) OVER (PARTITION BY {partition}{sort})")
            }
        }
    }
}