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
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
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
//! Domain Specific Language for building type-safe database queries

pub mod alias;
pub mod clean_projection;
pub mod composite_field;
pub mod expr;
pub mod hybrid_expr;
pub mod join;
pub mod procedure_call;
pub mod projection;
pub mod typed_column;
pub mod typed_query;

use crate::common::qualified_name;
use crate::schema::{Event, IndexMeta, StoredFunction, StoredProcedure, Table, View};
use std::borrow::Cow;
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::sync::{Arc, OnceLock, RwLock};

// Re-export key types
pub use clean_projection::{AutoProjection, CleanProjectedQuery, CleanRow};
pub use composite_field::{CompositeField, CompositeFieldBuilder, CompositeFieldRef};
pub use procedure_call::{
    call_function, call_procedure, FunctionCall, ParameterBinding, ProcedureCall,
};
pub use projection::{ProjectedQuery, ProjectionTarget, TypedRow};
pub use typed_column::{ColumnSelector, OrderBy, TypedColumn, WhereCondition};
pub use typed_query::{TypedQuery, TypedQueryBuilder};

/// Generic source for queries (table, view, event, or procedure call)
#[derive(Debug, Clone)]
pub enum Source {
    Table(Table),
    View(View),
    Event(Event),
    Procedure(StoredProcedure),
    Function(StoredFunction),
}

impl Source {
    /// Get the name of the source
    pub fn name(&self) -> &str {
        match self {
            Source::Table(table) => &table.name,
            Source::View(view) => &view.name,
            Source::Event(event) => &event.name,
            Source::Procedure(proc) => &proc.name,
            Source::Function(func) => &func.name,
        }
    }

    /// Get the schema of the source
    pub fn schema(&self) -> Option<&str> {
        match self {
            Source::Table(table) => table.schema.as_deref(),
            Source::View(view) => view.schema.as_deref(),
            Source::Event(event) => event.schema.as_deref(),
            Source::Procedure(proc) => proc.schema.as_deref(),
            Source::Function(func) => func.schema.as_deref(),
        }
    }

    /// Check if this is a materialized view
    pub fn is_materialized(&self) -> bool {
        match self {
            Source::Table(_) => false,
            Source::View(view) => view.materialized,
            Source::Event(_) => false,
            Source::Procedure(_) => false,
            Source::Function(_) => false,
        }
    }

    /// Get the fully qualified name
    pub fn qualified_name(&self) -> String {
        qualified_name(self.schema(), self.name())
    }

    /// Create a Source from a Table
    pub fn from_table(table: Table) -> Self {
        Source::Table(table)
    }

    /// Create a Source from a View
    pub fn from_view(view: View) -> Self {
        Source::View(view)
    }

    /// Create a Source from an Event
    pub fn from_event(event: Event) -> Self {
        Source::Event(event)
    }

    /// Create a Source from a Procedure
    pub fn from_procedure(procedure: StoredProcedure) -> Self {
        Source::Procedure(procedure)
    }

    /// Create a Source from a Function
    pub fn from_function(function: StoredFunction) -> Self {
        Source::Function(function)
    }
}

/// Thread-safe query cache for SQL generation performance
#[derive(Debug)]
struct QueryCache {
    cache: RwLock<HashMap<u64, String>>,
}

impl QueryCache {
    fn new() -> Self {
        Self {
            cache: RwLock::new(HashMap::new()),
        }
    }

    fn get(&self, hash: u64) -> Option<String> {
        self.cache
            .read()
            .ok()
            .and_then(|cache| cache.get(&hash).cloned())
    }

    fn insert(&self, hash: u64, sql: String) {
        if let Ok(mut cache) = self.cache.write() {
            // Simple LRU-like eviction when cache gets too large
            if cache.len() > 1000 {
                // Remove oldest entries (simple approach)
                let keys: Vec<u64> = cache.keys().cloned().take(100).collect();
                for key in keys {
                    cache.remove(&key);
                }
            }
            cache.insert(hash, sql);
        }
    }

    fn stats(&self) -> (usize, usize) {
        if let Ok(cache) = self.cache.read() {
            (cache.len(), 1000) // current size, max size
        } else {
            (0, 0)
        }
    }
}

/// Global thread-safe query cache for SQL generation
static QUERY_CACHE: OnceLock<Arc<QueryCache>> = OnceLock::new();

