floz-orm 0.1.7

A lightweight, typesafe Rust ORM — unifying DAO and DSL from a single schema
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
//! Typed column references for building type-safe queries.
//!
//! `Column<T>` carries the Rust type `T` at compile time, enabling the proc macro
//! to generate type-safe `.eq()`, `.gt()` etc. methods. At runtime, the column
//! name and table are used for SQL rendering.
//!
//! ```ignore
//! // Generated by the proc macro:
//! pub struct UserTable;
//! impl UserTable {
//!     pub const id: Column<i32> = Column::new("id", "users");
//!     pub const name: Column<String> = Column::new("name", "users");
//! }
//!
//! // Used in queries:
//! UserTable::age.gt(25)              // Expr::Gt
//! UserTable::name.eq("Alice")        // Expr::Eq
//! UserTable::name.asc()              // OrderExpr
//! ```

use std::marker::PhantomData;

use crate::expr::{Expr, OrderDirection, OrderExpr};
use crate::value::Value;

/// A typed reference to a database column.
///
/// `T` represents the Rust type this column maps to (e.g., `Column<i32>` for INTEGER).
/// The type parameter enables compile-time type checking when the proc macro generates
/// operator methods.
#[derive(Debug, Clone)]
pub struct Column<T> {
    name: &'static str,
    table: &'static str,
    _phantom: PhantomData<T>,
}

impl<T> Column<T> {
    /// Create a new column reference.
    pub const fn new(name: &'static str, table: &'static str) -> Self {
        Self {
            name,
            table,
            _phantom: PhantomData,
        }
    }

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

    /// The table this column belongs to.
    pub const fn table(&self) -> &'static str {
        self.table
    }

    /// Erase the type information for dynamic use.
    pub const fn into_any(&self) -> AnyColumn {
        AnyColumn {
            name: self.name,
            table: self.table,
        }
    }

    fn any(&self) -> AnyColumn {
        self.into_any()
    }
}

// ── Comparison operators (available on all column types) ──

impl<T> Column<T>
where
    T: Into<Value> + Clone,
{
    /// `column = value`
    pub fn eq(&self, val: impl Into<Value>) -> Expr {
        Expr::Eq(self.any(), val.into())
    }

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

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

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

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

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

    /// `column BETWEEN low AND high`
    pub fn between(&self, low: impl Into<Value>, high: impl Into<Value>) -> Expr {
        Expr::Between(self.any(), low.into(), high.into())
    }

    /// `column IN (values...)` — empty list renders as `1=0` (always false)
    pub fn in_list(&self, vals: Vec<impl Into<Value>>) -> Expr {
        let values: Vec<Value> = vals.into_iter().map(|v| v.into()).collect();
        Expr::InList(self.any(), values)
    }

    /// `column NOT IN (values...)` — empty list renders as `1=1` (always true)
    pub fn not_in(&self, vals: Vec<impl Into<Value>>) -> Expr {
        let values: Vec<Value> = vals.into_iter().map(|v| v.into()).collect();
        Expr::NotIn(self.any(), values)
    }
}

// ── String operators (available on all columns, typically used with String columns) ──

impl<T> Column<T> {
    /// `column LIKE pattern` — e.g., `.like("A%")`
    pub fn like(&self, pattern: impl Into<Value>) -> Expr {
        Expr::Like(self.any(), pattern.into())
    }

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

    /// `column LIKE '%value%'` — shorthand for contains
    pub fn contains(&self, val: &str) -> Expr {
        Expr::Like(self.any(), Value::String(format!("%{}%", val)))
    }

    /// `column LIKE 'value%'` — shorthand for starts_with
    pub fn starts_with(&self, val: &str) -> Expr {
        Expr::Like(self.any(), Value::String(format!("{}%", val)))
    }

    /// `column LIKE '%value'` — shorthand for ends_with
    pub fn ends_with(&self, val: &str) -> Expr {
        Expr::Like(self.any(), Value::String(format!("%{}", val)))
    }
}

// ── Null operators ──

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

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

// ── Ordering ──

impl<T> Column<T> {
    /// `column ASC`
    pub fn asc(&self) -> OrderExpr {
        OrderExpr::new(self.any(), OrderDirection::Asc)
    }

    /// `column DESC`
    pub fn desc(&self) -> OrderExpr {
        OrderExpr::new(self.any(), OrderDirection::Desc)
    }

