pgorm 0.1.2

A lightweight Postgres-only ORM 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
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
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
//! Query builder types for dynamic WHERE, ORDER BY, and pagination.
//!
//! This module provides structured builders for constructing SQL clauses safely:
//! - [`WhereExpr`]: Boolean expression tree for WHERE clauses (AND/OR/NOT/grouping)
//! - [`OrderBy`]: Structured ORDER BY builder with nulls handling
//! - [`Pagination`]: LIMIT/OFFSET builder
//! - [`Ident`]: Safe SQL identifier handling (see [`crate::Ident`])

use crate::Ident;
use crate::condition::Condition;
use crate::error::{OrmError, OrmResult};
use crate::ident::IntoIdent;
use crate::sql::Sql;

// ==================== WhereExpr: Boolean expression tree ====================

/// A WHERE clause expression tree supporting AND/OR/NOT/grouping.
///
/// # Example
/// ```ignore
/// use pgorm::builder::WhereExpr;
/// use pgorm::Condition;
///
/// let expr = WhereExpr::And(vec![
///     WhereExpr::Atom(Condition::eq("status", "active")?),
///     WhereExpr::Or(vec![
///         WhereExpr::Atom(Condition::eq("role", "admin")?),
///         WhereExpr::Atom(Condition::eq("role", "owner")?),
///     ]),
/// ]);
/// ```
#[derive(Debug, Clone)]
pub enum WhereExpr {
    /// A single atomic condition.
    Atom(Condition),
    /// Conjunction of expressions (AND).
    And(Vec<WhereExpr>),
    /// Disjunction of expressions (OR).
    Or(Vec<WhereExpr>),
    /// Negation of an expression (NOT).
    Not(Box<WhereExpr>),
    /// Raw SQL expression (escape hatch - use with caution).
    ///
    /// **Warning**: This bypasses SQL injection protection. Only use with
    /// trusted, hardcoded SQL strings.
    Raw(String),
}

impl WhereExpr {
    /// Create an atomic condition expression.
    pub fn atom(condition: Condition) -> Self {
        WhereExpr::Atom(condition)
    }

    /// Create an AND expression from multiple sub-expressions.
    pub fn and(exprs: Vec<WhereExpr>) -> Self {
        WhereExpr::And(exprs)
    }

    /// Create an OR expression from multiple sub-expressions.
    pub fn or(exprs: Vec<WhereExpr>) -> Self {
        WhereExpr::Or(exprs)
    }

    /// Create a NOT expression.
    #[allow(clippy::should_implement_trait)]
    pub fn not(expr: WhereExpr) -> Self {
        WhereExpr::Not(Box::new(expr))
    }

    /// Create a raw SQL expression.
    ///
    /// **Warning**: This bypasses SQL injection protection. Only use with
    /// trusted, hardcoded SQL strings.
    pub fn raw(sql: impl Into<String>) -> Self {
        WhereExpr::Raw(sql.into())
    }

    /// Combine this expression with another using AND.
    pub fn and_with(self, other: WhereExpr) -> WhereExpr {
        match self {
            WhereExpr::And(mut exprs) => {
                exprs.push(other);
                WhereExpr::And(exprs)
            }
            _ => WhereExpr::And(vec![self, other]),
        }
    }

    /// Combine this expression with another using OR.
    pub fn or_with(self, other: WhereExpr) -> WhereExpr {
        match self {
            WhereExpr::Or(mut exprs) => {
                exprs.push(other);
                WhereExpr::Or(exprs)
            }
            _ => WhereExpr::Or(vec![self, other]),
        }
    }

    /// Returns `true` if this expression is the identity `TRUE` (i.e. `AND([])`).
    pub fn is_trivially_true(&self) -> bool {
        matches!(self, WhereExpr::And(exprs) if exprs.is_empty())
    }

    /// Returns `true` if this expression is the identity `FALSE` (i.e. `OR([])`).
    pub fn is_trivially_false(&self) -> bool {
        matches!(self, WhereExpr::Or(exprs) if exprs.is_empty())
    }

    /// Append this expression to a SQL builder.
    ///
    /// Parentheses are added around compound expressions to ensure correct precedence.
    pub fn append_to_sql(&self, sql: &mut Sql) {
        match self {
            WhereExpr::Atom(cond) => {
                cond.append_to_sql(sql);
            }
            WhereExpr::And(exprs) => {
                if exprs.is_empty() {
                    // Empty AND is TRUE
                    sql.push("TRUE");
                } else if exprs.len() == 1 {
                    exprs[0].append_to_sql(sql);
                } else {
                    sql.push("(");
                    for (i, expr) in exprs.iter().enumerate() {
                        if i > 0 {
                            sql.push(" AND ");
                        }
                        expr.append_to_sql(sql);
                    }
                    sql.push(")");
                }
            }
            WhereExpr::Or(exprs) => {
                if exprs.is_empty() {
                    // Empty OR is FALSE
                    sql.push("FALSE");
                } else if exprs.len() == 1 {
                    exprs[0].append_to_sql(sql);
                } else {
                    sql.push("(");
                    for (i, expr) in exprs.iter().enumerate() {
                        if i > 0 {
                            sql.push(" OR ");
                        }
                        expr.append_to_sql(sql);
                    }
                    sql.push(")");
                }
            }
            WhereExpr::Not(expr) => {
                sql.push("(NOT ");
                expr.append_to_sql(sql);
                sql.push(")");
            }
            WhereExpr::Raw(s) => {
                sql.push(s);
            }
        }
    }
}

