reddb-io-engine 1.26.2

Shared RedDB query execution and storage primitives for native and WebAssembly runtimes.
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
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
//! Filter Predicates for Query Engine
//!
//! Provides filter operations for querying data including comparison,
//! logical, and pattern matching operations.

use super::value_compare::partial_compare_values;
use reddb_types::Value;
use std::fmt;

/// Filter operation type
#[derive(Debug, Clone, PartialEq)]
pub enum FilterOp {
    /// Equal to
    Eq,
    /// Not equal to
    Ne,
    /// Less than
    Lt,
    /// Less than or equal
    Le,
    /// Greater than
    Gt,
    /// Greater than or equal
    Ge,
    /// Between two values (inclusive)
    Between,
    /// In a set of values
    In,
    /// Not in a set of values
    NotIn,
    /// Like pattern matching (SQL-style with % and _)
    Like,
    /// Not like pattern
    NotLike,
    /// Is null
    IsNull,
    /// Is not null
    IsNotNull,
    /// Contains (for text or arrays)
    Contains,
    /// Starts with
    StartsWith,
    /// Ends with
    EndsWith,
}

impl fmt::Display for FilterOp {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            FilterOp::Eq => write!(f, "="),
            FilterOp::Ne => write!(f, "!="),
            FilterOp::Lt => write!(f, "<"),
            FilterOp::Le => write!(f, "<="),
            FilterOp::Gt => write!(f, ">"),
            FilterOp::Ge => write!(f, ">="),
            FilterOp::Between => write!(f, "BETWEEN"),
            FilterOp::In => write!(f, "IN"),
            FilterOp::NotIn => write!(f, "NOT IN"),
            FilterOp::Like => write!(f, "LIKE"),
            FilterOp::NotLike => write!(f, "NOT LIKE"),
            FilterOp::IsNull => write!(f, "IS NULL"),
            FilterOp::IsNotNull => write!(f, "IS NOT NULL"),
            FilterOp::Contains => write!(f, "CONTAINS"),
            FilterOp::StartsWith => write!(f, "STARTS WITH"),
            FilterOp::EndsWith => write!(f, "ENDS WITH"),
        }
    }
}

/// A single predicate condition
#[derive(Debug, Clone)]
pub struct Predicate {
    /// Column name
    pub column: String,
    /// Filter operation
    pub op: FilterOp,
    /// Value(s) to compare against
    pub value: PredicateValue,
}

/// Value type for predicates
#[derive(Debug, Clone)]
pub enum PredicateValue {
    /// Single value
    Single(Value),
    /// Range of values (for BETWEEN)
    Range(Value, Value),
    /// List of values (for IN)
    List(Vec<Value>),
    /// Pattern string (for LIKE)
    Pattern(String),
    /// No value (for IS NULL)
    None,
}

impl Predicate {
    /// Create an equality predicate
    pub fn eq(column: impl Into<String>, value: Value) -> Self {
        Self {
            column: column.into(),
            op: FilterOp::Eq,
            value: PredicateValue::Single(value),
        }
    }

    /// Create a not-equal predicate
    pub fn ne(column: impl Into<String>, value: Value) -> Self {
        Self {
            column: column.into(),
            op: FilterOp::Ne,
            value: PredicateValue::Single(value),
        }
    }

    /// Create a less-than predicate
    pub fn lt(column: impl Into<String>, value: Value) -> Self {
        Self {
            column: column.into(),
            op: FilterOp::Lt,
            value: PredicateValue::Single(value),
        }
    }

    /// Create a less-than-or-equal predicate
    pub fn le(column: impl Into<String>, value: Value) -> Self {
        Self {
            column: column.into(),
            op: FilterOp::Le,
            value: PredicateValue::Single(value),
        }
    }

    /// Create a greater-than predicate
    pub fn gt(column: impl Into<String>, value: Value) -> Self {
        Self {
            column: column.into(),
            op: FilterOp::Gt,
            value: PredicateValue::Single(value),
        }
    }

    /// Create a greater-than-or-equal predicate
    pub fn ge(column: impl Into<String>, value: Value) -> Self {
        Self {
            column: column.into(),
            op: FilterOp::Ge,
            value: PredicateValue::Single(value),
        }
    }

