rok-fluent 0.4.1

Eloquent-inspired async ORM for Rust (PostgreSQL, MySQL, SQLite)
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
//! [`Column`] — typed column reference, ordering, and aggregate expressions.
//!
//! Every field on a `#[derive(Table)]` struct generates a
//! `pub const FIELD_NAME: Column<StructType, FieldType>` constant on the struct.
//! These column values are zero-size and used only at the type/query-building level.

use super::expr::Expr;
use crate::core::condition::SqlValue;

/// A typed column reference: `Column<TableStruct, ValueType>`.
///
/// Created by `#[derive(Table)]` — users do not construct these directly.
///
/// ```rust,ignore
/// // Generated for `pub id: i64` on a `#[derive(Table)] struct User`:
/// // pub const ID: Column<User, i64> = Column::new("users", "id");
///
/// // Then in queries:
/// User::ID.eq(42_i64)       // → Expr::Eq(...)
/// User::NAME.like("%Al%")   // → Expr::Like(...)
/// ```
#[derive(Debug, Clone, Copy)]
pub struct Column<T, V> {
    pub(crate) table: &'static str,
    pub(crate) name: &'static str,
    _table: std::marker::PhantomData<T>,
    _value: std::marker::PhantomData<V>,
}

impl<T, V> Column<T, V> {
    /// Construct a column reference. Called by `#[derive(Table)]` generated code.
    pub const fn new(table: &'static str, name: &'static str) -> Self {
        Self {
            table,
            name,
            _table: std::marker::PhantomData,
            _value: std::marker::PhantomData,
        }
    }

    /// The SQL-qualified form `"table"."column"`.
    pub fn qualified(&self) -> String {
        format!("\"{}\".\"{}\"", self.table, self.name)
    }

    /// Bare column name.
    pub fn name(&self) -> &'static str {
        self.name
    }
}

// ── Comparison operators ──────────────────────────────────────────────────────

impl<T, V: Into<SqlValue>> Column<T, V> {
    /// `column = value`
    pub fn eq(self, val: impl Into<SqlValue>) -> Expr {
        Expr::Eq(self.qualified(), val.into())
    }

    /// `column != value`
    pub fn ne(self, val: impl Into<SqlValue>) -> Expr {
        Expr::Ne(self.qualified(), val.into())
    }

    /// `column > value`
    pub fn gt(self, val: impl Into<SqlValue>) -> Expr {
        Expr::Gt(self.qualified(), val.into())
    }

    /// `column >= value`
    pub fn gte(self, val: impl Into<SqlValue>) -> Expr {
        Expr::Gte(self.qualified(), val.into())
    }

    /// `column < value`
    pub fn lt(self, val: impl Into<SqlValue>) -> Expr {
        Expr::Lt(self.qualified(), val.into())
    }

    /// `column <= value`
    pub fn lte(self, val: impl Into<SqlValue>) -> Expr {
        Expr::Lte(self.qualified(), val.into())
    }

    /// `column LIKE pattern`
    pub fn like(self, pattern: impl Into<SqlValue>) -> Expr {
        Expr::Like(self.qualified(), pattern.into())
    }

    /// `column NOT LIKE pattern`
    pub fn not_like(self, pattern: impl Into<SqlValue>) -> Expr {
        Expr::NotLike(self.qualified(), pattern.into())
    }

    /// `column ILIKE pattern` — PostgreSQL case-insensitive LIKE.
    pub fn ilike(self, pattern: impl Into<SqlValue>) -> Expr {
        Expr::ILike(self.qualified(), pattern.into())
    }

    /// `column IN (v1, v2, …)`
    pub fn in_(self, vals: impl IntoIterator<Item = impl Into<SqlValue>>) -> Expr {
        Expr::In(self.qualified(), vals.into_iter().map(Into::into).collect())
    }

    /// `column NOT IN (v1, v2, …)`
    pub fn not_in(self, vals: impl IntoIterator<Item = impl Into<SqlValue>>) -> Expr {
        Expr::NotIn(self.qualified(), vals.into_iter().map(Into::into).collect())
    }

    /// `column = ANY(ARRAY[$1, $2, …])` — single array parameter; better prepared-statement reuse than `IN`.
    pub fn eq_any(self, vals: impl IntoIterator<Item = impl Into<SqlValue>>) -> Expr {
        Expr::EqAny(self.qualified(), vals.into_iter().map(Into::into).collect())
    }