impl From<Condition> for WhereExpr {
    fn from(cond: Condition) -> Self {
        WhereExpr::Atom(cond)
    }
}

// ==================== OrderBy: Structured ORDER BY builder ====================

/// Sort direction for ORDER BY.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SortDir {
    #[default]
    Asc,
    Desc,
}

impl SortDir {
    fn to_sql(self) -> &'static str {
        match self {
            SortDir::Asc => "ASC",
            SortDir::Desc => "DESC",
        }
    }
}

/// NULLS ordering for ORDER BY.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NullsOrder {
    First,
    Last,
}

impl NullsOrder {
    fn to_sql(self) -> &'static str {
        match self {
            NullsOrder::First => "NULLS FIRST",
            NullsOrder::Last => "NULLS LAST",
        }
    }
}

/// A single ORDER BY item.
#[derive(Debug, Clone)]
pub enum OrderItem {
    Column {
        column: Ident,
        dir: SortDir,
        nulls: Option<NullsOrder>,
    },
    /// Raw SQL (escape hatch - use with extreme caution).
    Raw(String),
}

impl OrderItem {
    /// Create a new order item (validated identifier).
    pub fn new(column: Ident, dir: SortDir) -> Self {
        Self::Column {
            column,
            dir,
            nulls: None,
        }
    }

    /// Create a raw SQL order item.
    pub fn raw(sql: impl Into<String>) -> Self {
        Self::Raw(sql.into())
    }

    /// Set NULLS ordering (no-op for raw items).
    pub fn nulls(mut self, order: NullsOrder) -> Self {
        if let OrderItem::Column { nulls, .. } = &mut self {
            *nulls = Some(order);
        }
        self
    }

    fn append_to_sql(&self, sql: &mut Sql) {
        match self {
            OrderItem::Column { column, dir, nulls } => {
                sql.push(&column.to_sql());
                sql.push(" ");
                sql.push(dir.to_sql());
                if let Some(nulls) = nulls {
                    sql.push(" ");
                    sql.push(nulls.to_sql());
                }
            }
            OrderItem::Raw(s) => {
                sql.push(s);
            }
        }
    }
}

/// ORDER BY clause builder.
///
/// # Example
/// ```ignore
/// use pgorm::builder::{OrderBy, SortDir, NullsOrder};
///
/// let order = OrderBy::new()
///     .asc("created_at")
///     .desc("priority")
///     .with_nulls("last_login", SortDir::Desc, NullsOrder::Last);
/// ```
#[derive(Debug, Clone, Default)]
pub struct OrderBy {
    items: Vec<OrderItem>,
}

impl OrderBy {
    /// Create a new empty OrderBy builder.
    pub fn new() -> Self {
        Self::default()
    }

    /// Add an ascending sort (validated identifier).
    pub fn asc(mut self, column: impl IntoIdent) -> OrmResult<Self> {
        self.items
            .push(OrderItem::new(column.into_ident()?, SortDir::Asc));
        Ok(self)
    }

    /// Add a descending sort (validated identifier).
    pub fn desc(mut self, column: impl IntoIdent) -> OrmResult<Self> {
        self.items
            .push(OrderItem::new(column.into_ident()?, SortDir::Desc));
        Ok(self)
    }

    /// Add a sort with custom direction and nulls ordering.
    pub fn with_nulls(
        mut self,
        column: impl IntoIdent,
        dir: SortDir,
        nulls: NullsOrder,
    ) -> OrmResult<Self> {
        self.items
            .push(OrderItem::new(column.into_ident()?, dir).nulls(nulls));
        Ok(self)
    }

    /// Add a custom order item.
    #[allow(clippy::should_implement_trait)]
    pub fn add(mut self, item: OrderItem) -> Self {
        self.items.push(item);
        self
    }

    /// Check if this OrderBy is empty.
    pub fn is_empty(&self) -> bool {
        self.items.is_empty()
    }

