audb-codegen 0.1.11

Code generation for AuDB compile-time database applications
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
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
//! Query Pattern Matcher
//!
//! Analyzes HyperQL AST to classify queries into optimization patterns.
//! Each pattern corresponds to a specific code generation strategy.

use crate::hyperql::{CompilerError, CompilerResult};
use audb::model::Query;
use hyperQL::ast::{Expression, SelectStatement, Statement};

/// Recognized query patterns for optimization
#[derive(Debug, Clone, PartialEq)]
pub enum QueryPattern {
    /// Point query: SELECT * WHERE id = :param
    PointQuery { table: String, id_param: String },

    /// Simple filter: SELECT * WHERE conditions
    FilterQuery {
        table: String,
        filters: Vec<FilterCondition>,
    },

    /// Projection: SELECT field1, field2 WHERE conditions
    ProjectionQuery {
        table: String,
        fields: Vec<String>,
        filters: Vec<FilterCondition>,
    },

    /// Ordered query: ORDER BY field [LIMIT n]
    OrderedQuery {
        table: String,
        filters: Vec<FilterCondition>,
        order_by: Vec<OrderByClause>,
        limit: Option<u64>,
        offset: Option<u64>,
    },

    /// Relationship traversal: TRAVERSE clause
    RelationshipQuery {
        table: String,
        traverse: TraverseInfo,
        filters: Vec<FilterCondition>,
    },

    /// Aggregation: COUNT, SUM, AVG, etc.
    AggregationQuery {
        table: String,
        aggregates: Vec<AggregateFunction>,
        filters: Vec<FilterCondition>,
        group_by: Vec<String>,
    },

    /// Complex query that doesn't fit other patterns
    ComplexQuery { ast: Box<SelectStatement> },
}

/// Filter condition extracted from WHERE clause
#[derive(Debug, Clone, PartialEq)]
pub struct FilterCondition {
    pub field: String,
    pub operator: FilterOperator,
    pub value: FilterValue,
}

/// Filter operators
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FilterOperator {
    Equal,
    NotEqual,
    LessThan,
    LessThanOrEqual,
    GreaterThan,
    GreaterThanOrEqual,
    Like,
    In,
}

/// Filter value (parameter or literal)
#[derive(Debug, Clone, PartialEq)]
pub enum FilterValue {
    Parameter(String),
    Literal(LiteralValue),
}

/// Literal values in filters
#[derive(Debug, Clone, PartialEq)]
pub enum LiteralValue {
    String(String),
    Integer(i64),
    Float(f64),
    Boolean(bool),
    Null,
}

/// ORDER BY clause
#[derive(Debug, Clone, PartialEq)]
pub struct OrderByClause {
    pub field: String,
    pub descending: bool,
}

/// TRAVERSE information
#[derive(Debug, Clone, PartialEq)]
pub struct TraverseInfo {
    pub relationship: String,
    pub target_table: String,
}

/// Aggregate function
#[derive(Debug, Clone, PartialEq)]
pub enum AggregateFunction {
    Count,
    Sum(String),
    Avg(String),
    Min(String),
    Max(String),
}

/// Pattern matcher for query analysis
pub struct PatternMatcher;

impl PatternMatcher {
    /// Create a new pattern matcher
    pub fn new() -> Self {
        Self
    }

    /// Analyze HyperQL AST and classify into a pattern
    pub fn analyze(&self, ast: &Statement, query: &Query) -> CompilerResult<QueryPattern> {
        match ast {
            Statement::Select(select) => self.analyze_select(select, query),
            _ => Err(CompilerError::UnsupportedPattern(
                "Only SELECT queries are currently supported".to_string(),
            )),
        }
    }

    /// Analyze SELECT statement
    fn analyze_select(
        &self,
        select: &SelectStatement,
        query: &Query,
    ) -> CompilerResult<QueryPattern> {
        // Extract table name
        let table = self.extract_table_name(select)?;

        // Check for point query pattern first (most specific)
        if let Some(pattern) = self.match_point_query(select, &table, query)? {
            return Ok(pattern);
        }

        // Check for aggregation
        if self.has_aggregates(select) {
            return self.match_aggregation_query(select, &table);
        }

        // Check for relationship traversal
        if select.traverse_clause.is_some() {
            return self.match_relationship_query(select, &table);
        }

        // Check for ordering
        if !select.order_by.is_empty() || select.limit.is_some() {
            return self.match_ordered_query(select, &table);
        }

        // Check for projection
        if !self.is_select_star(select) {
            return self.match_projection_query(select, &table);
        }

        // Default to filter query
        self.match_filter_query(select, &table)
    }