    /// Create a between predicate (inclusive)
    pub fn between(column: impl Into<String>, low: Value, high: Value) -> Self {
        Self {
            column: column.into(),
            op: FilterOp::Between,
            value: PredicateValue::Range(low, high),
        }
    }

    /// Create an IN predicate
    pub fn in_list(column: impl Into<String>, values: Vec<Value>) -> Self {
        Self {
            column: column.into(),
            op: FilterOp::In,
            value: PredicateValue::List(values),
        }
    }

    /// Create a NOT IN predicate
    pub fn not_in(column: impl Into<String>, values: Vec<Value>) -> Self {
        Self {
            column: column.into(),
            op: FilterOp::NotIn,
            value: PredicateValue::List(values),
        }
    }

    /// Create a LIKE predicate
    pub fn like(column: impl Into<String>, pattern: impl Into<String>) -> Self {
        Self {
            column: column.into(),
            op: FilterOp::Like,
            value: PredicateValue::Pattern(pattern.into()),
        }
    }

    /// Create a NOT LIKE predicate
    pub fn not_like(column: impl Into<String>, pattern: impl Into<String>) -> Self {
        Self {
            column: column.into(),
            op: FilterOp::NotLike,
            value: PredicateValue::Pattern(pattern.into()),
        }
    }

    /// Create an IS NULL predicate
    pub fn is_null(column: impl Into<String>) -> Self {
        Self {
            column: column.into(),
            op: FilterOp::IsNull,
            value: PredicateValue::None,
        }
    }

    /// Create an IS NOT NULL predicate
    pub fn is_not_null(column: impl Into<String>) -> Self {
        Self {
            column: column.into(),
            op: FilterOp::IsNotNull,
            value: PredicateValue::None,
        }
    }

    /// Create a CONTAINS predicate
    pub fn contains(column: impl Into<String>, value: Value) -> Self {
        Self {
            column: column.into(),
            op: FilterOp::Contains,
            value: PredicateValue::Single(value),
        }
    }

    /// Create a STARTS WITH predicate
    pub fn starts_with(column: impl Into<String>, prefix: impl Into<String>) -> Self {
        Self {
            column: column.into(),
            op: FilterOp::StartsWith,
            value: PredicateValue::Pattern(prefix.into()),
        }
    }

    /// Create an ENDS WITH predicate
    pub fn ends_with(column: impl Into<String>, suffix: impl Into<String>) -> Self {
        Self {
            column: column.into(),
            op: FilterOp::EndsWith,
            value: PredicateValue::Pattern(suffix.into()),
        }
    }

    /// Evaluate predicate against a value
    pub fn evaluate(&self, column_value: &Value) -> bool {
        match (&self.op, &self.value) {
            (FilterOp::Eq, PredicateValue::Single(v)) => column_value == v,
            (FilterOp::Ne, PredicateValue::Single(v)) => column_value != v,
            (FilterOp::Lt, PredicateValue::Single(v)) => {
                partial_compare_values(column_value, v) == Some(std::cmp::Ordering::Less)
            }
            (FilterOp::Le, PredicateValue::Single(v)) => {
                matches!(
                    partial_compare_values(column_value, v),
                    Some(std::cmp::Ordering::Less | std::cmp::Ordering::Equal)
                )
            }
            (FilterOp::Gt, PredicateValue::Single(v)) => {
                partial_compare_values(column_value, v) == Some(std::cmp::Ordering::Greater)
            }
            (FilterOp::Ge, PredicateValue::Single(v)) => {
                matches!(
                    partial_compare_values(column_value, v),
                    Some(std::cmp::Ordering::Greater | std::cmp::Ordering::Equal)
                )
            }
            (FilterOp::Between, PredicateValue::Range(low, high)) => {
                matches!(
                    partial_compare_values(column_value, low),
                    Some(std::cmp::Ordering::Greater | std::cmp::Ordering::Equal)
                ) && matches!(
                    partial_compare_values(column_value, high),
                    Some(std::cmp::Ordering::Less | std::cmp::Ordering::Equal)
                )
            }
            (FilterOp::In, PredicateValue::List(values)) => values.contains(column_value),
            (FilterOp::NotIn, PredicateValue::List(values)) => !values.contains(column_value),
            (FilterOp::Like, PredicateValue::Pattern(pattern)) => match column_value {
                Value::Text(s) => match_like_pattern(s, pattern),
                _ => false,
            },
            (FilterOp::NotLike, PredicateValue::Pattern(pattern)) => match column_value {
                Value::Text(s) => !match_like_pattern(s, pattern),
                _ => true,
            },
            (FilterOp::IsNull, PredicateValue::None) => matches!(column_value, Value::Null),
            (FilterOp::IsNotNull, PredicateValue::None) => !matches!(column_value, Value::Null),
            (FilterOp::Contains, PredicateValue::Single(v)) => match (column_value, v) {
                (Value::Text(haystack), Value::Text(needle)) => haystack.contains(needle.as_ref()),
                _ => false,
            },
            (FilterOp::StartsWith, PredicateValue::Pattern(prefix)) => match column_value {
                Value::Text(s) => s.starts_with(prefix),
                _ => false,
            },
            (FilterOp::EndsWith, PredicateValue::Pattern(suffix)) => match column_value {
                Value::Text(s) => s.ends_with(suffix),
                _ => false,
            },
            _ => false,
        }
    }
}