    /// Append this ORDER BY clause to a SQL builder.
    ///
    /// Does nothing if the OrderBy is empty.
    pub fn append_to_sql(&self, sql: &mut Sql) {
        if self.items.is_empty() {
            return;
        }
        sql.push(" ORDER BY ");
        for (i, item) in self.items.iter().enumerate() {
            if i > 0 {
                sql.push(", ");
            }
            item.append_to_sql(sql);
        }
    }

    /// Build the ORDER BY clause as a string.
    pub fn to_sql(&self) -> String {
        if self.items.is_empty() {
            return String::new();
        }
        let mut sql = Sql::empty();
        sql.push("ORDER BY ");
        for (i, item) in self.items.iter().enumerate() {
            if i > 0 {
                sql.push(", ");
            }
            item.append_to_sql(&mut sql);
        }
        sql.to_sql()
    }
}

// ==================== Pagination: LIMIT/OFFSET builder ====================

/// Pagination configuration for LIMIT/OFFSET.
///
/// # Example
/// ```ignore
/// use pgorm::builder::Pagination;
///
/// // Direct limit/offset
/// let pag = Pagination::new().limit(10).offset(20);
///
/// // Page-based (page 3 with 25 items per page)
/// let pag = Pagination::page(3, 25)?;
/// ```
#[derive(Debug, Clone, Default)]
pub struct Pagination {
    pub limit: Option<i64>,
    pub offset: Option<i64>,
}

impl Pagination {
    /// Create a new empty pagination (no limit/offset).
    pub fn new() -> Self {
        Self::default()
    }

    /// Create pagination from page number and page size.
    ///
    /// Page numbers start at 1. Returns error if page < 1.
    pub fn page(page: i64, per_page: i64) -> OrmResult<Self> {
        if page < 1 {
            return Err(OrmError::validation(format!(
                "page must be >= 1, got {page}"
            )));
        }
        Ok(Self {
            limit: Some(per_page),
            offset: Some((page - 1) * per_page),
        })
    }

    /// Set the limit.
    pub fn limit(mut self, n: i64) -> Self {
        self.limit = Some(n);
        self
    }

    /// Set the offset.
    pub fn offset(mut self, n: i64) -> Self {
        self.offset = Some(n);
        self
    }

    /// Check if pagination is set.
    pub fn is_empty(&self) -> bool {
        self.limit.is_none() && self.offset.is_none()
    }