/// Index-aware query optimization
#[derive(Debug, Clone)]
pub struct IndexOptimizer {
    available_indexes: Vec<IndexMeta>,
}

impl IndexOptimizer {
    /// Create a new index optimizer with available indexes
    pub fn new(available_indexes: Vec<IndexMeta>) -> Self {
        Self { available_indexes }
    }

    /// Find the best index for a query based on WHERE conditions
    pub fn find_best_index(
        &self,
        where_conditions: &[String],
        table_name: &str,
    ) -> Option<&IndexMeta> {
        let table_indexes: Vec<&IndexMeta> = self
            .available_indexes
            .iter()
            .filter(|idx| idx.table == table_name)
            .collect();

        if table_indexes.is_empty() {
            return None;
        }

        // Score indexes based on how well they match the WHERE conditions
        let mut best_index = None;
        let mut best_score = 0;

        for index in table_indexes {
            let score = self.score_index_for_conditions(index, where_conditions);
            if score > best_score {
                best_score = score;
                best_index = Some(index);
            }
        }

        best_index
    }

    /// Score an index based on how well it matches WHERE conditions
    fn score_index_for_conditions(&self, index: &IndexMeta, conditions: &[String]) -> usize {
        let mut score = 0;

        for condition in conditions {
            for column in index.columns {
                if condition.contains(column) {
                    score += 1;
                }
            }
        }

        // Bonus for unique indexes
        if index.unique {
            score += 2;
        }

        // Bonus for B-tree indexes (most versatile)
        if matches!(index.index_type, crate::schema::IndexType::BTree) {
            score += 1;
        }

        score
    }

    /// Generate index hints for the query
    pub fn generate_index_hints(
        &self,
        table_name: &str,
        where_conditions: &[String],
    ) -> Option<String> {
        if let Some(index) = self.find_best_index(where_conditions, table_name) {
            Some(format!("/* Use index: {} */", index.name))
        } else {
            None
        }
    }

    /// Check if a query can benefit from an index
    pub fn can_use_index(&self, table_name: &str, columns: &[String]) -> bool {
        self.available_indexes.iter().any(|idx| {
            idx.table == table_name
                && columns
                    .iter()
                    .any(|col| idx.columns.contains(&col.as_str()))
        })
    }
}

/// Join type for SQL queries
#[derive(Debug, Clone, Hash)]
pub enum JoinType {
    Inner,
    Left,
    Right,
    Full,
}

/// Join clause for queries
#[derive(Debug, Clone)]
pub struct JoinClause {
    pub join_type: JoinType,
    pub target: Source,
    pub condition: String,
}

impl Hash for JoinClause {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.join_type.hash(state);
        // Hash the target name instead of the full target
        self.target.name().hash(state);
        self.condition.hash(state);
    }
}

/// Main query builder for Ignis
#[derive(Debug, Clone)]
pub struct Query {
    pub from_source: Option<Source>,
    pub select_columns: Vec<String>,
    pub joins: Vec<JoinClause>,
    pub where_clause: Option<String>,
    pub group_by: Vec<String>,
    pub having_clause: Option<String>,
    pub order_by: Vec<String>,
    pub limit: Option<usize>,
    pub offset: Option<usize>,
    pub index_optimizer: Option<IndexOptimizer>,
}

impl Hash for Query {
    fn hash<H: Hasher>(&self, state: &mut H) {
        // Hash the key components that affect SQL generation
        if let Some(ref source) = self.from_source {
            source.name().hash(state);
        }
        self.select_columns.hash(state);
        self.joins.len().hash(state);
        for join in &self.joins {
            join.join_type.hash(state);
            // Hash the target name instead of the full target
            join.target.name().hash(state);
            join.condition.hash(state);
        }
        self.where_clause.hash(state);
        self.group_by.hash(state);
        self.having_clause.hash(state);
        self.order_by.hash(state);
        self.limit.hash(state);
        self.offset.hash(state);
    }
}

impl Query {
    /// Create a new query
    pub fn new() -> Self {
        Self {
            from_source: None,
            select_columns: Vec::new(),
            joins: Vec::new(),
            where_clause: None,
            group_by: Vec::new(),
            having_clause: None,
            order_by: Vec::new(),
            limit: None,
            offset: None,
            index_optimizer: None,
        }
    }