/// Match SQL LIKE pattern
///
/// % matches any sequence of characters
/// _ matches any single character
fn match_like_pattern(text: &str, pattern: &str) -> bool {
    let mut text_chars = text.chars().peekable();
    let mut pattern_chars = pattern.chars().peekable();

    match_like_recursive(&mut text_chars, &mut pattern_chars)
}

fn match_like_recursive<I: Iterator<Item = char> + Clone>(
    text: &mut std::iter::Peekable<I>,
    pattern: &mut std::iter::Peekable<I>,
) -> bool {
    loop {
        match (pattern.peek().cloned(), text.peek().cloned()) {
            // Pattern exhausted
            (None, None) => return true,
            (None, Some(_)) => return false,

            // Wildcard %: match zero or more characters
            (Some('%'), _) => {
                pattern.next();
                // Skip consecutive %
                while pattern.peek() == Some(&'%') {
                    pattern.next();
                }
                // If % is at end, match everything
                if pattern.peek().is_none() {
                    return true;
                }
                // Try matching from each position
                loop {
                    let mut text_clone = text.clone();
                    let mut pattern_clone = pattern.clone();
                    if match_like_recursive(&mut text_clone, &mut pattern_clone) {
                        return true;
                    }
                    if text.next().is_none() {
                        return false;
                    }
                }
            }

            // Single char wildcard _
            (Some('_'), Some(_)) => {
                pattern.next();
                text.next();
            }
            (Some('_'), None) => return false,

            // Literal match
            (Some(p), Some(t)) => {
                if p.to_lowercase().next() == t.to_lowercase().next() {
                    pattern.next();
                    text.next();
                } else {
                    return false;
                }
            }

            // Pattern has more but text exhausted
            (Some(_), None) => return false,
        }
    }
}

/// Composite filter with logical operations
#[derive(Debug, Clone)]
pub enum Filter {
    /// Single predicate
    Predicate(Predicate),
    /// Logical AND of filters
    And(Vec<Filter>),
    /// Logical OR of filters
    Or(Vec<Filter>),
    /// Logical NOT of filter
    Not(Box<Filter>),
}

impl Filter {
    /// Create filter from predicate
    pub fn from_predicate(predicate: Predicate) -> Self {
        Filter::Predicate(predicate)
    }

    /// Create equality filter
    pub fn eq(column: impl Into<String>, value: Value) -> Self {
        Filter::Predicate(Predicate::eq(column, value))
    }

    /// Create not-equal filter
    pub fn ne(column: impl Into<String>, value: Value) -> Self {
        Filter::Predicate(Predicate::ne(column, value))
    }

    /// Create less-than filter
    pub fn lt(column: impl Into<String>, value: Value) -> Self {
        Filter::Predicate(Predicate::lt(column, value))
    }

    /// Create less-than-or-equal filter
    pub fn le(column: impl Into<String>, value: Value) -> Self {
        Filter::Predicate(Predicate::le(column, value))
    }

    /// Create greater-than filter
    pub fn gt(column: impl Into<String>, value: Value) -> Self {
        Filter::Predicate(Predicate::gt(column, value))
    }

    /// Create greater-than-or-equal filter
    pub fn ge(column: impl Into<String>, value: Value) -> Self {
        Filter::Predicate(Predicate::ge(column, value))
    }

