Skip to main content

ignis_db/dsl/
hybrid_expr.rs

1//! Hybrid expression system for type-safe, high-performance SQL query building
2//!
3//! This module implements a hybrid approach that combines:
4//! - Enum-based dispatch for core SQL operations (95% of usage) - maximum performance
5//! - Trait object extensibility for plugins (5% of usage) - maximum flexibility
6
7use crate::BindValue;
8use std::{any::Any, fmt, sync::Arc};
9
10// ===== Core Column Types =====
11
12/// Column type information for type safety
13#[derive(Clone, Debug, PartialEq, Eq)]
14pub enum ColumnType {
15    Simple,
16    Composite(String),
17    Array(Box<ColumnType>),
18}
19
20/// Column expression with table and type information
21#[derive(Clone, Debug, PartialEq, Eq)]
22pub struct ColumnExpr {
23    pub table: Option<String>,
24    pub name: String,
25    pub ty: ColumnType,
26}
27
28impl ColumnExpr {
29    /// Create a simple column reference
30    pub fn new(name: impl Into<String>) -> Self {
31        Self {
32            table: None,
33            name: name.into(),
34            ty: ColumnType::Simple,
35        }
36    }
37
38    /// Create a column with table reference
39    pub fn with_table(table: impl Into<String>, name: impl Into<String>) -> Self {
40        Self {
41            table: Some(table.into()),
42            name: name.into(),
43            ty: ColumnType::Simple,
44        }
45    }
46
47    /// Create a composite column reference
48    pub fn composite(name: impl Into<String>, composite_type: impl Into<String>) -> Self {
49        Self {
50            table: None,
51            name: name.into(),
52            ty: ColumnType::Composite(composite_type.into()),
53        }
54    }
55}
56
57// ===== Value Types =====
58
59/// Value expression that can be used in comparisons
60#[derive(Clone, Debug, PartialEq)]
61pub enum ValueExpr {
62    Bind(BindValue),
63    Column(ColumnExpr),
64    Tuple(Vec<BindValue>), // for IN lists
65}
66
67impl<V: Into<BindValue>> From<V> for ValueExpr {
68    fn from(v: V) -> Self {
69        ValueExpr::Bind(v.into())
70    }
71}
72
73// ===== Comparison Operators =====
74
75/// SQL comparison operators
76#[derive(Clone, Copy, Debug, PartialEq, Eq)]
77pub enum CmpOp {
78    Eq,
79    Ne,
80    Gt,
81    Ge,
82    Lt,
83    Le,
84    Like,
85    ILike,
86    In,
87    NotIn,
88}
89
90impl CmpOp {
91    /// Convert to SQL operator string
92    #[inline]
93    pub fn to_sql(self) -> &'static str {
94        match self {
95            CmpOp::Eq => "=",
96            CmpOp::Ne => "<>",
97            CmpOp::Gt => ">",
98            CmpOp::Ge => ">=",
99            CmpOp::Lt => "<",
100            CmpOp::Le => "<=",
101            CmpOp::Like => "LIKE",
102            CmpOp::ILike => "ILIKE",
103            CmpOp::In => "IN",
104            CmpOp::NotIn => "NOT IN",
105        }
106    }
107}
108
109// ===== Core Expression Types =====
110
111/// Comparison expression (e.g., column = value)
112#[derive(Clone, Debug, PartialEq)]
113pub struct ComparisonExpr {
114    pub left: ColumnExpr,
115    pub op: CmpOp,
116    pub right: ValueExpr,
117}
118
119/// Null check types
120#[derive(Clone, Copy, Debug, PartialEq, Eq)]
121pub enum NullCheckKind {
122    IsNull,
123    IsNotNull,
124}
125
126/// Null check expression
127#[derive(Clone, Debug, PartialEq)]
128pub struct NullCheckExpr {
129    pub column: ColumnExpr,
130    pub kind: NullCheckKind,
131}
132
133// ===== Plugin Extension Trait =====
134
135/// Trait for external expressions that can be plugged into the system
136pub trait ExtBoolExpr: fmt::Debug + Send + Sync + 'static {
137    /// Render SQL and push bind values in order
138    fn write_sql(&self, out: &mut String, binds: &mut Vec<BindValue>);
139
140    /// Optional downcasting hook for typed access
141    fn as_any(&self) -> &dyn Any
142    where
143        Self: Sized,
144    {
145        self
146    }
147
148    /// Precedence for parenthesization (higher = tighter binding)
149    fn precedence(&self) -> u8 {
150        5 // Default middle precedence
151    }
152}
153
154// ===== Hybrid Boolean Expression Enum =====
155
156/// The main expression type - hybrid enum for performance and extensibility
157#[derive(Clone, Debug)]
158pub enum BoolExpr {
159    // Core SQL operations - zero overhead enum dispatch
160    Comparison(ComparisonExpr),
161    NullCheck(NullCheckExpr),
162    And(Box<BoolExpr>, Box<BoolExpr>),
163    Or(Box<BoolExpr>, Box<BoolExpr>),
164    Not(Box<BoolExpr>),
165    Parens(Box<BoolExpr>),
166    Literal(bool),
167
168    // Extension point for plugins - trait object only when needed
169    Custom(Arc<dyn ExtBoolExpr>),
170}
171
172impl BoolExpr {
173    /// Combine with AND
174    #[inline]
175    pub fn and(self, rhs: BoolExpr) -> Self {
176        BoolExpr::And(Box::new(self), Box::new(rhs))
177    }
178
179    /// Combine with OR
180    #[inline]
181    pub fn or(self, rhs: BoolExpr) -> Self {
182        BoolExpr::Or(Box::new(self), Box::new(rhs))
183    }
184
185    /// Negate the expression
186    #[inline]
187    pub fn not(self) -> Self {
188        BoolExpr::Not(Box::new(self))
189    }
190
191    /// Add parentheses for precedence
192    #[inline]
193    pub fn grouped(self) -> Self {
194        BoolExpr::Parens(Box::new(self))
195    }
196}
197
198// ===== Column-specific operations (compile-time safety) =====
199
200/// Operations only available on columns
201pub trait ColumnOps: Sized {
202    /// Check if column is NULL
203    fn is_null(self) -> BoolExpr;
204
205    /// Check if column is NOT NULL
206    fn not_null(self) -> BoolExpr;
207}
208
209/// Comparison operations only available on columns
210pub trait CompareOps: Sized {
211    /// Equal comparison
212    fn eq<V: Into<BindValue>>(self, v: V) -> BoolExpr;
213
214    /// Not equal comparison
215    fn ne<V: Into<BindValue>>(self, v: V) -> BoolExpr;
216
217    /// Greater than comparison
218    fn gt<V: Into<BindValue>>(self, v: V) -> BoolExpr;
219
220    /// Greater than or equal comparison
221    fn ge<V: Into<BindValue>>(self, v: V) -> BoolExpr;
222
223    /// Less than comparison
224    fn lt<V: Into<BindValue>>(self, v: V) -> BoolExpr;
225
226    /// Less than or equal comparison
227    fn le<V: Into<BindValue>>(self, v: V) -> BoolExpr;
228
229    /// LIKE pattern matching
230    fn like<V: Into<BindValue>>(self, v: V) -> BoolExpr;
231
232    /// Case-insensitive LIKE
233    fn ilike<V: Into<BindValue>>(self, v: V) -> BoolExpr;
234
235    /// IN list check
236    fn is_in<V: Into<BindValue>>(self, values: impl IntoIterator<Item = V>) -> BoolExpr;
237
238    /// NOT IN list check
239    fn not_in<V: Into<BindValue>>(self, values: impl IntoIterator<Item = V>) -> BoolExpr;
240}
241
242// Implement column operations for ColumnExpr
243impl ColumnOps for ColumnExpr {
244    #[inline]
245    fn is_null(self) -> BoolExpr {
246        BoolExpr::NullCheck(NullCheckExpr {
247            column: self,
248            kind: NullCheckKind::IsNull,
249        })
250    }
251
252    #[inline]
253    fn not_null(self) -> BoolExpr {
254        BoolExpr::NullCheck(NullCheckExpr {
255            column: self,
256            kind: NullCheckKind::IsNotNull,
257        })
258    }
259}
260
261// Implement comparison operations for ColumnExpr
262impl CompareOps for ColumnExpr {
263    #[inline]
264    fn eq<V: Into<BindValue>>(self, v: V) -> BoolExpr {
265        BoolExpr::Comparison(ComparisonExpr {
266            left: self,
267            op: CmpOp::Eq,
268            right: ValueExpr::from(v),
269        })
270    }
271
272    #[inline]
273    fn ne<V: Into<BindValue>>(self, v: V) -> BoolExpr {
274        BoolExpr::Comparison(ComparisonExpr {
275            left: self,
276            op: CmpOp::Ne,
277            right: ValueExpr::from(v),
278        })
279    }
280
281    #[inline]
282    fn gt<V: Into<BindValue>>(self, v: V) -> BoolExpr {
283        BoolExpr::Comparison(ComparisonExpr {
284            left: self,
285            op: CmpOp::Gt,
286            right: ValueExpr::from(v),
287        })
288    }
289
290    #[inline]
291    fn ge<V: Into<BindValue>>(self, v: V) -> BoolExpr {
292        BoolExpr::Comparison(ComparisonExpr {
293            left: self,
294            op: CmpOp::Ge,
295            right: ValueExpr::from(v),
296        })
297    }
298
299    #[inline]
300    fn lt<V: Into<BindValue>>(self, v: V) -> BoolExpr {
301        BoolExpr::Comparison(ComparisonExpr {
302            left: self,
303            op: CmpOp::Lt,
304            right: ValueExpr::from(v),
305        })
306    }
307
308    #[inline]
309    fn le<V: Into<BindValue>>(self, v: V) -> BoolExpr {
310        BoolExpr::Comparison(ComparisonExpr {
311            left: self,
312            op: CmpOp::Le,
313            right: ValueExpr::from(v),
314        })
315    }
316
317    #[inline]
318    fn like<V: Into<BindValue>>(self, v: V) -> BoolExpr {
319        BoolExpr::Comparison(ComparisonExpr {
320            left: self,
321            op: CmpOp::Like,
322            right: ValueExpr::from(v),
323        })
324    }
325
326    #[inline]
327    fn ilike<V: Into<BindValue>>(self, v: V) -> BoolExpr {
328        BoolExpr::Comparison(ComparisonExpr {
329            left: self,
330            op: CmpOp::ILike,
331            right: ValueExpr::from(v),
332        })
333    }
334
335    #[inline]
336    fn is_in<V: Into<BindValue>>(self, values: impl IntoIterator<Item = V>) -> BoolExpr {
337        let vals: Vec<BindValue> = values.into_iter().map(Into::into).collect();
338        BoolExpr::Comparison(ComparisonExpr {
339            left: self,
340            op: CmpOp::In,
341            right: ValueExpr::Tuple(vals),
342        })
343    }
344
345    #[inline]
346    fn not_in<V: Into<BindValue>>(self, values: impl IntoIterator<Item = V>) -> BoolExpr {
347        let vals: Vec<BindValue> = values.into_iter().map(Into::into).collect();
348        BoolExpr::Comparison(ComparisonExpr {
349            left: self,
350            op: CmpOp::NotIn,
351            right: ValueExpr::Tuple(vals),
352        })
353    }
354}
355
356// ===== SQL Rendering =====
357
358/// Trait for SQL generation
359pub trait ToSql {
360    /// Render SQL into buffer and collect bind values
361    fn write_sql(&self, out: &mut String, binds: &mut Vec<BindValue>);
362}
363
364impl ToSql for ColumnExpr {
365    #[inline]
366    fn write_sql(&self, out: &mut String, _binds: &mut Vec<BindValue>) {
367        if let Some(ref table) = self.table {
368            out.push('"');
369            out.push_str(table);
370            out.push_str("\".");
371        }
372        out.push('"');
373        out.push_str(&self.name);
374        out.push('"');
375    }
376}
377
378impl ToSql for ComparisonExpr {
379    #[inline]
380    fn write_sql(&self, out: &mut String, binds: &mut Vec<BindValue>) {
381        self.left.write_sql(out, binds);
382        out.push(' ');
383        out.push_str(self.op.to_sql());
384        out.push(' ');
385
386        match &self.right {
387            ValueExpr::Bind(v) => {
388                out.push('?');
389                binds.push(v.clone());
390            }
391            ValueExpr::Column(c) => {
392                c.write_sql(out, binds);
393            }
394            ValueExpr::Tuple(vals) => {
395                out.push('(');
396                for (i, v) in vals.iter().enumerate() {
397                    if i > 0 {
398                        out.push_str(", ");
399                    }
400                    out.push('?');
401                    binds.push(v.clone());
402                }
403                out.push(')');
404            }
405        }
406    }
407}
408
409impl ToSql for NullCheckExpr {
410    #[inline]
411    fn write_sql(&self, out: &mut String, binds: &mut Vec<BindValue>) {
412        self.column.write_sql(out, binds);
413        match self.kind {
414            NullCheckKind::IsNull => out.push_str(" IS NULL"),
415            NullCheckKind::IsNotNull => out.push_str(" IS NOT NULL"),
416        }
417    }
418}
419
420impl ToSql for BoolExpr {
421    #[inline]
422    fn write_sql(&self, out: &mut String, binds: &mut Vec<BindValue>) {
423        match self {
424            BoolExpr::Comparison(c) => c.write_sql(out, binds),
425            BoolExpr::NullCheck(n) => n.write_sql(out, binds),
426            BoolExpr::And(left, right) => {
427                left.write_sql(out, binds);
428                out.push_str(" AND ");
429                right.write_sql(out, binds);
430            }
431            BoolExpr::Or(left, right) => {
432                left.write_sql(out, binds);
433                out.push_str(" OR ");
434                right.write_sql(out, binds);
435            }
436            BoolExpr::Not(expr) => {
437                out.push_str("NOT ");
438                expr.write_sql(out, binds);
439            }
440            BoolExpr::Parens(expr) => {
441                out.push('(');
442                expr.write_sql(out, binds);
443                out.push(')');
444            }
445            BoolExpr::Literal(true) => out.push_str("TRUE"),
446            BoolExpr::Literal(false) => out.push_str("FALSE"),
447            BoolExpr::Custom(ext) => ext.write_sql(out, binds),
448        }
449    }
450}
451
452// Display implementation for debugging
453impl fmt::Display for BoolExpr {
454    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
455        let mut sql = String::new();
456        let mut binds = Vec::new();
457        self.write_sql(&mut sql, &mut binds);
458        write!(f, "{} -- binds: {:?}", sql, binds)
459    }
460}
461
462// ===== Helper Functions =====
463
464/// Create a column expression
465pub fn col(name: impl Into<String>) -> ColumnExpr {
466    ColumnExpr::new(name)
467}
468
469/// Create a column with table reference
470pub fn table_col(table: impl Into<String>, name: impl Into<String>) -> ColumnExpr {
471    ColumnExpr::with_table(table, name)
472}
473
474/// Create a literal boolean expression
475pub fn literal(value: bool) -> BoolExpr {
476    BoolExpr::Literal(value)
477}
478
479// ===== Tests =====
480
481#[cfg(test)]
482mod tests {
483    use super::*;
484
485    #[test]
486    fn test_column_operations() {
487        // Test that column operations are only available on ColumnExpr
488        let email = col("email");
489        let age = col("age");
490
491        // These compile - methods exist on ColumnExpr
492        let expr = email.not_null().and(age.gt(18));
493
494        let mut sql = String::new();
495        let mut binds = vec![];
496        expr.write_sql(&mut sql, &mut binds);
497
498        assert_eq!(sql, r#""email" IS NOT NULL AND "age" > ?"#);
499        assert_eq!(binds, vec![BindValue::Int4(18)]);
500    }
501
502    #[test]
503    fn test_complex_expression() {
504        let expr = table_col("users", "email")
505            .not_null()
506            .and(table_col("users", "age").ge(21))
507            .or(table_col("users", "verified").eq(true))
508            .grouped();
509
510        let mut sql = String::new();
511        let mut binds = vec![];
512        expr.write_sql(&mut sql, &mut binds);
513
514        assert_eq!(
515            sql,
516            r#"("users"."email" IS NOT NULL AND "users"."age" >= ? OR "users"."verified" = ?)"#
517        );
518        assert_eq!(binds, vec![BindValue::Int4(21), BindValue::Bool(true)]);
519    }
520
521    #[test]
522    fn test_in_list() {
523        let expr = col("status").is_in(["active", "pending", "approved"]);
524
525        let mut sql = String::new();
526        let mut binds = vec![];
527        expr.write_sql(&mut sql, &mut binds);
528
529        assert_eq!(sql, r#""status" IN (?, ?, ?)"#);
530        assert_eq!(
531            binds,
532            vec![
533                BindValue::Text("active".to_string()),
534                BindValue::Text("pending".to_string()),
535                BindValue::Text("approved".to_string()),
536            ]
537        );
538    }
539
540    #[test]
541    fn test_not_expression() {
542        let expr = col("active").eq(false).not();
543
544        let mut sql = String::new();
545        let mut binds = vec![];
546        expr.write_sql(&mut sql, &mut binds);
547
548        assert_eq!(sql, r#"NOT "active" = ?"#);
549        assert_eq!(binds, vec![BindValue::Bool(false)]);
550    }
551
552    // Test plugin extensibility
553    #[derive(Debug)]
554    struct GeoWithinExpr {
555        geom_col: ColumnExpr,
556        region_wkt: String,
557    }
558
559    impl ExtBoolExpr for GeoWithinExpr {
560        fn write_sql(&self, out: &mut String, binds: &mut Vec<BindValue>) {
561            out.push_str("ST_Within(");
562            self.geom_col.write_sql(out, binds);
563            out.push_str(", ST_GeomFromText(?))");
564            binds.push(BindValue::Text(self.region_wkt.clone()));
565        }
566    }
567
568    fn geo_within(geom_col: ColumnExpr, region_wkt: impl Into<String>) -> BoolExpr {
569        BoolExpr::Custom(Arc::new(GeoWithinExpr {
570            geom_col,
571            region_wkt: region_wkt.into(),
572        }))
573    }
574
575    #[test]
576    fn test_plugin_expression() {
577        let expr = geo_within(col("location"), "POLYGON((0 0, 1 0, 1 1, 0 1, 0 0))")
578            .and(col("active").eq(true));
579
580        let mut sql = String::new();
581        let mut binds = vec![];
582        expr.write_sql(&mut sql, &mut binds);
583
584        assert_eq!(
585            sql,
586            r#"ST_Within("location", ST_GeomFromText(?)) AND "active" = ?"#
587        );
588        assert_eq!(
589            binds,
590            vec![
591                BindValue::Text("POLYGON((0 0, 1 0, 1 1, 0 1, 0 0))".to_string()),
592                BindValue::Bool(true),
593            ]
594        );
595    }
596}