    /// Set the table to query from
    pub fn from(mut self, source: Source) -> Self {
        self.from_source = Some(source);
        self
    }

    /// Set the table to query from (convenience method)
    pub fn from_table(mut self, table: Table) -> Self {
        self.from_source = Some(Source::Table(table));
        self
    }

    /// Set the table to query from using table name (convenience method)
    pub fn from_table_name(mut self, table_name: impl Into<String>) -> Self {
        self.from_source = Some(Source::Table(Table::new(table_name)));
        self
    }

    /// Set the view to query from (convenience method)
    pub fn from_view(mut self, view: View) -> Self {
        self.from_source = Some(Source::View(view));
        self
    }

    /// Call a stored procedure (convenience method)
    pub fn call_procedure(mut self, procedure: StoredProcedure) -> Self {
        self.from_source = Some(Source::Procedure(procedure));
        self
    }

    /// Call a stored function (convenience method)
    pub fn call_function(mut self, function: StoredFunction) -> Self {
        self.from_source = Some(Source::Function(function));
        self
    }

    /// Add columns to select
    pub fn select_columns(mut self, columns: Vec<String>) -> Self {
        self.select_columns = columns;
        self
    }

    /// Add columns to select (convenience method for &[&str])
    pub fn select_columns_str(mut self, columns: &[&str]) -> Self {
        self.select_columns = columns.iter().map(|s| s.to_string()).collect();
        self
    }

    /// Set the WHERE clause
    pub fn filter(mut self, where_clause: impl Into<String>) -> Self {
        self.where_clause = Some(where_clause.into());
        self
    }

    /// Add composite field filter to WHERE clause
    pub fn filter_composite_field(mut self, field_ref: CompositeFieldRef) -> Self {
        let condition = field_ref.sql_expression;

        if let Some(existing) = self.where_clause {
            self.where_clause = Some(format!("({}) AND ({})", existing, condition));
        } else {
            self.where_clause = Some(condition);
        }

        self
    }

    /// Add composite field filter with OR logic
    pub fn or_filter_composite_field(mut self, field_ref: CompositeFieldRef) -> Self {
        let condition = field_ref.sql_expression;

        if let Some(existing) = self.where_clause {
            self.where_clause = Some(format!("({}) OR ({})", existing, condition));
        } else {
            self.where_clause = Some(condition);
        }

        self
    }

    /// Add ORDER BY clause
    pub fn order_by(mut self, column: impl Into<String>) -> Self {
        self.order_by.push(column.into());
        self
    }

    /// Add ORDER BY clause using composite field
    pub fn order_by_composite_field<T>(mut self, field: CompositeField<T>) -> Self {
        self.order_by.push(field.to_sql_expression());
        self
    }

    /// Add composite field to SELECT clause
    pub fn select_composite_field<T>(
        mut self,
        field: CompositeField<T>,
        alias: Option<String>,
    ) -> Self {
        let expression = if let Some(alias) = alias {
            format!("{} AS \"{}\"", field.to_sql_expression(), alias)
        } else {
            field.to_sql_expression()
        };

        self.select_columns.push(expression);
        self
    }

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

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

    /// Add an INNER JOIN
    pub fn inner_join(mut self, target: Source, condition: impl Into<String>) -> Self {
        self.joins.push(JoinClause {
            join_type: JoinType::Inner,
            target,
            condition: condition.into(),
        });
        self
    }

    /// Add a LEFT JOIN
    pub fn left_join(mut self, target: Source, condition: impl Into<String>) -> Self {
        self.joins.push(JoinClause {
            join_type: JoinType::Left,
            target,
            condition: condition.into(),
        });
        self
    }

    /// Add a RIGHT JOIN
    pub fn right_join(mut self, target: Source, condition: impl Into<String>) -> Self {
        self.joins.push(JoinClause {
            join_type: JoinType::Right,
            target,
            condition: condition.into(),
        });
        self
    }

    /// Add a FULL OUTER JOIN
    pub fn full_join(mut self, target: Source, condition: impl Into<String>) -> Self {
        self.joins.push(JoinClause {
            join_type: JoinType::Full,
            target,
            condition: condition.into(),
        });
        self
    }

