ignis-db 0.2.0

A comprehensive PostgreSQL ORM with macro-driven schema management
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
//! Hybrid expression system for type-safe, high-performance SQL query building
//!
//! This module implements a hybrid approach that combines:
//! - Enum-based dispatch for core SQL operations (95% of usage) - maximum performance
//! - Trait object extensibility for plugins (5% of usage) - maximum flexibility

use crate::BindValue;
use std::{any::Any, fmt, sync::Arc};

// ===== Core Column Types =====

/// Column type information for type safety
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ColumnType {
    Simple,
    Composite(String),
    Array(Box<ColumnType>),
}

/// Column expression with table and type information
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ColumnExpr {
    pub table: Option<String>,
    pub name: String,
    pub ty: ColumnType,
}

impl ColumnExpr {
    /// Create a simple column reference
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            table: None,
            name: name.into(),
            ty: ColumnType::Simple,
        }
    }

    /// Create a column with table reference
    pub fn with_table(table: impl Into<String>, name: impl Into<String>) -> Self {
        Self {
            table: Some(table.into()),
            name: name.into(),
            ty: ColumnType::Simple,
        }
    }

    /// Create a composite column reference
    pub fn composite(name: impl Into<String>, composite_type: impl Into<String>) -> Self {
        Self {
            table: None,
            name: name.into(),
            ty: ColumnType::Composite(composite_type.into()),
        }
    }
}

// ===== Value Types =====

/// Value expression that can be used in comparisons
#[derive(Clone, Debug, PartialEq)]
pub enum ValueExpr {
    Bind(BindValue),
    Column(ColumnExpr),
    Tuple(Vec<BindValue>), // for IN lists
}

impl<V: Into<BindValue>> From<V> for ValueExpr {
    fn from(v: V) -> Self {
        ValueExpr::Bind(v.into())
    }
}

// ===== Comparison Operators =====

/// SQL comparison operators
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CmpOp {
    Eq,
    Ne,
    Gt,
    Ge,
    Lt,
    Le,
    Like,
    ILike,
    In,
    NotIn,
}

impl CmpOp {
    /// Convert to SQL operator string
    #[inline]
    pub fn to_sql(self) -> &'static str {
        match self {
            CmpOp::Eq => "=",
            CmpOp::Ne => "<>",
            CmpOp::Gt => ">",
            CmpOp::Ge => ">=",
            CmpOp::Lt => "<",
            CmpOp::Le => "<=",
            CmpOp::Like => "LIKE",
            CmpOp::ILike => "ILIKE",
            CmpOp::In => "IN",
            CmpOp::NotIn => "NOT IN",
        }
    }
}

// ===== Core Expression Types =====

/// Comparison expression (e.g., column = value)
#[derive(Clone, Debug, PartialEq)]
pub struct ComparisonExpr {
    pub left: ColumnExpr,
    pub op: CmpOp,
    pub right: ValueExpr,
}

/// Null check types
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum NullCheckKind {
    IsNull,
    IsNotNull,
}

/// Null check expression
#[derive(Clone, Debug, PartialEq)]
pub struct NullCheckExpr {
    pub column: ColumnExpr,
    pub kind: NullCheckKind,
}

// ===== Plugin Extension Trait =====

/// Trait for external expressions that can be plugged into the system
pub trait ExtBoolExpr: fmt::Debug + Send + Sync + 'static {
    /// Render SQL and push bind values in order
    fn write_sql(&self, out: &mut String, binds: &mut Vec<BindValue>);

    /// Optional downcasting hook for typed access
    fn as_any(&self) -> &dyn Any
    where
        Self: Sized,
    {
        self
    }

    /// Precedence for parenthesization (higher = tighter binding)
    fn precedence(&self) -> u8 {
        5 // Default middle precedence
    }
}

// ===== Hybrid Boolean Expression Enum =====

/// The main expression type - hybrid enum for performance and extensibility
#[derive(Clone, Debug)]
pub enum BoolExpr {
    // Core SQL operations - zero overhead enum dispatch
    Comparison(ComparisonExpr),
    NullCheck(NullCheckExpr),
    And(Box<BoolExpr>, Box<BoolExpr>),
    Or(Box<BoolExpr>, Box<BoolExpr>),
    Not(Box<BoolExpr>),
    Parens(Box<BoolExpr>),
    Literal(bool),