    /// `column BETWEEN lo AND hi`
    pub fn between(self, lo: impl Into<SqlValue>, hi: impl Into<SqlValue>) -> Expr {
        Expr::Between(self.qualified(), lo.into(), hi.into())
    }

    /// `column NOT BETWEEN lo AND hi`
    pub fn not_between(self, lo: impl Into<SqlValue>, hi: impl Into<SqlValue>) -> Expr {
        Expr::NotBetween(self.qualified(), lo.into(), hi.into())
    }
}

// ── Null checks and ordering (no value bound required) ───────────────────────

impl<T, V> Column<T, V> {
    /// `column IS NULL`
    pub fn is_null(self) -> Expr {
        Expr::IsNull(self.qualified())
    }

    /// `column IS NOT NULL`
    pub fn is_not_null(self) -> Expr {
        Expr::IsNotNull(self.qualified())
    }

    /// `column ASC` — pass to `.order_by()`.
    pub fn asc(self) -> OrderExpr {
        OrderExpr {
            col: self.qualified(),
            dir: OrderDir::Asc,
            nulls: NullsOrder::Default,
        }
    }

    /// `column DESC` — pass to `.order_by()`.
    pub fn desc(self) -> OrderExpr {
        OrderExpr {
            col: self.qualified(),
            dir: OrderDir::Desc,
            nulls: NullsOrder::Default,
        }
    }

    /// `column ASC NULLS LAST`
    pub fn asc_nulls_last(self) -> OrderExpr {
        OrderExpr {
            col: self.qualified(),
            dir: OrderDir::Asc,
            nulls: NullsOrder::Last,
        }
    }

    /// `column ASC NULLS FIRST`
    pub fn asc_nulls_first(self) -> OrderExpr {
        OrderExpr {
            col: self.qualified(),
            dir: OrderDir::Asc,
            nulls: NullsOrder::First,
        }
    }

    /// `column DESC NULLS LAST`
    pub fn desc_nulls_last(self) -> OrderExpr {
        OrderExpr {
            col: self.qualified(),
            dir: OrderDir::Desc,
            nulls: NullsOrder::Last,
        }
    }

    /// `column DESC NULLS FIRST`
    pub fn desc_nulls_first(self) -> OrderExpr {
        OrderExpr {
            col: self.qualified(),
            dir: OrderDir::Desc,
            nulls: NullsOrder::First,
        }
    }

    /// Column-to-column equality for JOIN ON clauses: `self = other`.
    ///
    /// ```rust,ignore
    /// .inner_join(Post::table(), Post::USER_ID.references(User::ID))
    /// ```
    pub fn references<T2, V2>(self, other: Column<T2, V2>) -> Expr {
        Expr::ColEq(self.qualified(), other.qualified())
    }

    /// Column-to-column equality — alias for [`references`](Self::references)
    /// intended for use in `WHERE` expressions.
    pub fn eq_col<T2, V2>(self, other: Column<T2, V2>) -> Expr {
        Expr::ColEq(self.qualified(), other.qualified())
    }

    /// `column IN (subquery_sql)` — subquery inserted verbatim.
    ///
    /// ```rust,ignore
    /// User::ID.in_subquery("SELECT user_id FROM orders WHERE total > 100")
    /// ```
    pub fn in_subquery(self, subquery_sql: impl Into<String>) -> Expr {
        Expr::InSubquery(self.qualified(), subquery_sql.into())
    }

    /// `column NOT IN (subquery_sql)`
    pub fn not_in_subquery(self, subquery_sql: impl Into<String>) -> Expr {
        Expr::NotInSubquery(self.qualified(), subquery_sql.into())
    }
}

// ── SQL function expressions ──────────────────────────────────────────────────

impl<T, V> Column<T, V> {
    /// `LOWER(column)` — rendered as a raw expression string.
    pub fn lower(self) -> FnExpr {
        FnExpr::new(format!("LOWER({})", self.qualified()))
    }

    /// `UPPER(column)`
    pub fn upper(self) -> FnExpr {
        FnExpr::new(format!("UPPER({})", self.qualified()))
    }

    /// `LENGTH(column)` — character length.
    pub fn length(self) -> FnExpr {
        FnExpr::new(format!("LENGTH({})", self.qualified()))
    }

