drizzle-core 0.1.10

A type-safe SQL query builder for Rust
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
//! Window functions and OVER clause support.
//!
//! Provides:
//! - `WindowSpec` builder for PARTITION BY, ORDER BY, and frame clauses
//! - `.over()` method on aggregate `SQLExpr` to convert Agg → Scalar
//! - Pure window functions: `row_number`, `rank`, `dense_rank`, `ntile`,
//!   `percent_rank`, `cume_dist`, `lag`, `lead`, `first_value`, `last_value`,
//!   `nth_value`
//!
//! # Example
//!
//! ```rust
//! # let _ = r####"
//! use drizzle_core::expr::*;
//!
//! // Aggregate as window function
//! count_all().over(window().partition_by([users.dept]))
//! // → SQLExpr<CountType, NonNull, Scalar>
//!
//! // Pure window function
//! row_number().over(window().order_by([asc(users.id)]))
//! // → SQLExpr<CountType, NonNull, Scalar>
//! # "####;
//! ```

use core::marker::PhantomData;

use crate::sql::{SQL, Token};
use crate::traits::{SQLParam, ToSQL};
use crate::types::{BooleanLike, Compatible, DataType};

use super::agg::{CountPolicy, FloatPolicy};
use super::null::NullOr;
use super::{Agg, Expr, NonNull, Null, Nullability, SQLExpr, Scalar};

// =============================================================================
// Frame Bounds
// =============================================================================

/// Specifies a bound for a window frame (ROWS/RANGE BETWEEN).
#[derive(Debug, Clone, Copy)]
pub enum FrameBound {
    /// UNBOUNDED PRECEDING
    UnboundedPreceding,
    /// N PRECEDING
    Preceding(u64),
    /// CURRENT ROW
    CurrentRow,
    /// N FOLLOWING
    Following(u64),
    /// UNBOUNDED FOLLOWING
    UnboundedFollowing,
}

impl FrameBound {
    fn write_sql<'a, V: SQLParam>(&self) -> SQL<'a, V> {
        match self {
            Self::UnboundedPreceding => SQL::from(Token::UNBOUNDED).push(Token::PRECEDING),
            Self::Preceding(n) => {
                SQL::number(usize::try_from(*n).unwrap_or(usize::MAX)).push(Token::PRECEDING)
            }
            Self::CurrentRow => SQL::from(Token::CURRENT).push(Token::ROW),
            Self::Following(n) => {
                SQL::number(usize::try_from(*n).unwrap_or(usize::MAX)).push(Token::FOLLOWING)
            }
            Self::UnboundedFollowing => SQL::from(Token::UNBOUNDED).push(Token::FOLLOWING),
        }
    }
}

// =============================================================================
// WindowSpec
// =============================================================================

/// Builder for a window specification (the content inside `OVER (...)`).
///
/// # Example
///
/// ```rust
/// # let _ = r####"
/// window()
///     .partition_by([users.dept])
///     .order_by([asc(users.salary)])
///     .rows_between(FrameBound::UnboundedPreceding, FrameBound::CurrentRow)
/// # "####;
/// ```
#[derive(Debug, Clone)]
pub struct WindowSpec<'a, V: SQLParam> {
    partition: Option<SQL<'a, V>>,
    order: Option<SQL<'a, V>>,
    frame: Option<SQL<'a, V>>,
}

/// Create an empty window specification.
#[must_use]
pub const fn window<'a, V: SQLParam>() -> WindowSpec<'a, V> {
    WindowSpec {
        partition: None,
        order: None,
        frame: None,
    }
}

impl<'a, V: SQLParam + 'a> WindowSpec<'a, V> {
    /// Set the PARTITION BY clause.
    #[must_use]
    pub fn partition_by<I>(mut self, exprs: I) -> Self
    where
        I: IntoIterator,
        I::Item: ToSQL<'a, V>,
    {
        self.partition = Some(
            SQL::from(Token::PARTITION)
                .push(Token::BY)
                .append(SQL::join(exprs, Token::COMMA)),
        );
        self
    }

    /// Set the ORDER BY clause.
    #[must_use]
    pub fn order_by<T: ToSQL<'a, V>>(mut self, exprs: T) -> Self {
        self.order = Some(
            SQL::from(Token::ORDER)
                .push(Token::BY)
                .append(exprs.into_sql()),
        );
        self
    }

    /// Set a ROWS frame specification.
    #[must_use]
    pub fn rows_between(mut self, start: FrameBound, end: FrameBound) -> Self {
        self.frame = Some(
            SQL::from(Token::ROWS)
                .push(Token::BETWEEN)
                .append(start.write_sql())
                .push(Token::AND)
                .append(end.write_sql()),
        );
        self
    }

    /// Set a RANGE frame specification.
    #[must_use]
    pub fn range_between(mut self, start: FrameBound, end: FrameBound) -> Self {
        self.frame = Some(
            SQL::from(Token::RANGE)
                .push(Token::BETWEEN)
                .append(start.write_sql())
                .push(Token::AND)
                .append(end.write_sql()),
        );
        self
    }

    /// Build the window spec into SQL (contents inside the OVER parentheses).
    fn into_sql(self) -> SQL<'a, V> {
        let mut sql = SQL::empty();
        if let Some(p) = self.partition {
            sql.append_mut(p);
        }
        if let Some(o) = self.order {
            sql.append_mut(o);
        }
        if let Some(f) = self.frame {
            sql.append_mut(f);
        }
        sql
    }
}