    /// Extract table name from FROM clause
    fn extract_table_name(&self, select: &SelectStatement) -> CompilerResult<String> {
        match &select.from {
            Some(from_clause) => match from_clause {
                hyperQL::ast::FromClause::Table {
                    collection,
                    entity_type: _,
                    alias: _,
                } => Ok(collection.clone()),
                hyperQL::ast::FromClause::Subquery { .. } => {
                    Err(CompilerError::UnsupportedPattern(
                        "Subqueries are not yet supported".to_string(),
                    ))
                }
            },
            None => Err(CompilerError::UnsupportedPattern(
                "SELECT without FROM clause not supported".to_string(),
            )),
        }
    }

    /// Match point query pattern: SELECT * WHERE id = :param
    fn match_point_query(
        &self,
        select: &SelectStatement,
        table: &str,
        query: &Query,
    ) -> CompilerResult<Option<QueryPattern>> {
        // Must be SELECT *
        if !self.is_select_star(select) {
            return Ok(None);
        }

        // Must have WHERE clause
        let where_clause = match &select.where_clause {
            Some(expr) => expr,
            None => return Ok(None),
        };

        // Must have no ORDER BY, GROUP BY, LIMIT, OFFSET, etc.
        if !select.order_by.is_empty()
            || select.limit.is_some()
            || select.offset.is_some()
            || !select.group_by.is_empty()
            || select.having.is_some()
            || !select.joins.is_empty()
            || select.traverse_clause.is_some()
        {
            return Ok(None);
        }

        // Check if it's a simple id = value expression
        if self.is_id_equality(where_clause) {
            // For point queries, use the first parameter (should be the id parameter)
            if let Some(param) = query.params.first() {
                return Ok(Some(QueryPattern::PointQuery {
                    table: table.to_string(),
                    id_param: param.name.clone(),
                }));
            }
        }

        Ok(None)
    }

    /// Check if expression is `id = :param` or similar simple equality
    /// Returns true if this is a point query pattern (id equality)
    fn is_id_equality(&self, expr: &Expression) -> bool {
        match expr {
            Expression::Binary { left, op, right: _ } => {
                // Check if operator is Equal
                if !matches!(op, hyperQL::ast::BinaryOperator::Equal) {
                    return false;
                }

                // Check if left side is column reference to "id"
                matches!(
                    left.as_ref(),
                    Expression::Column(col_ref) if col_ref.name == "id"
                )
            }
            _ => false,
        }
    }

    /// Match filter query pattern
    fn match_filter_query(
        &self,
        select: &SelectStatement,
        table: &str,
    ) -> CompilerResult<QueryPattern> {
        let filters = match &select.where_clause {
            Some(expr) => self.extract_filters(expr)?,
            None => Vec::new(),
        };

        Ok(QueryPattern::FilterQuery {
            table: table.to_string(),
            filters,
        })
    }

    /// Match projection query pattern
    fn match_projection_query(
        &self,
        select: &SelectStatement,
        table: &str,
    ) -> CompilerResult<QueryPattern> {
        let fields = self.extract_projection_fields(select)?;
        let filters = match &select.where_clause {
            Some(expr) => self.extract_filters(expr)?,
            None => Vec::new(),
        };

        Ok(QueryPattern::ProjectionQuery {
            table: table.to_string(),
            fields,
            filters,
        })
    }

    /// Match ordered query pattern
    fn match_ordered_query(
        &self,
        select: &SelectStatement,
        table: &str,
    ) -> CompilerResult<QueryPattern> {
        let filters = match &select.where_clause {
            Some(expr) => self.extract_filters(expr)?,
            None => Vec::new(),
        };

        let order_by = self.extract_order_by(&select.order_by)?;

        Ok(QueryPattern::OrderedQuery {
            table: table.to_string(),
            filters,
            order_by,
            limit: select.limit,
            offset: select.offset,
        })
    }