    /// `TRIM(column)`
    pub fn trim(self) -> FnExpr {
        FnExpr::new(format!("TRIM({})", self.qualified()))
    }

    /// `COALESCE(column, fallback_sql)` — e.g. `User::NAME.coalesce("'anonymous'")`.
    pub fn coalesce(self, fallback_sql: impl Into<String>) -> FnExpr {
        FnExpr::new(format!(
            "COALESCE({}, {})",
            self.qualified(),
            fallback_sql.into()
        ))
    }

    /// `CAST(column AS type_sql)` — e.g. `User::SCORE.cast_as("FLOAT")`.
    pub fn cast_as(self, type_sql: impl Into<String>) -> FnExpr {
        FnExpr::new(format!("CAST({} AS {})", self.qualified(), type_sql.into()))
    }

    /// `DATE_TRUNC(unit, column)` — PostgreSQL date truncation.
    pub fn date_trunc(self, unit: impl Into<String>) -> FnExpr {
        FnExpr::new(format!(
            "DATE_TRUNC('{}', {})",
            unit.into(),
            self.qualified()
        ))
    }

    /// `EXTRACT(part FROM column)` — e.g. `User::CREATED_AT.extract("year")`.
    pub fn extract(self, part: impl Into<String>) -> FnExpr {
        FnExpr::new(format!(
            "EXTRACT({} FROM {})",
            part.into(),
            self.qualified()
        ))
    }
}

// ── Aggregate expressions (Phase 24) ─────────────────────────────────────────

impl<T, V> Column<T, V> {
    /// `COUNT(column)` — returns an [`AggExpr`] for use in `.columns()` or `.having()`.
    pub fn count(self) -> AggExpr {
        AggExpr::new(format!("COUNT({})", self.qualified()))
    }

    /// `COUNT(DISTINCT column)`
    pub fn count_distinct(self) -> AggExpr {
        AggExpr::new(format!("COUNT(DISTINCT {})", self.qualified()))
    }

    /// `SUM(column)`
    pub fn sum(self) -> AggExpr {
        AggExpr::new(format!("SUM({})", self.qualified()))
    }

    /// `AVG(column)`
    pub fn avg(self) -> AggExpr {
        AggExpr::new(format!("AVG({})", self.qualified()))
    }

    /// `MIN(column)`
    pub fn min(self) -> AggExpr {
        AggExpr::new(format!("MIN({})", self.qualified()))
    }

    /// `MAX(column)`
    pub fn max(self) -> AggExpr {
        AggExpr::new(format!("MAX({})", self.qualified()))
    }
}

// ── AggExpr ───────────────────────────────────────────────────────────────────

/// An aggregate function expression — used in `HAVING` clauses and in projection.
///
/// Obtained from column aggregate methods like `.count()`, `.sum()`, `.avg()`, etc.
///
/// ```rust,ignore
/// // HAVING COUNT("orders"."id") > 5
/// .having(Order::ID.count().gt(5_i64))
/// ```
#[derive(Debug, Clone)]
pub struct AggExpr {
    /// Pre-rendered aggregate SQL, e.g. `COUNT("users"."id")`.
    pub(crate) sql: String,
    /// Optional alias for use in SELECT projections.
    alias: Option<String>,
}

impl AggExpr {
    pub(crate) fn new(sql: String) -> Self {
        Self { sql, alias: None }
    }

    /// Assign an alias: `COUNT("users"."id") AS total`.
    #[must_use]
    pub fn alias(mut self, name: impl Into<String>) -> Self {
        self.alias = Some(name.into());
        self
    }

    /// Render the aggregate expression for use in SELECT projection.
    pub fn to_projection_sql(&self) -> String {
        match &self.alias {
            Some(a) => format!("{} AS \"{}\"", self.sql, a),
            None => self.sql.clone(),
        }
    }

    /// `AGG > value` — produces a HAVING predicate.
    pub fn gt(self, val: impl Into<SqlValue>) -> Expr {
        Expr::AggCmp(self.sql, ">", val.into())
    }

    /// `AGG >= value`
    pub fn gte(self, val: impl Into<SqlValue>) -> Expr {
        Expr::AggCmp(self.sql, ">=", val.into())
    }

    /// `AGG < value`
    pub fn lt(self, val: impl Into<SqlValue>) -> Expr {
        Expr::AggCmp(self.sql, "<", val.into())
    }