    // Extension point for plugins - trait object only when needed
    Custom(Arc<dyn ExtBoolExpr>),
}

impl BoolExpr {
    /// Combine with AND
    #[inline]
    pub fn and(self, rhs: BoolExpr) -> Self {
        BoolExpr::And(Box::new(self), Box::new(rhs))
    }

    /// Combine with OR
    #[inline]
    pub fn or(self, rhs: BoolExpr) -> Self {
        BoolExpr::Or(Box::new(self), Box::new(rhs))
    }

    /// Negate the expression
    #[inline]
    pub fn not(self) -> Self {
        BoolExpr::Not(Box::new(self))
    }

    /// Add parentheses for precedence
    #[inline]
    pub fn grouped(self) -> Self {
        BoolExpr::Parens(Box::new(self))
    }
}

// ===== Column-specific operations (compile-time safety) =====

/// Operations only available on columns
pub trait ColumnOps: Sized {
    /// Check if column is NULL
    fn is_null(self) -> BoolExpr;

    /// Check if column is NOT NULL
    fn not_null(self) -> BoolExpr;
}

/// Comparison operations only available on columns
pub trait CompareOps: Sized {
    /// Equal comparison
    fn eq<V: Into<BindValue>>(self, v: V) -> BoolExpr;

    /// Not equal comparison
    fn ne<V: Into<BindValue>>(self, v: V) -> BoolExpr;

    /// Greater than comparison
    fn gt<V: Into<BindValue>>(self, v: V) -> BoolExpr;

    /// Greater than or equal comparison
    fn ge<V: Into<BindValue>>(self, v: V) -> BoolExpr;

    /// Less than comparison
    fn lt<V: Into<BindValue>>(self, v: V) -> BoolExpr;

    /// Less than or equal comparison
    fn le<V: Into<BindValue>>(self, v: V) -> BoolExpr;

    /// LIKE pattern matching
    fn like<V: Into<BindValue>>(self, v: V) -> BoolExpr;

    /// Case-insensitive LIKE
    fn ilike<V: Into<BindValue>>(self, v: V) -> BoolExpr;

    /// IN list check
    fn is_in<V: Into<BindValue>>(self, values: impl IntoIterator<Item = V>) -> BoolExpr;

    /// NOT IN list check
    fn not_in<V: Into<BindValue>>(self, values: impl IntoIterator<Item = V>) -> BoolExpr;
}

// Implement column operations for ColumnExpr
impl ColumnOps for ColumnExpr {
    #[inline]
    fn is_null(self) -> BoolExpr {
        BoolExpr::NullCheck(NullCheckExpr {
            column: self,
            kind: NullCheckKind::IsNull,
        })
    }

    #[inline]
    fn not_null(self) -> BoolExpr {
        BoolExpr::NullCheck(NullCheckExpr {
            column: self,
            kind: NullCheckKind::IsNotNull,
        })
    }
}

// Implement comparison operations for ColumnExpr
impl CompareOps for ColumnExpr {
    #[inline]
    fn eq<V: Into<BindValue>>(self, v: V) -> BoolExpr {
        BoolExpr::Comparison(ComparisonExpr {
            left: self,
            op: CmpOp::Eq,
            right: ValueExpr::from(v),
        })
    }

    #[inline]
    fn ne<V: Into<BindValue>>(self, v: V) -> BoolExpr {
        BoolExpr::Comparison(ComparisonExpr {
            left: self,
            op: CmpOp::Ne,
            right: ValueExpr::from(v),
        })
    }

    #[inline]
    fn gt<V: Into<BindValue>>(self, v: V) -> BoolExpr {
        BoolExpr::Comparison(ComparisonExpr {
            left: self,
            op: CmpOp::Gt,
            right: ValueExpr::from(v),
        })
    }

    #[inline]
    fn ge<V: Into<BindValue>>(self, v: V) -> BoolExpr {
        BoolExpr::Comparison(ComparisonExpr {
            left: self,
            op: CmpOp::Ge,
            right: ValueExpr::from(v),
        })
    }

    #[inline]
    fn lt<V: Into<BindValue>>(self, v: V) -> BoolExpr {
        BoolExpr::Comparison(ComparisonExpr {
            left: self,
            op: CmpOp::Lt,
            right: ValueExpr::from(v),
        })
    }