    /// Add a JOIN using table (convenience method)
    pub fn inner_join_table(mut self, table: Table, condition: impl Into<String>) -> Self {
        self.joins.push(JoinClause {
            join_type: JoinType::Inner,
            target: Source::Table(table),
            condition: condition.into(),
        });
        self
    }

    /// Add an INNER JOIN using table name (convenience method)
    pub fn inner_join_table_name(
        mut self,
        table_name: impl Into<String>,
        condition: impl Into<String>,
    ) -> Self {
        self.joins.push(JoinClause {
            join_type: JoinType::Inner,
            target: Source::Table(Table::new(table_name)),
            condition: condition.into(),
        });
        self
    }

    /// Add a LEFT JOIN using table name (convenience method)
    pub fn left_join_table_name(
        mut self,
        table_name: impl Into<String>,
        condition: impl Into<String>,
    ) -> Self {
        self.joins.push(JoinClause {
            join_type: JoinType::Left,
            target: Source::Table(Table::new(table_name)),
            condition: condition.into(),
        });
        self
    }

    /// Add a RIGHT JOIN using table name (convenience method)
    pub fn right_join_table_name(
        mut self,
        table_name: impl Into<String>,
        condition: impl Into<String>,
    ) -> Self {
        self.joins.push(JoinClause {
            join_type: JoinType::Right,
            target: Source::Table(Table::new(table_name)),
            condition: condition.into(),
        });
        self
    }

    /// Add GROUP BY clause
    pub fn group_by(mut self, column: impl Into<String>) -> Self {
        self.group_by.push(column.into());
        self
    }

    /// Set HAVING clause
    pub fn having(mut self, condition: impl Into<String>) -> Self {
        self.having_clause = Some(condition.into());
        self
    }

    /// Add a SELECT with aggregation function
    pub fn select(mut self, expression: impl Into<String>) -> Self {
        self.select_columns.push(expression.into());
        self
    }

    /// Add COUNT aggregation
    pub fn count(mut self, column: impl Into<String>) -> Self {
        self.select_columns
            .push(format!("COUNT({})", column.into()));
        self
    }

    /// Add SUM aggregation
    pub fn sum(mut self, column: impl Into<String>) -> Self {
        self.select_columns.push(format!("SUM({})", column.into()));
        self
    }

    /// Add AVG aggregation
    pub fn avg(mut self, column: impl Into<String>) -> Self {
        self.select_columns.push(format!("AVG({})", column.into()));
        self
    }

    /// Add MAX aggregation
    pub fn max(mut self, column: impl Into<String>) -> Self {
        self.select_columns.push(format!("MAX({})", column.into()));
        self
    }

    /// Add MIN aggregation
    pub fn min(mut self, column: impl Into<String>) -> Self {
        self.select_columns.push(format!("MIN({})", column.into()));
        self
    }

    /// Enable index-aware query optimization
    pub fn with_indexes(mut self, indexes: Vec<IndexMeta>) -> Self {
        self.index_optimizer = Some(IndexOptimizer::new(indexes));
        self
    }

    /// Get index optimization hints for this query
    pub fn get_index_hints(&self) -> Option<String> {
        if let (Some(optimizer), Some(source), Some(where_clause)) =
            (&self.index_optimizer, &self.from_source, &self.where_clause)
        {
            // Extract column names from WHERE clause for analysis
            let conditions = vec![where_clause.clone()];
            optimizer.generate_index_hints(source.name(), &conditions)
        } else {
            None
        }
    }

    /// Check if this query is against a materialized view
    pub fn is_materialized_view(&self) -> bool {
        self.from_source
            .as_ref()
            .map(|s| s.is_materialized())
            .unwrap_or(false)
    }

    /// Generate refresh SQL for materialized views
    pub fn generate_refresh_sql(&self) -> Option<String> {
        if let Some(ref source) = self.from_source {
            if let Source::View(view) = source {
                if view.materialized {
                    return view.generate_refresh_ddl();
                }
            }
        }
        None
    }

    /// Check if this query is a procedure or function call
    pub fn is_procedure_call(&self) -> bool {
        matches!(
            self.from_source,
            Some(Source::Procedure(_)) | Some(Source::Function(_))
        )
    }