    /// Append LIMIT/OFFSET to a SQL builder with bound parameters.
    pub fn append_to_sql(&self, sql: &mut Sql) {
        if let Some(limit) = self.limit {
            sql.push(" LIMIT ");
            sql.push_bind(limit);
        }
        if let Some(offset) = self.offset {
            sql.push(" OFFSET ");
            sql.push_bind(offset);
        }
    }
}

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

    // ==================== WhereExpr tests ====================

    #[test]
    fn where_atom() {
        let expr = WhereExpr::atom(Condition::eq("status", "active").unwrap());
        let mut sql = Sql::empty();
        expr.append_to_sql(&mut sql);
        assert_eq!(sql.to_sql(), "status = $1");
    }

    #[test]
    fn where_and() {
        let expr = WhereExpr::And(vec![
            WhereExpr::Atom(Condition::eq("a", 1_i32).unwrap()),
            WhereExpr::Atom(Condition::eq("b", 2_i32).unwrap()),
        ]);
        let mut sql = Sql::empty();
        expr.append_to_sql(&mut sql);
        assert_eq!(sql.to_sql(), "(a = $1 AND b = $2)");
    }

    #[test]
    fn where_or() {
        let expr = WhereExpr::Or(vec![
            WhereExpr::Atom(Condition::eq("role", "admin").unwrap()),
            WhereExpr::Atom(Condition::eq("role", "owner").unwrap()),
        ]);
        let mut sql = Sql::empty();
        expr.append_to_sql(&mut sql);
        assert_eq!(sql.to_sql(), "(role = $1 OR role = $2)");
    }

    #[test]
    fn where_not() {
        let expr = WhereExpr::Not(Box::new(WhereExpr::Atom(
            Condition::eq("deleted", true).unwrap(),
        )));
        let mut sql = Sql::empty();
        expr.append_to_sql(&mut sql);
        assert_eq!(sql.to_sql(), "(NOT deleted = $1)");
    }

    #[test]
    fn where_nested() {
        let expr = WhereExpr::And(vec![
            WhereExpr::Atom(Condition::eq("status", "active").unwrap()),
            WhereExpr::Or(vec![
                WhereExpr::Atom(Condition::eq("role", "admin").unwrap()),
                WhereExpr::Atom(Condition::eq("role", "owner").unwrap()),
            ]),
        ]);
        let mut sql = Sql::empty();
        expr.append_to_sql(&mut sql);
        assert_eq!(sql.to_sql(), "(status = $1 AND (role = $2 OR role = $3))");
    }

    #[test]
    fn where_empty_and_is_true() {
        let expr = WhereExpr::And(vec![]);
        let mut sql = Sql::empty();
        expr.append_to_sql(&mut sql);
        assert_eq!(sql.to_sql(), "TRUE");
    }

    #[test]
    fn where_empty_or_is_false() {
        let expr = WhereExpr::Or(vec![]);
        let mut sql = Sql::empty();
        expr.append_to_sql(&mut sql);
        assert_eq!(sql.to_sql(), "FALSE");
    }

    #[test]
    fn where_and_with_combines() {
        let a = WhereExpr::atom(Condition::eq("a", 1_i32).unwrap());
        let b = WhereExpr::atom(Condition::eq("b", 2_i32).unwrap());
        let expr = a.and_with(b);
        let mut sql = Sql::empty();
        expr.append_to_sql(&mut sql);
        assert_eq!(sql.to_sql(), "(a = $1 AND b = $2)");
    }

    #[test]
    fn where_raw() {
        let expr = WhereExpr::raw("custom_func(x) > 0");
        let mut sql = Sql::empty();
        expr.append_to_sql(&mut sql);
        assert_eq!(sql.to_sql(), "custom_func(x) > 0");
    }

    // ==================== OrderBy tests ====================

    #[test]
    fn order_by_single_asc() {
        let order = OrderBy::new().asc("created_at").unwrap();
        assert_eq!(order.to_sql(), "ORDER BY created_at ASC");
    }

    #[test]
    fn order_by_single_desc() {
        let order = OrderBy::new().desc("priority").unwrap();
        assert_eq!(order.to_sql(), "ORDER BY priority DESC");
    }

    #[test]
    fn order_by_multiple() {
        let order = OrderBy::new()
            .asc("status")
            .unwrap()
            .desc("created_at")
            .unwrap();
        assert_eq!(order.to_sql(), "ORDER BY status ASC, created_at DESC");
    }

    #[test]
    fn order_by_with_nulls() {
        let order = OrderBy::new()
            .with_nulls("last_login", SortDir::Desc, NullsOrder::Last)
            .unwrap();
        assert_eq!(order.to_sql(), "ORDER BY last_login DESC NULLS LAST");
    }

    #[test]
    fn order_by_empty() {
        let order = OrderBy::new();
        assert!(order.is_empty());
        assert_eq!(order.to_sql(), "");
    }

    #[test]
    fn order_by_append() {
        let order = OrderBy::new().asc("id").unwrap();
        let mut sql = Sql::new("SELECT * FROM users");
        order.append_to_sql(&mut sql);
        assert_eq!(sql.to_sql(), "SELECT * FROM users ORDER BY id ASC");
    }

    #[test]
    fn order_by_validates_column() {
        let res = OrderBy::new().asc("valid_column; DROP TABLE users;");
        assert!(res.is_err());
    }

    // ==================== Pagination tests ====================

    #[test]
    fn pagination_limit_only() {
        let pag = Pagination::new().limit(10);
        let mut sql = Sql::new("SELECT * FROM users");
        pag.append_to_sql(&mut sql);
        assert_eq!(sql.to_sql(), "SELECT * FROM users LIMIT $1");
    }

    #[test]
    fn pagination_offset_only() {
        let pag = Pagination::new().offset(20);
        let mut sql = Sql::new("SELECT * FROM users");
        pag.append_to_sql(&mut sql);
        assert_eq!(sql.to_sql(), "SELECT * FROM users OFFSET $1");
    }

    #[test]
    fn pagination_limit_offset() {
        let pag = Pagination::new().limit(10).offset(20);
        let mut sql = Sql::new("SELECT * FROM users");
        pag.append_to_sql(&mut sql);
        assert_eq!(sql.to_sql(), "SELECT * FROM users LIMIT $1 OFFSET $2");
    }

    #[test]
    fn pagination_page() {
        let pag = Pagination::page(3, 25).unwrap();
        assert_eq!(pag.limit, Some(25));
        assert_eq!(pag.offset, Some(50)); // (3-1) * 25 = 50
    }

    #[test]
    fn pagination_page_one() {
        let pag = Pagination::page(1, 10).unwrap();
        assert_eq!(pag.limit, Some(10));
        assert_eq!(pag.offset, Some(0));
    }

    #[test]
    fn pagination_page_rejects_zero() {
        assert!(Pagination::page(0, 10).is_err());
    }

    #[test]
    fn pagination_page_rejects_negative() {
        assert!(Pagination::page(-1, 10).is_err());
    }

    #[test]
    fn pagination_empty() {
        let pag = Pagination::new();
        assert!(pag.is_empty());
        let mut sql = Sql::new("SELECT * FROM users");
        pag.append_to_sql(&mut sql);
        assert_eq!(sql.to_sql(), "SELECT * FROM users");
    }
}