    #[inline]
    fn le<V: Into<BindValue>>(self, v: V) -> BoolExpr {
        BoolExpr::Comparison(ComparisonExpr {
            left: self,
            op: CmpOp::Le,
            right: ValueExpr::from(v),
        })
    }

    #[inline]
    fn like<V: Into<BindValue>>(self, v: V) -> BoolExpr {
        BoolExpr::Comparison(ComparisonExpr {
            left: self,
            op: CmpOp::Like,
            right: ValueExpr::from(v),
        })
    }

    #[inline]
    fn ilike<V: Into<BindValue>>(self, v: V) -> BoolExpr {
        BoolExpr::Comparison(ComparisonExpr {
            left: self,
            op: CmpOp::ILike,
            right: ValueExpr::from(v),
        })
    }

    #[inline]
    fn is_in<V: Into<BindValue>>(self, values: impl IntoIterator<Item = V>) -> BoolExpr {
        let vals: Vec<BindValue> = values.into_iter().map(Into::into).collect();
        BoolExpr::Comparison(ComparisonExpr {
            left: self,
            op: CmpOp::In,
            right: ValueExpr::Tuple(vals),
        })
    }

    #[inline]
    fn not_in<V: Into<BindValue>>(self, values: impl IntoIterator<Item = V>) -> BoolExpr {
        let vals: Vec<BindValue> = values.into_iter().map(Into::into).collect();
        BoolExpr::Comparison(ComparisonExpr {
            left: self,
            op: CmpOp::NotIn,
            right: ValueExpr::Tuple(vals),
        })
    }
}

// ===== SQL Rendering =====

/// Trait for SQL generation
pub trait ToSql {
    /// Render SQL into buffer and collect bind values
    fn write_sql(&self, out: &mut String, binds: &mut Vec<BindValue>);
}

impl ToSql for ColumnExpr {
    #[inline]
    fn write_sql(&self, out: &mut String, _binds: &mut Vec<BindValue>) {
        if let Some(ref table) = self.table {
            out.push('"');
            out.push_str(table);
            out.push_str("\".");
        }
        out.push('"');
        out.push_str(&self.name);
        out.push('"');
    }
}

impl ToSql for ComparisonExpr {
    #[inline]
    fn write_sql(&self, out: &mut String, binds: &mut Vec<BindValue>) {
        self.left.write_sql(out, binds);
        out.push(' ');
        out.push_str(self.op.to_sql());
        out.push(' ');

        match &self.right {
            ValueExpr::Bind(v) => {
                out.push('?');
                binds.push(v.clone());
            }
            ValueExpr::Column(c) => {
                c.write_sql(out, binds);
            }
            ValueExpr::Tuple(vals) => {
                out.push('(');
                for (i, v) in vals.iter().enumerate() {
                    if i > 0 {
                        out.push_str(", ");
                    }
                    out.push('?');
                    binds.push(v.clone());
                }
                out.push(')');
            }
        }
    }
}

impl ToSql for NullCheckExpr {
    #[inline]
    fn write_sql(&self, out: &mut String, binds: &mut Vec<BindValue>) {
        self.column.write_sql(out, binds);
        match self.kind {
            NullCheckKind::IsNull => out.push_str(" IS NULL"),
            NullCheckKind::IsNotNull => out.push_str(" IS NOT NULL"),
        }
    }
}

impl ToSql for BoolExpr {
    #[inline]
    fn write_sql(&self, out: &mut String, binds: &mut Vec<BindValue>) {
        match self {
            BoolExpr::Comparison(c) => c.write_sql(out, binds),
            BoolExpr::NullCheck(n) => n.write_sql(out, binds),
            BoolExpr::And(left, right) => {
                left.write_sql(out, binds);
                out.push_str(" AND ");
                right.write_sql(out, binds);
            }
            BoolExpr::Or(left, right) => {
                left.write_sql(out, binds);
                out.push_str(" OR ");
                right.write_sql(out, binds);
            }
            BoolExpr::Not(expr) => {
                out.push_str("NOT ");
                expr.write_sql(out, binds);
            }
            BoolExpr::Parens(expr) => {
                out.push('(');
                expr.write_sql(out, binds);
                out.push(')');
            }
            BoolExpr::Literal(true) => out.push_str("TRUE"),
            BoolExpr::Literal(false) => out.push_str("FALSE"),
            BoolExpr::Custom(ext) => ext.write_sql(out, binds),
        }
    }
}