// =============================================================================
// .over() on aggregate expressions — Agg → Scalar
// =============================================================================

impl<'a, V, T, N> SQLExpr<'a, V, T, N, Agg>
where
    V: SQLParam + 'a,
    T: DataType,
    N: Nullability,
{
    /// Apply a window specification to this aggregate expression.
    ///
    /// Converts the expression from `Agg` to `Scalar`, generating
    /// `<expr> OVER (...)`.
    ///
    /// # Example
    ///
    /// ```rust
    /// # let _ = r####"
    /// sum(orders.amount).over(
    ///     window()
    ///         .partition_by([orders.customer_id])
    ///         .order_by([asc(orders.date)])
    /// )
    /// # "####;
    /// ```
    pub fn over(self, spec: WindowSpec<'a, V>) -> SQLExpr<'a, V, T, N, Scalar> {
        let sql = self
            .into_sql()
            .push(Token::OVER)
            .push(Token::LPAREN)
            .append(spec.into_sql())
            .push(Token::RPAREN);
        SQLExpr::new(sql)
    }

    /// Apply a FILTER clause to this aggregate (`PostgreSQL` extension).
    ///
    /// Generates `<agg> FILTER (WHERE <condition>)`.
    #[must_use]
    pub fn filter<C>(self, condition: C) -> Self
    where
        C: Expr<'a, V>,
        C::SQLType: BooleanLike,
    {
        let sql = self
            .into_sql()
            .push(Token::FILTER)
            .push(Token::LPAREN)
            .push(Token::WHERE)
            .append(condition.into_sql())
            .push(Token::RPAREN);
        SQLExpr::new(sql)
    }
}

// =============================================================================
// WindowFnExpr — pure window functions that require .over()
// =============================================================================

/// A window function expression that is not yet valid SQL.
///
/// Pure window functions like `ROW_NUMBER`, RANK, LAG, etc. MUST have an
/// `.over()` call before they can be used in a query. This type enforces
/// that at compile time by not implementing `Expr` or `ToSQL`.
#[derive(Debug, Clone)]
pub struct WindowFnExpr<'a, V: SQLParam, T: DataType, N: Nullability> {
    sql: SQL<'a, V>,
    _marker: PhantomData<(T, N)>,
}

impl<'a, V, T, N> WindowFnExpr<'a, V, T, N>
where
    V: SQLParam + 'a,
    T: DataType,
    N: Nullability,
{
    const fn new(sql: SQL<'a, V>) -> Self {
        Self {
            sql,
            _marker: PhantomData,
        }
    }

    /// Apply a window specification, producing a usable scalar expression.
    ///
    /// Generates `<fn> OVER (...)`.
    pub fn over(self, spec: WindowSpec<'a, V>) -> SQLExpr<'a, V, T, N, Scalar> {
        let sql = self
            .sql
            .push(Token::OVER)
            .push(Token::LPAREN)
            .append(spec.into_sql())
            .push(Token::RPAREN);
        SQLExpr::new(sql)
    }
}

// =============================================================================
// Pure Window Functions
// =============================================================================

/// `ROW_NUMBER()` — sequential row number within the partition.
///
/// Returns an integer, never NULL.
#[must_use]
pub fn row_number<'a, V>() -> WindowFnExpr<'a, V, <V::DialectMarker as CountPolicy>::Count, NonNull>
where
    V: SQLParam + 'a,
    V::DialectMarker: CountPolicy,
{
    WindowFnExpr::new(SQL::raw("ROW_NUMBER()"))
}

/// `RANK()` — rank with gaps for ties.
///
/// Returns an integer, never NULL.
#[must_use]
pub fn rank<'a, V>() -> WindowFnExpr<'a, V, <V::DialectMarker as CountPolicy>::Count, NonNull>
where
    V: SQLParam + 'a,
    V::DialectMarker: CountPolicy,
{
    WindowFnExpr::new(SQL::raw("RANK()"))
}

/// `DENSE_RANK()` — rank without gaps.
///
/// Returns an integer, never NULL.
#[must_use]
pub fn dense_rank<'a, V>() -> WindowFnExpr<'a, V, <V::DialectMarker as CountPolicy>::Count, NonNull>
where
    V: SQLParam + 'a,
    V::DialectMarker: CountPolicy,
{
    WindowFnExpr::new(SQL::raw("DENSE_RANK()"))
}

/// NTILE(n) — divide rows into n roughly equal groups.
///
/// Returns an integer, never NULL.
#[must_use]
pub fn ntile<'a, V>(
    n: usize,
) -> WindowFnExpr<'a, V, <V::DialectMarker as CountPolicy>::Count, NonNull>
where
    V: SQLParam + 'a,
    V::DialectMarker: CountPolicy,
{
    WindowFnExpr::new(SQL::func("NTILE", SQL::number(n)))
}