    /// Create between filter
    pub fn between(column: impl Into<String>, low: Value, high: Value) -> Self {
        Filter::Predicate(Predicate::between(column, low, high))
    }

    /// Create IN filter
    pub fn in_list(column: impl Into<String>, values: Vec<Value>) -> Self {
        Filter::Predicate(Predicate::in_list(column, values))
    }

    /// Create LIKE filter
    pub fn like(column: impl Into<String>, pattern: impl Into<String>) -> Self {
        Filter::Predicate(Predicate::like(column, pattern))
    }

    /// Create IS NULL filter
    pub fn is_null(column: impl Into<String>) -> Self {
        Filter::Predicate(Predicate::is_null(column))
    }

    /// Create IS NOT NULL filter
    pub fn is_not_null(column: impl Into<String>) -> Self {
        Filter::Predicate(Predicate::is_not_null(column))
    }

    /// Create AND filter
    pub fn and(filters: Vec<Filter>) -> Self {
        Filter::And(filters)
    }

    /// Create OR filter
    pub fn or(filters: Vec<Filter>) -> Self {
        Filter::Or(filters)
    }

    /// Create NOT filter
    pub fn not(filter: Filter) -> Self {
        Filter::Not(Box::new(filter))
    }

    /// Combine with another filter using AND
    pub fn and_filter(self, other: Filter) -> Self {
        match self {
            Filter::And(mut filters) => {
                filters.push(other);
                Filter::And(filters)
            }
            _ => Filter::And(vec![self, other]),
        }
    }

    /// Combine with another filter using OR
    pub fn or_filter(self, other: Filter) -> Self {
        match self {
            Filter::Or(mut filters) => {
                filters.push(other);
                Filter::Or(filters)
            }
            _ => Filter::Or(vec![self, other]),
        }
    }

    /// Evaluate filter against a row (column name -> value map)
    pub fn evaluate(&self, get_value: &impl Fn(&str) -> Option<Value>) -> bool {
        match self {
            Filter::Predicate(pred) => {
                if let Some(value) = get_value(&pred.column) {
                    pred.evaluate(&value)
                } else {
                    // Column not found - treat as NULL
                    matches!(pred.op, FilterOp::IsNull)
                }
            }
            Filter::And(filters) => filters.iter().all(|f| f.evaluate(get_value)),
            Filter::Or(filters) => filters.iter().any(|f| f.evaluate(get_value)),
            Filter::Not(filter) => !filter.evaluate(get_value),
        }
    }

    /// Check if filter references a specific column
    pub fn references_column(&self, column: &str) -> bool {
        match self {
            Filter::Predicate(pred) => pred.column == column,
            Filter::And(filters) | Filter::Or(filters) => {
                filters.iter().any(|f| f.references_column(column))
            }
            Filter::Not(filter) => filter.references_column(column),
        }
    }

    /// Get all referenced columns
    pub fn referenced_columns(&self) -> Vec<&str> {
        let mut columns = Vec::new();
        self.collect_columns(&mut columns);
        columns
    }