    /// `AGG <= value`
    pub fn lte(self, val: impl Into<SqlValue>) -> Expr {
        Expr::AggCmp(self.sql, "<=", val.into())
    }

    /// `AGG = value`
    pub fn eq(self, val: impl Into<SqlValue>) -> Expr {
        Expr::AggCmp(self.sql, "=", val.into())
    }

    /// `AGG != value`
    pub fn ne(self, val: impl Into<SqlValue>) -> Expr {
        Expr::AggCmp(self.sql, "!=", val.into())
    }
}

// ── OrderExpr ─────────────────────────────────────────────────────────────────

/// A column ordering expression produced by `.asc()` / `.desc()` etc.
#[derive(Debug, Clone)]
pub struct OrderExpr {
    pub(crate) col: String,
    pub(crate) dir: OrderDir,
    pub(crate) nulls: NullsOrder,
}

/// Sort direction.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OrderDir {
    /// Ascending order.
    Asc,
    /// Descending order.
    Desc,
}

/// NULL ordering modifier.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NullsOrder {
    /// Database default — no explicit NULLS FIRST / NULLS LAST.
    Default,
    /// NULLS FIRST
    First,
    /// NULLS LAST
    Last,
}

impl OrderExpr {
    /// Render as `"table"."col" ASC [NULLS FIRST|LAST]`.
    pub fn to_sql(&self) -> String {
        let dir = match self.dir {
            OrderDir::Asc => "ASC",
            OrderDir::Desc => "DESC",
        };
        let nulls = match self.nulls {
            NullsOrder::Default => String::new(),
            NullsOrder::First => " NULLS FIRST".to_string(),
            NullsOrder::Last => " NULLS LAST".to_string(),
        };
        format!("{} {}{}", self.col, dir, nulls)
    }
}

// ── FnExpr ────────────────────────────────────────────────────────────────────

/// A SQL function expression wrapping a column — e.g. `LOWER("users"."name")`.
///
/// Obtained from column function methods like `.lower()`, `.upper()`, etc.
/// Use in `SELECT` projections via `.agg_col()` or convert to an [`Expr`] for
/// use in `WHERE`/`HAVING` with the comparison methods below.
#[derive(Debug, Clone)]
pub struct FnExpr {
    /// Pre-rendered SQL, e.g. `LOWER("users"."name")`.
    pub(crate) sql: String,
    /// Optional alias for projection.
    alias: Option<String>,
}

impl FnExpr {
    pub(crate) fn new(sql: String) -> Self {
        Self { sql, alias: None }
    }

    /// Assign an alias: `LOWER("users"."name") AS lower_name`.
    #[must_use]
    pub fn alias(mut self, name: impl Into<String>) -> Self {
        self.alias = Some(name.into());
        self
    }

    /// Render for use in a SELECT projection.
    pub fn to_projection_sql(&self) -> String {
        match &self.alias {
            Some(a) => format!("{} AS \"{}\"", self.sql, a),
            None => self.sql.clone(),
        }
    }

    /// `fn_expr = value`
    pub fn eq(self, val: impl Into<crate::core::condition::SqlValue>) -> super::expr::Expr {
        super::expr::Expr::AggCmp(self.sql, "=", val.into())
    }

    /// `fn_expr != value`
    pub fn ne(self, val: impl Into<crate::core::condition::SqlValue>) -> super::expr::Expr {
        super::expr::Expr::AggCmp(self.sql, "!=", val.into())
    }

    /// `fn_expr LIKE pattern`
    pub fn like(self, pattern: impl Into<crate::core::condition::SqlValue>) -> super::expr::Expr {
        super::expr::Expr::AggCmp(self.sql, "LIKE", pattern.into())
    }

    /// `fn_expr ILIKE pattern` — PostgreSQL case-insensitive.
    pub fn ilike(self, pattern: impl Into<crate::core::condition::SqlValue>) -> super::expr::Expr {
        super::expr::Expr::AggCmp(self.sql, "ILIKE", pattern.into())
    }

    /// `fn_expr > value`
    pub fn gt(self, val: impl Into<crate::core::condition::SqlValue>) -> super::expr::Expr {
        super::expr::Expr::AggCmp(self.sql, ">", val.into())
    }

    /// `fn_expr < value`
    pub fn lt(self, val: impl Into<crate::core::condition::SqlValue>) -> super::expr::Expr {
        super::expr::Expr::AggCmp(self.sql, "<", val.into())
    }
}