// Display implementation for debugging
impl fmt::Display for BoolExpr {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut sql = String::new();
        let mut binds = Vec::new();
        self.write_sql(&mut sql, &mut binds);
        write!(f, "{} -- binds: {:?}", sql, binds)
    }
}

// ===== Helper Functions =====

/// Create a column expression
pub fn col(name: impl Into<String>) -> ColumnExpr {
    ColumnExpr::new(name)
}

/// Create a column with table reference
pub fn table_col(table: impl Into<String>, name: impl Into<String>) -> ColumnExpr {
    ColumnExpr::with_table(table, name)
}

/// Create a literal boolean expression
pub fn literal(value: bool) -> BoolExpr {
    BoolExpr::Literal(value)
}

// ===== Tests =====

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

    #[test]
    fn test_column_operations() {
        // Test that column operations are only available on ColumnExpr
        let email = col("email");
        let age = col("age");

        // These compile - methods exist on ColumnExpr
        let expr = email.not_null().and(age.gt(18));

        let mut sql = String::new();
        let mut binds = vec![];
        expr.write_sql(&mut sql, &mut binds);

        assert_eq!(sql, r#""email" IS NOT NULL AND "age" > ?"#);
        assert_eq!(binds, vec![BindValue::Int4(18)]);
    }

    #[test]
    fn test_complex_expression() {
        let expr = table_col("users", "email")
            .not_null()
            .and(table_col("users", "age").ge(21))
            .or(table_col("users", "verified").eq(true))
            .grouped();

        let mut sql = String::new();
        let mut binds = vec![];
        expr.write_sql(&mut sql, &mut binds);

        assert_eq!(
            sql,
            r#"("users"."email" IS NOT NULL AND "users"."age" >= ? OR "users"."verified" = ?)"#
        );
        assert_eq!(binds, vec![BindValue::Int4(21), BindValue::Bool(true)]);
    }

    #[test]
    fn test_in_list() {
        let expr = col("status").is_in(["active", "pending", "approved"]);

        let mut sql = String::new();
        let mut binds = vec![];
        expr.write_sql(&mut sql, &mut binds);

        assert_eq!(sql, r#""status" IN (?, ?, ?)"#);
        assert_eq!(
            binds,
            vec![
                BindValue::Text("active".to_string()),
                BindValue::Text("pending".to_string()),
                BindValue::Text("approved".to_string()),
            ]
        );
    }

    #[test]
    fn test_not_expression() {
        let expr = col("active").eq(false).not();

        let mut sql = String::new();
        let mut binds = vec![];
        expr.write_sql(&mut sql, &mut binds);

        assert_eq!(sql, r#"NOT "active" = ?"#);
        assert_eq!(binds, vec![BindValue::Bool(false)]);
    }

    // Test plugin extensibility
    #[derive(Debug)]
    struct GeoWithinExpr {
        geom_col: ColumnExpr,
        region_wkt: String,
    }

    impl ExtBoolExpr for GeoWithinExpr {
        fn write_sql(&self, out: &mut String, binds: &mut Vec<BindValue>) {
            out.push_str("ST_Within(");
            self.geom_col.write_sql(out, binds);
            out.push_str(", ST_GeomFromText(?))");
            binds.push(BindValue::Text(self.region_wkt.clone()));
        }
    }

    fn geo_within(geom_col: ColumnExpr, region_wkt: impl Into<String>) -> BoolExpr {
        BoolExpr::Custom(Arc::new(GeoWithinExpr {
            geom_col,
            region_wkt: region_wkt.into(),
        }))
    }

    #[test]
    fn test_plugin_expression() {
        let expr = geo_within(col("location"), "POLYGON((0 0, 1 0, 1 1, 0 1, 0 0))")
            .and(col("active").eq(true));

        let mut sql = String::new();
        let mut binds = vec![];
        expr.write_sql(&mut sql, &mut binds);

        assert_eq!(
            sql,
            r#"ST_Within("location", ST_GeomFromText(?)) AND "active" = ?"#
        );
        assert_eq!(
            binds,
            vec![
                BindValue::Text("POLYGON((0 0, 1 0, 1 1, 0 1, 0 0))".to_string()),
                BindValue::Bool(true),
            ]
        );
    }
}