    /// Generate CALL statement for procedures or SELECT statement for functions
    pub fn generate_call_sql(&self, parameters: Vec<String>) -> String {
        match &self.from_source {
            Some(Source::Procedure(proc)) => {
                let qualified_name = proc.qualified_name();
                if parameters.is_empty() {
                    format!("CALL {}()", qualified_name)
                } else {
                    format!("CALL {}({})", qualified_name, parameters.join(", "))
                }
            }
            Some(Source::Function(func)) => {
                let qualified_name = func.qualified_name();
                if parameters.is_empty() {
                    format!("SELECT {}() as result", qualified_name)
                } else {
                    format!(
                        "SELECT {}({}) as result",
                        qualified_name,
                        parameters.join(", ")
                    )
                }
            }
            _ => panic!("generate_call_sql can only be used with procedure or function sources"),
        }
    }

    /// Generate the SQL for this query with thread-safe caching for performance
    pub fn to_sql(&self) -> String {
        // Check cache first
        let mut hasher = std::collections::hash_map::DefaultHasher::new();
        self.hash(&mut hasher);
        let hash = hasher.finish();

        // Try to get from cache
        if let Some(cache) = QUERY_CACHE.get() {
            if let Some(cached_sql) = cache.get(hash) {
                return cached_sql;
            }
        }

        // Generate SQL with optimized string building
        let sql = self.generate_sql_optimized();

        // Cache the result in thread-safe manner
        if let Some(cache) = QUERY_CACHE.get() {
            cache.insert(hash, sql.clone());
        }

        sql
    }

    /// Optimized SQL generation using Cow and pre-allocated capacity
    fn generate_sql_optimized(&self) -> String {
        // Pre-allocate with reasonable capacity
        let mut sql = String::with_capacity(512);

        // Use Cow for static strings to avoid allocations
        let select_keyword: Cow<'static, str> = Cow::Borrowed("SELECT");
        let from_keyword: Cow<'static, str> = Cow::Borrowed(" FROM ");
        let where_keyword: Cow<'static, str> = Cow::Borrowed(" WHERE ");
        let group_by_keyword: Cow<'static, str> = Cow::Borrowed(" GROUP BY ");
        let having_keyword: Cow<'static, str> = Cow::Borrowed(" HAVING ");
        let order_by_keyword: Cow<'static, str> = Cow::Borrowed(" ORDER BY ");
        let limit_keyword: Cow<'static, str> = Cow::Borrowed(" LIMIT ");
        let offset_keyword: Cow<'static, str> = Cow::Borrowed(" OFFSET ");

        // SELECT
        if self.select_columns.is_empty() {
            sql.push_str("SELECT *");
        } else {
            // Optimize column formatting
            let cols: Vec<Cow<'_, str>> = self
                .select_columns
                .iter()
                .map(|c| {
                    if c.contains('(') || c.contains(' ') || c.contains('.') {
                        Cow::Borrowed(c.as_str()) // Aggregates, complex expressions, or qualified names
                    } else {
                        Cow::Owned(format!("\"{}\"", c)) // Simple column names only
                    }
                })
                .collect();
            use std::fmt::Write;
            write!(sql, "{} {}", select_keyword, cols.join(", ")).unwrap();
        }

        // FROM (skip for procedure/function calls)
        if let Some(ref source) = self.from_source {
            match source {
                Source::Procedure(_) | Source::Function(_) => {
                    // For procedure/function calls, we shouldn't generate SELECT FROM syntax
                    // Use generate_call_sql instead
                    return "-- Use generate_call_sql() for procedure/function calls".to_string();
                }
                _ => {
                    sql.push_str(&from_keyword);
                    sql.push_str(&source.qualified_name());
                }
            }
        }

        // JOINs
        for join in &self.joins {
            let join_keyword = match join.join_type {
                JoinType::Inner => " INNER JOIN ",
                JoinType::Left => " LEFT JOIN ",
                JoinType::Right => " RIGHT JOIN ",
                JoinType::Full => " FULL OUTER JOIN ",
            };
            sql.push_str(join_keyword);
            sql.push_str(&join.target.qualified_name());
            sql.push_str(" ON ");
            sql.push_str(&join.condition);
        }

        // WHERE
        if let Some(ref where_clause) = self.where_clause {
            sql.push_str(&where_keyword);
            sql.push_str(where_clause);
        }

        // GROUP BY
        if !self.group_by.is_empty() {
            sql.push_str(&group_by_keyword);
            let group_cols: Vec<Cow<'_, str>> = self
                .group_by
                .iter()
                .map(|c| {
                    if c.contains('.') {
                        Cow::Borrowed(c.as_str()) // Already qualified
                    } else {
                        Cow::Owned(format!("\"{}\"", c)) // Simple column name
                    }
                })
                .collect();
            sql.push_str(&group_cols.join(", "));
        }

        // HAVING
        if let Some(ref having_clause) = self.having_clause {
            sql.push_str(&having_keyword);
            sql.push_str(having_clause);
        }

        // ORDER BY
        if !self.order_by.is_empty() {
            sql.push_str(&order_by_keyword);
            let order_cols: Vec<Cow<'_, str>> = self
                .order_by
                .iter()
                .map(|c| {
                    if c.contains('.') || c.contains(' ') {
                        Cow::Borrowed(c.as_str()) // Already qualified or complex
                    } else {
                        Cow::Owned(format!("\"{}\"", c)) // Simple column name
                    }
                })
                .collect();
            sql.push_str(&order_cols.join(", "));
        }

        // LIMIT
        if let Some(limit) = self.limit {
            sql.push_str(&limit_keyword);
            sql.push_str(&limit.to_string());
        }

        // OFFSET
        if let Some(offset) = self.offset {
            sql.push_str(&offset_keyword);
            sql.push_str(&offset.to_string());
        }

        sql
    }