    /// `column ASC NULLS LAST`
    pub fn asc_nulls_last(&self) -> OrderExpr {
        OrderExpr::new(self.any(), OrderDirection::AscNullsLast)
    }

    /// `column DESC NULLS FIRST`
    pub fn desc_nulls_first(&self) -> OrderExpr {
        OrderExpr::new(self.any(), OrderDirection::DescNullsFirst)
    }
}

// ── AnyColumn (type-erased) ──

/// A type-erased column reference for use in dynamic contexts (e.g., `Value` bindings, `user_row!`).
#[derive(Debug, Clone)]
pub struct AnyColumn {
    name: &'static str,
    table: &'static str,
}

impl AnyColumn {
    pub const fn new(name: &'static str, table: &'static str) -> Self {
        Self { name, table }
    }

    pub const fn name(&self) -> &'static str {
        self.name
    }

    pub const fn table(&self) -> &'static str {
        self.table
    }
}

// ── Tests ──

#[cfg(test)]
mod tests {
    use super::*;

    fn col_id() -> Column<i32> {
        Column::new("id", "users")
    }

    fn col_age() -> Column<i32> {
        Column::new("age", "users")
    }

    fn col_name() -> Column<String> {
        Column::new("name", "users")
    }

    fn col_email() -> Column<String> {
        Column::new("email", "users")
    }

    // ── Column basics ──

    #[test]
    fn column_name_and_table() {
        let col = col_age();
        assert_eq!(col.name(), "age");
        assert_eq!(col.table(), "users");
    }

    #[test]
    fn column_into_any() {
        let any = col_age().into_any();
        assert_eq!(any.name(), "age");
        assert_eq!(any.table(), "users");
    }

    // ── Comparison operators ──

    #[test]
    fn column_eq() {
        let expr = col_age().eq(25);
        match expr {
            Expr::Eq(col, Value::Int(25)) => {
                assert_eq!(col.name(), "age");
            }
            _ => panic!("Expected Eq with Int(25)"),
        }
    }

    #[test]
    fn column_ne() {
        let expr = col_age().ne(0);
        assert!(matches!(expr, Expr::Ne(_, Value::Int(0))));
    }

    #[test]
    fn column_gt() {
        let expr = col_age().gt(25);
        assert!(matches!(expr, Expr::Gt(_, Value::Int(25))));
    }

    #[test]
    fn column_gte() {
        let expr = col_age().gte(18);
        assert!(matches!(expr, Expr::Gte(_, Value::Int(18))));
    }

    #[test]
    fn column_lt() {
        let expr = col_age().lt(65);
        assert!(matches!(expr, Expr::Lt(_, Value::Int(65))));
    }

    #[test]
    fn column_lte() {
        let expr = col_age().lte(100);
        assert!(matches!(expr, Expr::Lte(_, Value::Int(100))));
    }

    // ── Range ──

    #[test]
    fn column_between() {
        let expr = col_age().between(18, 65);
        match expr {
            Expr::Between(col, Value::Int(18), Value::Int(65)) => {
                assert_eq!(col.name(), "age");
            }
            _ => panic!("Expected Between(18, 65)"),
        }
    }

    #[test]
    fn column_in_list() {
        let expr = col_id().in_list(vec![1, 2, 3]);
        match expr {
            Expr::InList(col, vals) => {
                assert_eq!(col.name(), "id");
                assert_eq!(vals.len(), 3);
                assert_eq!(vals[0], Value::Int(1));
                assert_eq!(vals[1], Value::Int(2));
                assert_eq!(vals[2], Value::Int(3));
            }
            _ => panic!("Expected InList"),
        }
    }

    #[test]
    fn column_in_list_empty() {
        let expr = col_id().in_list(Vec::<i32>::new());
        match expr {
            Expr::InList(_, vals) => assert!(vals.is_empty()),
            _ => panic!("Expected InList"),
        }
    }

    #[test]
    fn column_not_in() {
        let expr = col_id().not_in(vec![4, 5]);
        match expr {
            Expr::NotIn(col, vals) => {
                assert_eq!(col.name(), "id");
                assert_eq!(vals.len(), 2);
            }
            _ => panic!("Expected NotIn"),
        }
    }

    // ── String operators ──

    #[test]
    fn column_like() {
        let expr = col_name().like("A%");
        match expr {
            Expr::Like(col, Value::String(ref s)) => {
                assert_eq!(col.name(), "name");
                assert_eq!(s, "A%");
            }
            _ => panic!("Expected Like"),
        }
    }