    /// Match relationship query pattern
    fn match_relationship_query(
        &self,
        select: &SelectStatement,
        table: &str,
    ) -> CompilerResult<QueryPattern> {
        let traverse = match &select.traverse_clause {
            Some(clause) => self.extract_traverse_info(clause)?,
            None => {
                return Err(CompilerError::CodeGenError(
                    "Expected TRAVERSE clause".to_string(),
                ));
            }
        };

        let filters = match &select.where_clause {
            Some(expr) => self.extract_filters(expr)?,
            None => Vec::new(),
        };

        Ok(QueryPattern::RelationshipQuery {
            table: table.to_string(),
            traverse,
            filters,
        })
    }

    /// Match aggregation query pattern
    fn match_aggregation_query(
        &self,
        select: &SelectStatement,
        table: &str,
    ) -> CompilerResult<QueryPattern> {
        let aggregates = self.extract_aggregates(select)?;
        let filters = match &select.where_clause {
            Some(expr) => self.extract_filters(expr)?,
            None => Vec::new(),
        };
        let group_by = self.extract_group_by(&select.group_by)?;

        Ok(QueryPattern::AggregationQuery {
            table: table.to_string(),
            aggregates,
            filters,
            group_by,
        })
    }

    /// Check if SELECT * is used
    fn is_select_star(&self, select: &SelectStatement) -> bool {
        select.select_list.len() == 1
            && matches!(select.select_list[0], hyperQL::ast::SelectItem::Wildcard)
    }

    /// Check if query has aggregate functions
    fn has_aggregates(&self, select: &SelectStatement) -> bool {
        for item in &select.select_list {
            if let hyperQL::ast::SelectItem::Expression { expr, .. } = item {
                if self.is_aggregate_expr(expr) {
                    return true;
                }
            }
        }
        false
    }

    /// Check if expression is an aggregate function
    fn is_aggregate_expr(&self, expr: &Expression) -> bool {
        matches!(
            expr,
            Expression::Function { name, .. }
            if matches!(name.to_uppercase().as_str(), "COUNT" | "SUM" | "AVG" | "MIN" | "MAX")
        )
    }

    /// Extract filters from WHERE clause
    fn extract_filters(&self, expr: &Expression) -> CompilerResult<Vec<FilterCondition>> {
        let mut filters = Vec::new();
        self.extract_filters_recursive(expr, &mut filters)?;
        Ok(filters)
    }

    /// Recursively extract filters from expression tree
    fn extract_filters_recursive(
        &self,
        expr: &Expression,
        filters: &mut Vec<FilterCondition>,
    ) -> CompilerResult<()> {
        match expr {
            Expression::Binary { left, op, right } => {
                // Check if this is a logical operator (AND/OR)
                match op {
                    hyperQL::ast::BinaryOperator::And | hyperQL::ast::BinaryOperator::Or => {
                        // Recursively process both sides
                        self.extract_filters_recursive(left, filters)?;
                        self.extract_filters_recursive(right, filters)?;
                    }
                    _ => {
                        // This is a comparison operator - extract the condition
                        let filter = self.extract_single_filter(left, op, right)?;
                        filters.push(filter);
                    }
                }
            }
            Expression::Unary { op, expr } => {
                // Handle NOT operator
                if matches!(op, hyperQL::ast::UnaryOperator::Not) {
                    // For now, we'll extract the inner expression
                    // TODO: Properly handle negation in filter compilation
                    self.extract_filters_recursive(expr, filters)?;
                }
            }
            _ => {
                // Other expression types - might be valid in some contexts
                // For now, we'll skip them
            }
        }
        Ok(())
    }

    /// Extract a single filter condition from a comparison expression
    fn extract_single_filter(
        &self,
        left: &Expression,
        op: &hyperQL::ast::BinaryOperator,
        right: &Expression,
    ) -> CompilerResult<FilterCondition> {
        // Extract field name from left side (should be a column reference)
        let field = match left {
            Expression::Column(col_ref) => col_ref.name.clone(),
            _ => {
                return Err(CompilerError::InvalidFilter(
                    "Left side of comparison must be a column reference".to_string(),
                ));
            }
        };

        // Convert operator
        let operator = self.convert_binary_operator(op)?;

        // Extract value from right side
        let value = self.extract_filter_value(right)?;

        Ok(FilterCondition {
            field,
            operator,
            value,
        })
    }