    /// Get cache statistics for monitoring
    pub fn cache_stats() -> (usize, usize) {
        QUERY_CACHE
            .get()
            .map(|cache| cache.stats())
            .unwrap_or((0, 0))
    }

    /// Initialize the query cache (call once at startup)
    pub fn init_cache() {
        let _ = QUERY_CACHE.set(Arc::new(QueryCache::new()));
    }

    /// Generate all SQL statements for this query (including refresh for materialized views)
    pub fn generate_all_sql(&self) -> Vec<String> {
        let mut statements = Vec::new();

        // Main query
        statements.push(self.to_sql());

        // Refresh materialized view if applicable
        if let Some(refresh_sql) = self.generate_refresh_sql() {
            statements.push(refresh_sql);
        }

        statements
    }
}

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

/// Type-safe column reference for use in queries
#[derive(Debug, Clone)]
pub struct Column<T> {
    pub name: String,
    pub table: Option<String>,
    pub schema: Option<String>,
    _phantom: std::marker::PhantomData<T>,
}

impl<T> Column<T> {
    /// Create a new column reference
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            table: None,
            schema: None,
            _phantom: std::marker::PhantomData,
        }
    }

    /// Set the table for this column
    pub fn from_table(mut self, table: impl Into<String>) -> Self {
        self.table = Some(table.into());
        self
    }

    /// Set the schema for this column
    pub fn from_schema(mut self, schema: impl Into<String>) -> Self {
        self.schema = Some(schema.into());
        self
    }

    /// Get the fully qualified column name
    pub fn qualified_name(&self) -> String {
        let mut parts = Vec::new();

        if let Some(ref schema) = self.schema {
            parts.push(format!("\"{}\"", schema));
        }

        if let Some(ref table) = self.table {
            parts.push(format!("\"{}\"", table));
        }

        parts.push(format!("\"{}\"", self.name));

        parts.join(".")
    }

    /// Create an equality comparison
    pub fn eq(self, _value: T) -> String {
        format!("{} = ?", self.qualified_name())
    }

    /// Create a greater than comparison
    pub fn gt(self, _value: T) -> String {
        format!("{} > ?", self.qualified_name())
    }

    /// Create a less than comparison
    pub fn lt(self, _value: T) -> String {
        format!("{} < ?", self.qualified_name())
    }

    /// Create a LIKE comparison
    pub fn like(self, _pattern: impl Into<String>) -> String {
        format!("{} LIKE ?", self.qualified_name())
    }

    /// Create an IN comparison
    pub fn in_(self, _values: Vec<T>) -> String {
        let placeholders: Vec<String> = (0.._values.len()).map(|_| "?".to_string()).collect();
        format!("{} IN ({})", self.qualified_name(), placeholders.join(", "))
    }
}