    #[test]
    fn column_ilike() {
        let expr = col_name().ilike("alice%");
        assert!(matches!(expr, Expr::ILike(_, _)));
    }

    #[test]
    fn column_contains() {
        let expr = col_name().contains("foo");
        match expr {
            Expr::Like(_, Value::String(ref s)) => {
                assert_eq!(s, "%foo%");
            }
            _ => panic!("Expected Like with %foo%"),
        }
    }

    #[test]
    fn column_starts_with() {
        let expr = col_name().starts_with("A");
        match expr {
            Expr::Like(_, Value::String(ref s)) => {
                assert_eq!(s, "A%");
            }
            _ => panic!("Expected Like with A%"),
        }
    }

    #[test]
    fn column_ends_with() {
        let expr = col_name().ends_with("z");
        match expr {
            Expr::Like(_, Value::String(ref s)) => {
                assert_eq!(s, "%z");
            }
            _ => panic!("Expected Like with %z"),
        }
    }

    // ── Null operators ──

    #[test]
    fn column_is_null() {
        let expr = col_email().is_null();
        match expr {
            Expr::IsNull(col) => assert_eq!(col.name(), "email"),
            _ => panic!("Expected IsNull"),
        }
    }

    #[test]
    fn column_is_not_null() {
        let expr = col_email().is_not_null();
        match expr {
            Expr::IsNotNull(col) => assert_eq!(col.name(), "email"),
            _ => panic!("Expected IsNotNull"),
        }
    }

    // ── Ordering ──

    #[test]
    fn column_asc() {
        let o = col_name().asc();
        assert_eq!(o.column.name(), "name");
        assert_eq!(o.direction, OrderDirection::Asc);
    }

    #[test]
    fn column_desc() {
        let o = col_age().desc();
        assert_eq!(o.direction, OrderDirection::Desc);
    }

    #[test]
    fn column_asc_nulls_last() {
        let o = col_age().asc_nulls_last();
        assert_eq!(o.direction, OrderDirection::AscNullsLast);
    }

    #[test]
    fn column_desc_nulls_first() {
        let o = col_age().desc_nulls_first();
        assert_eq!(o.direction, OrderDirection::DescNullsFirst);
    }

    // ── Chaining ──

    #[test]
    fn column_chain_and() {
        let expr = col_age().gt(25).and(col_name().eq("Alice"));
        assert!(matches!(expr, Expr::And(_, _)));
    }

    #[test]
    fn column_chain_or() {
        let expr = col_age().lt(18).or(col_age().gt(65));
        assert!(matches!(expr, Expr::Or(_, _)));
    }

    #[test]
    fn column_chain_not() {
        let expr = col_email().is_null().not();
        assert!(matches!(expr, Expr::Not(_)));
    }

    #[test]
    fn column_complex_filter() {
        // (age BETWEEN 18 AND 65) AND (email IS NOT NULL) OR (name = 'admin')
        let expr = col_age()
            .between(18, 65)
            .and(col_email().is_not_null())
            .or(col_name().eq("admin"));

        // Should be: Or(And(Between, IsNotNull), Eq)
        match expr {
            Expr::Or(left, right) => {
                assert!(matches!(*left, Expr::And(_, _)));
                assert!(matches!(*right, Expr::Eq(_, _)));
            }
            _ => panic!("Expected Or(And(...), Eq(...))"),
        }
    }

    // ── Type safety: different column types ──

    #[test]
    fn column_string_eq() {
        let expr = col_name().eq("Alice");
        match expr {
            Expr::Eq(_, Value::String(ref s)) => assert_eq!(s, "Alice"),
            _ => panic!("Expected Eq with String"),
        }
    }

    #[test]
    fn column_i16() {
        let col: Column<i16> = Column::new("age", "users");
        let expr = col.eq(25i16);
        assert!(matches!(expr, Expr::Eq(_, Value::Short(25))));
    }

    #[test]
    fn column_i64() {
        let col: Column<i64> = Column::new("big_id", "users");
        let expr = col.eq(999i64);
        assert!(matches!(expr, Expr::Eq(_, Value::BigInt(999))));
    }

    #[test]
    fn column_bool() {
        let col: Column<bool> = Column::new("is_active", "users");
        let expr = col.eq(true);
        assert!(matches!(expr, Expr::Eq(_, Value::Bool(true))));
    }
}