    /// Convert HyperQL binary operator to filter operator
    fn convert_binary_operator(
        &self,
        op: &hyperQL::ast::BinaryOperator,
    ) -> CompilerResult<FilterOperator> {
        match op {
            hyperQL::ast::BinaryOperator::Equal => Ok(FilterOperator::Equal),
            hyperQL::ast::BinaryOperator::NotEqual => Ok(FilterOperator::NotEqual),
            hyperQL::ast::BinaryOperator::LessThan => Ok(FilterOperator::LessThan),
            hyperQL::ast::BinaryOperator::LessThanOrEqual => Ok(FilterOperator::LessThanOrEqual),
            hyperQL::ast::BinaryOperator::GreaterThan => Ok(FilterOperator::GreaterThan),
            hyperQL::ast::BinaryOperator::GreaterThanOrEqual => {
                Ok(FilterOperator::GreaterThanOrEqual)
            }
            hyperQL::ast::BinaryOperator::Like => Ok(FilterOperator::Like),
            hyperQL::ast::BinaryOperator::In => Ok(FilterOperator::In),
            _ => Err(CompilerError::InvalidFilter(format!(
                "Unsupported operator in filter: {:?}",
                op
            ))),
        }
    }

    /// Extract filter value from expression
    fn extract_filter_value(&self, expr: &Expression) -> CompilerResult<FilterValue> {
        match expr {
            Expression::Literal(lit) => {
                let literal = self.convert_literal(lit);
                Ok(FilterValue::Literal(literal))
            }
            Expression::Column(col_ref) => {
                // This is a parameter reference (e.g., :min_age)
                // In our context, column references on the right side are parameters
                Ok(FilterValue::Parameter(col_ref.name.clone()))
            }
            _ => Err(CompilerError::InvalidFilter(
                "Filter value must be a literal or parameter".to_string(),
            )),
        }
    }

    /// Convert HyperQL literal to filter literal value
    fn convert_literal(&self, lit: &hyperQL::ast::Literal) -> LiteralValue {
        match lit {
            hyperQL::ast::Literal::Null => LiteralValue::Null,
            hyperQL::ast::Literal::Bool(b) => LiteralValue::Boolean(*b),
            hyperQL::ast::Literal::Int(i) => LiteralValue::Integer(*i),
            hyperQL::ast::Literal::Float(f) => LiteralValue::Float(*f),
            hyperQL::ast::Literal::String(s) => LiteralValue::String(s.clone()),
            hyperQL::ast::Literal::EntityId(_) => {
                // For now, treat EntityId as string
                // TODO: Properly handle EntityId type
                LiteralValue::String("entity_id".to_string())
            }
        }
    }

    /// Extract projection fields from SELECT list
    fn extract_projection_fields(&self, select: &SelectStatement) -> CompilerResult<Vec<String>> {
        let mut fields = Vec::new();

        for item in &select.select_list {
            match item {
                hyperQL::ast::SelectItem::Wildcard => {
                    return Err(CompilerError::CodeGenError(
                        "Cannot mix wildcard with specific fields".to_string(),
                    ));
                }
                hyperQL::ast::SelectItem::Expression { expr, alias } => {
                    // Use alias if present, otherwise try to extract field name
                    let field_name = if let Some(name) = alias {
                        name.clone()
                    } else if let Expression::Column(col_ref) = expr {
                        col_ref.name.clone()
                    } else {
                        return Err(CompilerError::CodeGenError(
                            "Complex expressions in SELECT require aliases".to_string(),
                        ));
                    };
                    fields.push(field_name);
                }
            }
        }

        Ok(fields)
    }

    /// Extract ORDER BY clauses
    fn extract_order_by(
        &self,
        order_items: &[hyperQL::ast::OrderByItem],
    ) -> CompilerResult<Vec<OrderByClause>> {
        let mut clauses = Vec::new();

        for item in order_items {
            // Extract field name from expression
            let field = if let Expression::Column(col_ref) = &item.expr {
                col_ref.name.clone()
            } else {
                return Err(CompilerError::CodeGenError(
                    "Complex ORDER BY expressions not yet supported".to_string(),
                ));
            };

            let descending = matches!(item.direction, hyperQL::ast::OrderDirection::Desc);

            clauses.push(OrderByClause { field, descending });
        }

        Ok(clauses)
    }