/// `PERCENT_RANK()` — relative rank of the current row: (rank - 1) / (total rows - 1).
///
/// Returns a float between 0.0 and 1.0, never NULL.
#[must_use]
pub fn percent_rank<'a, V>()
-> WindowFnExpr<'a, V, <V::DialectMarker as FloatPolicy>::Float, NonNull>
where
    V: SQLParam + 'a,
    V::DialectMarker: FloatPolicy,
{
    WindowFnExpr::new(SQL::raw("PERCENT_RANK()"))
}

/// `CUME_DIST()` — cumulative distribution: fraction of rows <= current row.
///
/// Returns a float between 0.0 and 1.0 (exclusive of 0), never NULL.
#[must_use]
pub fn cume_dist<'a, V>() -> WindowFnExpr<'a, V, <V::DialectMarker as FloatPolicy>::Float, NonNull>
where
    V: SQLParam + 'a,
    V::DialectMarker: FloatPolicy,
{
    WindowFnExpr::new(SQL::raw("CUME_DIST()"))
}

/// LAG(expr) — value of expr from the previous row.
///
/// Returns the same type as expr, always nullable (no previous row → NULL).
pub fn lag<'a, V, E>(expr: E) -> WindowFnExpr<'a, V, E::SQLType, Null>
where
    V: SQLParam + 'a,
    E: Expr<'a, V>,
{
    WindowFnExpr::new(SQL::func("LAG", expr.into_sql()))
}

/// LAG(expr, offset, default) — value of expr from N rows back with a default.
///
/// Nullability is the combination of the expression's and default's nullability.
pub fn lag_with_default<'a, V, E, D>(
    expr: E,
    offset: usize,
    default: D,
) -> WindowFnExpr<'a, V, E::SQLType, <E::Nullable as NullOr<D::Nullable>>::Output>
where
    V: SQLParam + 'a,
    E: Expr<'a, V>,
    D: Expr<'a, V>,
    E::SQLType: Compatible<D::SQLType>,
    E::Nullable: NullOr<D::Nullable>,
    D::Nullable: Nullability,
{
    let args = expr
        .into_sql()
        .push(Token::COMMA)
        .append(SQL::number(offset))
        .push(Token::COMMA)
        .append(default.into_sql());
    WindowFnExpr::new(SQL::func("LAG", args))
}

/// LEAD(expr) — value of expr from the next row.
///
/// Returns the same type as expr, always nullable (no next row → NULL).
pub fn lead<'a, V, E>(expr: E) -> WindowFnExpr<'a, V, E::SQLType, Null>
where
    V: SQLParam + 'a,
    E: Expr<'a, V>,
{
    WindowFnExpr::new(SQL::func("LEAD", expr.into_sql()))
}

/// LEAD(expr, offset, default) — value of expr from N rows ahead with a default.
///
/// Nullability is the combination of the expression's and default's nullability.
pub fn lead_with_default<'a, V, E, D>(
    expr: E,
    offset: usize,
    default: D,
) -> WindowFnExpr<'a, V, E::SQLType, <E::Nullable as NullOr<D::Nullable>>::Output>
where
    V: SQLParam + 'a,
    E: Expr<'a, V>,
    D: Expr<'a, V>,
    E::SQLType: Compatible<D::SQLType>,
    E::Nullable: NullOr<D::Nullable>,
    D::Nullable: Nullability,
{
    let args = expr
        .into_sql()
        .push(Token::COMMA)
        .append(SQL::number(offset))
        .push(Token::COMMA)
        .append(default.into_sql());
    WindowFnExpr::new(SQL::func("LEAD", args))
}

/// `FIRST_VALUE(expr)` — value of expr from the first row of the frame.
///
/// Always nullable (frame may be empty for some edge cases).
pub fn first_value<'a, V, E>(expr: E) -> WindowFnExpr<'a, V, E::SQLType, Null>
where
    V: SQLParam + 'a,
    E: Expr<'a, V>,
{
    WindowFnExpr::new(SQL::func("FIRST_VALUE", expr.into_sql()))
}

/// `LAST_VALUE(expr)` — value of expr from the last row of the frame.
///
/// Always nullable (frame boundaries affect result).
pub fn last_value<'a, V, E>(expr: E) -> WindowFnExpr<'a, V, E::SQLType, Null>
where
    V: SQLParam + 'a,
    E: Expr<'a, V>,
{
    WindowFnExpr::new(SQL::func("LAST_VALUE", expr.into_sql()))
}

/// `NTH_VALUE(expr`, n) — value of expr from the nth row of the frame.
///
/// Always nullable (n may exceed frame size).
pub fn nth_value<'a, V, E>(expr: E, n: usize) -> WindowFnExpr<'a, V, E::SQLType, Null>
where
    V: SQLParam + 'a,
    E: Expr<'a, V>,
{
    let args = expr.into_sql().push(Token::COMMA).append(SQL::number(n));
    WindowFnExpr::new(SQL::func("NTH_VALUE", args))
}