    fn collect_columns<'a>(&'a self, columns: &mut Vec<&'a str>) {
        match self {
            Filter::Predicate(pred) => {
                if !columns.contains(&pred.column.as_str()) {
                    columns.push(&pred.column);
                }
            }
            Filter::And(filters) | Filter::Or(filters) => {
                for f in filters {
                    f.collect_columns(columns);
                }
            }
            Filter::Not(filter) => filter.collect_columns(columns),
        }
    }
}

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

    fn make_row() -> impl Fn(&str) -> Option<Value> {
        |col: &str| -> Option<Value> {
            match col {
                "name" => Some(Value::text("Alice".to_string())),
                "age" => Some(Value::Integer(25)),
                "score" => Some(Value::Float(95.5)),
                "active" => Some(Value::Boolean(true)),
                "email" => Some(Value::text("alice@example.com".to_string())),
                "nullable" => Some(Value::Null),
                _ => None,
            }
        }
    }

    #[test]
    fn test_predicate_eq() {
        let pred = Predicate::eq("name", Value::text("Alice".to_string()));
        assert!(pred.evaluate(&Value::text("Alice".to_string())));
        assert!(!pred.evaluate(&Value::text("Bob".to_string())));
    }

    #[test]
    fn test_predicate_ne() {
        let pred = Predicate::ne("name", Value::text("Bob".to_string()));
        assert!(pred.evaluate(&Value::text("Alice".to_string())));
        assert!(!pred.evaluate(&Value::text("Bob".to_string())));
    }

    #[test]
    fn test_predicate_lt() {
        let pred = Predicate::lt("age", Value::Integer(30));
        assert!(pred.evaluate(&Value::Integer(25)));
        assert!(!pred.evaluate(&Value::Integer(30)));
        assert!(!pred.evaluate(&Value::Integer(35)));
    }

    #[test]
    fn test_predicate_le() {
        let pred = Predicate::le("age", Value::Integer(30));
        assert!(pred.evaluate(&Value::Integer(25)));
        assert!(pred.evaluate(&Value::Integer(30)));
        assert!(!pred.evaluate(&Value::Integer(35)));
    }

    #[test]
    fn test_predicate_gt() {
        let pred = Predicate::gt("age", Value::Integer(20));
        assert!(pred.evaluate(&Value::Integer(25)));
        assert!(!pred.evaluate(&Value::Integer(20)));
        assert!(!pred.evaluate(&Value::Integer(15)));
    }

    #[test]
    fn test_predicate_ge() {
        let pred = Predicate::ge("age", Value::Integer(20));
        assert!(pred.evaluate(&Value::Integer(25)));
        assert!(pred.evaluate(&Value::Integer(20)));
        assert!(!pred.evaluate(&Value::Integer(15)));
    }

    #[test]
    fn test_predicate_between() {
        let pred = Predicate::between("age", Value::Integer(20), Value::Integer(30));
        assert!(pred.evaluate(&Value::Integer(25)));
        assert!(pred.evaluate(&Value::Integer(20)));
        assert!(pred.evaluate(&Value::Integer(30)));
        assert!(!pred.evaluate(&Value::Integer(19)));
        assert!(!pred.evaluate(&Value::Integer(31)));
    }

    #[test]
    fn test_predicate_in() {
        let pred = Predicate::in_list(
            "name",
            vec![
                Value::text("Alice".to_string()),
                Value::text("Bob".to_string()),
            ],
        );
        assert!(pred.evaluate(&Value::text("Alice".to_string())));
        assert!(pred.evaluate(&Value::text("Bob".to_string())));
        assert!(!pred.evaluate(&Value::text("Charlie".to_string())));
    }

    #[test]
    fn test_predicate_not_in() {
        let pred = Predicate::not_in("name", vec![Value::text("Alice".to_string())]);
        assert!(!pred.evaluate(&Value::text("Alice".to_string())));
        assert!(pred.evaluate(&Value::text("Bob".to_string())));
    }

    #[test]
    fn test_predicate_like() {
        // % matches any sequence
        let pred = Predicate::like("email", "%@example.com");
        assert!(pred.evaluate(&Value::text("alice@example.com".to_string())));
        assert!(pred.evaluate(&Value::text("bob@example.com".to_string())));
        assert!(!pred.evaluate(&Value::text("alice@gmail.com".to_string())));

        // _ matches single char
        let pred2 = Predicate::like("name", "A_ice");
        assert!(pred2.evaluate(&Value::text("Alice".to_string())));
        assert!(!pred2.evaluate(&Value::text("Alicia".to_string())));

        // Combined
        let pred3 = Predicate::like("email", "a%@%.com");
        assert!(pred3.evaluate(&Value::text("alice@example.com".to_string())));
    }

    #[test]
    fn test_predicate_is_null() {
        let pred = Predicate::is_null("nullable");
        assert!(pred.evaluate(&Value::Null));
        assert!(!pred.evaluate(&Value::Integer(0)));
    }

    #[test]
    fn test_predicate_is_not_null() {
        let pred = Predicate::is_not_null("name");
        assert!(pred.evaluate(&Value::text("Alice".to_string())));
        assert!(!pred.evaluate(&Value::Null));
    }

    #[test]
    fn test_predicate_contains() {
        let pred = Predicate::contains("email", Value::text("@example".to_string()));
        assert!(pred.evaluate(&Value::text("alice@example.com".to_string())));
        assert!(!pred.evaluate(&Value::text("alice@gmail.com".to_string())));
    }

    #[test]
    fn test_predicate_starts_with() {
        let pred = Predicate::starts_with("name", "Al");
        assert!(pred.evaluate(&Value::text("Alice".to_string())));
        assert!(pred.evaluate(&Value::text("Albert".to_string())));
        assert!(!pred.evaluate(&Value::text("Bob".to_string())));
    }

    #[test]
    fn test_predicate_ends_with() {
        let pred = Predicate::ends_with("email", ".com");
        assert!(pred.evaluate(&Value::text("alice@example.com".to_string())));
        assert!(!pred.evaluate(&Value::text("alice@example.org".to_string())));
    }

    #[test]
    fn test_filter_evaluate() {
        let row = make_row();

        // Simple equality
        let filter = Filter::eq("name", Value::text("Alice".to_string()));
        assert!(filter.evaluate(&row));

        // Comparison
        let filter = Filter::gt("age", Value::Integer(20));
        assert!(filter.evaluate(&row));
    }

    #[test]
    fn test_filter_and() {
        let row = make_row();

        let filter = Filter::and(vec![
            Filter::eq("name", Value::text("Alice".to_string())),
            Filter::gt("age", Value::Integer(20)),
        ]);
        assert!(filter.evaluate(&row));

        let filter = Filter::and(vec![
            Filter::eq("name", Value::text("Alice".to_string())),
            Filter::gt("age", Value::Integer(30)), // Alice is 25, fails
        ]);
        assert!(!filter.evaluate(&row));
    }

    #[test]
    fn test_filter_or() {
        let row = make_row();

        let filter = Filter::or(vec![
            Filter::eq("name", Value::text("Bob".to_string())), // Fails
            Filter::gt("age", Value::Integer(20)),              // Passes
        ]);
        assert!(filter.evaluate(&row));

        let filter = Filter::or(vec![
            Filter::eq("name", Value::text("Bob".to_string())),
            Filter::lt("age", Value::Integer(20)),
        ]);
        assert!(!filter.evaluate(&row));
    }

    #[test]
    fn test_filter_not() {
        let row = make_row();

        let filter = Filter::not(Filter::eq("name", Value::text("Bob".to_string())));
        assert!(filter.evaluate(&row)); // Alice != Bob

        let filter = Filter::not(Filter::eq("name", Value::text("Alice".to_string())));
        assert!(!filter.evaluate(&row));
    }

    #[test]
    fn test_filter_chain() {
        let row = make_row();

        let filter = Filter::eq("name", Value::text("Alice".to_string()))
            .and_filter(Filter::gt("age", Value::Integer(20)))
            .and_filter(Filter::lt("age", Value::Integer(30)));

        assert!(filter.evaluate(&row));
    }

    #[test]
    fn test_filter_referenced_columns() {
        let filter = Filter::and(vec![
            Filter::eq("name", Value::text("Alice".to_string())),
            Filter::or(vec![
                Filter::gt("age", Value::Integer(20)),
                Filter::lt("score", Value::Float(100.0)),
            ]),
        ]);

        let columns = filter.referenced_columns();
        assert!(columns.contains(&"name"));
        assert!(columns.contains(&"age"));
        assert!(columns.contains(&"score"));
        assert_eq!(columns.len(), 3);
    }

    #[test]
    fn test_cross_type_comparison() {
        // Integer vs Float
        let pred = Predicate::lt("value", Value::Float(30.5));
        assert!(pred.evaluate(&Value::Integer(30)));
        assert!(!pred.evaluate(&Value::Integer(31)));
    }

    #[test]
    fn test_like_edge_cases() {
        // Empty pattern
        let pred = Predicate::like("text", "");
        assert!(pred.evaluate(&Value::text("".to_string())));
        assert!(!pred.evaluate(&Value::text("a".to_string())));

        // Only %
        let pred = Predicate::like("text", "%");
        assert!(pred.evaluate(&Value::text("anything".to_string())));
        assert!(pred.evaluate(&Value::text("".to_string())));

        // Multiple %
        let pred = Predicate::like("text", "a%b%c");
        assert!(pred.evaluate(&Value::text("abc".to_string())));
        assert!(pred.evaluate(&Value::text("aXXbYYc".to_string())));
        assert!(!pred.evaluate(&Value::text("ab".to_string())));
    }
}