    /// Extract TRAVERSE information
    fn extract_traverse_info(
        &self,
        clause: &hyperQL::ast::TraverseClause,
    ) -> CompilerResult<TraverseInfo> {
        // For now, support simple single-pattern TRAVERSE
        if clause.patterns.is_empty() {
            return Err(CompilerError::UnsupportedPattern(
                "TRAVERSE clause must have at least one pattern".to_string(),
            ));
        }

        // Take the first pattern
        let pattern = &clause.patterns[0];

        // Extract relationship type (edge type)
        let relationship = pattern.relationship.rel_type.clone().ok_or_else(|| {
            CompilerError::UnsupportedPattern("TRAVERSE relationship must have a type".to_string())
        })?;

        // Extract target node label (target table)
        let target_table = pattern.end_node.label.clone().ok_or_else(|| {
            CompilerError::UnsupportedPattern("TRAVERSE target node must have a label".to_string())
        })?;

        Ok(TraverseInfo {
            relationship,
            target_table,
        })
    }

    /// Extract aggregate functions
    fn extract_aggregates(
        &self,
        select: &SelectStatement,
    ) -> CompilerResult<Vec<AggregateFunction>> {
        let mut aggregates = Vec::new();

        for item in &select.select_list {
            if let hyperQL::ast::SelectItem::Expression { expr, .. } = item {
                if let Some(agg) = self.extract_aggregate_function(expr)? {
                    aggregates.push(agg);
                }
            }
        }

        Ok(aggregates)
    }

    /// Extract a single aggregate function from expression
    fn extract_aggregate_function(
        &self,
        expr: &Expression,
    ) -> CompilerResult<Option<AggregateFunction>> {
        match expr {
            Expression::Function { name, args } => match name.to_uppercase().as_str() {
                "COUNT" => Ok(Some(AggregateFunction::Count)),
                "SUM" => {
                    let field = self.extract_field_from_args(args)?;
                    Ok(Some(AggregateFunction::Sum(field)))
                }
                "AVG" => {
                    let field = self.extract_field_from_args(args)?;
                    Ok(Some(AggregateFunction::Avg(field)))
                }
                "MIN" => {
                    let field = self.extract_field_from_args(args)?;
                    Ok(Some(AggregateFunction::Min(field)))
                }
                "MAX" => {
                    let field = self.extract_field_from_args(args)?;
                    Ok(Some(AggregateFunction::Max(field)))
                }
                _ => Ok(None),
            },
            _ => Ok(None),
        }
    }

    /// Extract field name from function arguments
    fn extract_field_from_args(&self, args: &[Expression]) -> CompilerResult<String> {
        if args.is_empty() {
            return Err(CompilerError::CodeGenError(
                "Aggregate function requires arguments".to_string(),
            ));
        }

        match &args[0] {
            Expression::Column(col_ref) => Ok(col_ref.name.clone()),
            _ => Err(CompilerError::CodeGenError(
                "Aggregate function argument must be a column reference".to_string(),
            )),
        }
    }

    /// Extract GROUP BY fields
    fn extract_group_by(&self, group_exprs: &[Expression]) -> CompilerResult<Vec<String>> {
        let mut fields = Vec::new();

        for expr in group_exprs {
            match expr {
                Expression::Column(col_ref) => fields.push(col_ref.name.clone()),
                _ => {
                    return Err(CompilerError::CodeGenError(
                        "Complex GROUP BY expressions not yet supported".to_string(),
                    ));
                }
            }
        }

        Ok(fields)
    }
}

impl Default for PatternMatcher {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[test]
    fn test_pattern_matcher_creation() {
        let matcher = PatternMatcher::new();
        assert!(true); // Matcher creates successfully
    }

    #[test]
    fn test_is_select_star() {
        let matcher = PatternMatcher::new();

        let select = SelectStatement {
            select_list: vec![hyperQL::ast::SelectItem::Wildcard],
            from: None,
            joins: Vec::new(),
            traverse_clause: None,
            where_clause: None,
            group_by: Vec::new(),
            having: None,
            order_by: Vec::new(),
            limit: None,
            offset: None,
            distinct: false,
        };

        assert!(matcher.is_select_star(&select));
    }

    #[test]
    fn test_extract_single_filter() {
        use hyperQL::ast::{BinaryOperator, ColumnRef, Expression, Literal};

        let matcher = PatternMatcher::new();

        // Create: age > 25
        let left = Expression::Column(ColumnRef {
            table: None,
            name: "age".to_string(),
        });
        let op = BinaryOperator::GreaterThan;
        let right = Expression::Literal(Literal::Int(25));

        let result = matcher.extract_single_filter(&left, &op, &right);
        assert!(result.is_ok(), "Failed to extract filter: {:?}", result);

        let filter = result.unwrap();
        assert_eq!(filter.field, "age");
        assert_eq!(filter.operator, FilterOperator::GreaterThan);
        assert!(matches!(filter.value, FilterValue::Literal(_)));
    }

    #[test]
    fn test_extract_filters_from_and_expression() {
        use hyperQL::ast::{BinaryOperator, ColumnRef, Expression, Literal};

        let matcher = PatternMatcher::new();

        // Create: age > 25 AND active = true
        let age_filter = Expression::Binary {
            left: Box::new(Expression::Column(ColumnRef {
                table: None,
                name: "age".to_string(),
            })),
            op: BinaryOperator::GreaterThan,
            right: Box::new(Expression::Literal(Literal::Int(25))),
        };

        let active_filter = Expression::Binary {
            left: Box::new(Expression::Column(ColumnRef {
                table: None,
                name: "active".to_string(),
            })),
            op: BinaryOperator::Equal,
            right: Box::new(Expression::Literal(Literal::Bool(true))),
        };

        let combined = Expression::Binary {
            left: Box::new(age_filter),
            op: BinaryOperator::And,
            right: Box::new(active_filter),
        };

        let result = matcher.extract_filters(&combined);
        assert!(result.is_ok(), "Failed to extract filters: {:?}", result);

        let filters = result.unwrap();
        assert_eq!(filters.len(), 2, "Expected 2 filters");
        assert_eq!(filters[0].field, "age");
        assert_eq!(filters[1].field, "active");
    }

    #[test]
    fn test_convert_binary_operator() {
        let matcher = PatternMatcher::new();

        let test_cases = vec![
            (hyperQL::ast::BinaryOperator::Equal, FilterOperator::Equal),
            (
                hyperQL::ast::BinaryOperator::NotEqual,
                FilterOperator::NotEqual,
            ),
            (
                hyperQL::ast::BinaryOperator::LessThan,
                FilterOperator::LessThan,
            ),
            (
                hyperQL::ast::BinaryOperator::LessThanOrEqual,
                FilterOperator::LessThanOrEqual,
            ),
            (
                hyperQL::ast::BinaryOperator::GreaterThan,
                FilterOperator::GreaterThan,
            ),
            (
                hyperQL::ast::BinaryOperator::GreaterThanOrEqual,
                FilterOperator::GreaterThanOrEqual,
            ),
            (hyperQL::ast::BinaryOperator::Like, FilterOperator::Like),
            (hyperQL::ast::BinaryOperator::In, FilterOperator::In),
        ];

        for (input, expected) in test_cases {
            let result = matcher.convert_binary_operator(&input);
            assert!(result.is_ok(), "Failed to convert operator {:?}", input);
            assert_eq!(result.unwrap(), expected);
        }
    }

    #[test]
    fn test_convert_literal() {
        use hyperQL::ast::Literal;

        let matcher = PatternMatcher::new();

        let test_cases = vec![
            (Literal::Null, LiteralValue::Null),
            (Literal::Bool(true), LiteralValue::Boolean(true)),
            (Literal::Int(42), LiteralValue::Integer(42)),
            (Literal::Float(3.14), LiteralValue::Float(3.14)),
            (
                Literal::String("test".to_string()),
                LiteralValue::String("test".to_string()),
            ),
        ];

        for (input, expected) in test_cases {
            let result = matcher.convert_literal(&input);
            assert_eq!(result, expected);
        }
    }

    #[test]
    fn test_extract_filter_value_parameter() {
        use hyperQL::ast::{ColumnRef, Expression};

        let matcher = PatternMatcher::new();

        let expr = Expression::Column(ColumnRef {
            table: None,
            name: "min_age".to_string(),
        });

        let result = matcher.extract_filter_value(&expr);
        assert!(result.is_ok());

        let value = result.unwrap();
        assert!(matches!(value, FilterValue::Parameter(ref p) if p == "min_age"));
    }

    #[test]
    fn test_extract_filter_value_literal() {
        use hyperQL::ast::{Expression, Literal};

        let matcher = PatternMatcher::new();

        let expr = Expression::Literal(Literal::Int(100));

        let result = matcher.extract_filter_value(&expr);
        assert!(result.is_ok());

        let value = result.unwrap();
        assert!(matches!(
            value,
            FilterValue::Literal(LiteralValue::Integer(100))
        ));
    }
}