Skip to main content

ignis_db/dsl/
mod.rs

1//! Domain Specific Language for building type-safe database queries
2
3pub mod alias;
4pub mod clean_projection;
5pub mod composite_field;
6pub mod expr;
7pub mod hybrid_expr;
8pub mod join;
9pub mod procedure_call;
10pub mod projection;
11pub mod typed_column;
12pub mod typed_query;
13
14use crate::common::qualified_name;
15use crate::schema::{Event, IndexMeta, StoredFunction, StoredProcedure, Table, View};
16use std::borrow::Cow;
17use std::collections::HashMap;
18use std::hash::{Hash, Hasher};
19use std::sync::{Arc, OnceLock, RwLock};
20
21// Re-export key types
22pub use clean_projection::{AutoProjection, CleanProjectedQuery, CleanRow};
23pub use composite_field::{CompositeField, CompositeFieldBuilder, CompositeFieldRef};
24pub use procedure_call::{
25    call_function, call_procedure, FunctionCall, ParameterBinding, ProcedureCall,
26};
27pub use projection::{ProjectedQuery, ProjectionTarget, TypedRow};
28pub use typed_column::{ColumnSelector, OrderBy, TypedColumn, WhereCondition};
29pub use typed_query::{TypedQuery, TypedQueryBuilder};
30
31/// Generic source for queries (table, view, event, or procedure call)
32#[derive(Debug, Clone)]
33pub enum Source {
34    Table(Table),
35    View(View),
36    Event(Event),
37    Procedure(StoredProcedure),
38    Function(StoredFunction),
39}
40
41impl Source {
42    /// Get the name of the source
43    pub fn name(&self) -> &str {
44        match self {
45            Source::Table(table) => &table.name,
46            Source::View(view) => &view.name,
47            Source::Event(event) => &event.name,
48            Source::Procedure(proc) => &proc.name,
49            Source::Function(func) => &func.name,
50        }
51    }
52
53    /// Get the schema of the source
54    pub fn schema(&self) -> Option<&str> {
55        match self {
56            Source::Table(table) => table.schema.as_deref(),
57            Source::View(view) => view.schema.as_deref(),
58            Source::Event(event) => event.schema.as_deref(),
59            Source::Procedure(proc) => proc.schema.as_deref(),
60            Source::Function(func) => func.schema.as_deref(),
61        }
62    }
63
64    /// Check if this is a materialized view
65    pub fn is_materialized(&self) -> bool {
66        match self {
67            Source::Table(_) => false,
68            Source::View(view) => view.materialized,
69            Source::Event(_) => false,
70            Source::Procedure(_) => false,
71            Source::Function(_) => false,
72        }
73    }
74
75    /// Get the fully qualified name
76    pub fn qualified_name(&self) -> String {
77        qualified_name(self.schema(), self.name())
78    }
79
80    /// Create a Source from a Table
81    pub fn from_table(table: Table) -> Self {
82        Source::Table(table)
83    }
84
85    /// Create a Source from a View
86    pub fn from_view(view: View) -> Self {
87        Source::View(view)
88    }
89
90    /// Create a Source from an Event
91    pub fn from_event(event: Event) -> Self {
92        Source::Event(event)
93    }
94
95    /// Create a Source from a Procedure
96    pub fn from_procedure(procedure: StoredProcedure) -> Self {
97        Source::Procedure(procedure)
98    }
99
100    /// Create a Source from a Function
101    pub fn from_function(function: StoredFunction) -> Self {
102        Source::Function(function)
103    }
104}
105
106/// Thread-safe query cache for SQL generation performance
107#[derive(Debug)]
108struct QueryCache {
109    cache: RwLock<HashMap<u64, String>>,
110}
111
112impl QueryCache {
113    fn new() -> Self {
114        Self {
115            cache: RwLock::new(HashMap::new()),
116        }
117    }
118
119    fn get(&self, hash: u64) -> Option<String> {
120        self.cache
121            .read()
122            .ok()
123            .and_then(|cache| cache.get(&hash).cloned())
124    }
125
126    fn insert(&self, hash: u64, sql: String) {
127        if let Ok(mut cache) = self.cache.write() {
128            // Simple LRU-like eviction when cache gets too large
129            if cache.len() > 1000 {
130                // Remove oldest entries (simple approach)
131                let keys: Vec<u64> = cache.keys().cloned().take(100).collect();
132                for key in keys {
133                    cache.remove(&key);
134                }
135            }
136            cache.insert(hash, sql);
137        }
138    }
139
140    fn stats(&self) -> (usize, usize) {
141        if let Ok(cache) = self.cache.read() {
142            (cache.len(), 1000) // current size, max size
143        } else {
144            (0, 0)
145        }
146    }
147}
148
149/// Global thread-safe query cache for SQL generation
150static QUERY_CACHE: OnceLock<Arc<QueryCache>> = OnceLock::new();
151
152/// Index-aware query optimization
153#[derive(Debug, Clone)]
154pub struct IndexOptimizer {
155    available_indexes: Vec<IndexMeta>,
156}
157
158impl IndexOptimizer {
159    /// Create a new index optimizer with available indexes
160    pub fn new(available_indexes: Vec<IndexMeta>) -> Self {
161        Self { available_indexes }
162    }
163
164    /// Find the best index for a query based on WHERE conditions
165    pub fn find_best_index(
166        &self,
167        where_conditions: &[String],
168        table_name: &str,
169    ) -> Option<&IndexMeta> {
170        let table_indexes: Vec<&IndexMeta> = self
171            .available_indexes
172            .iter()
173            .filter(|idx| idx.table == table_name)
174            .collect();
175
176        if table_indexes.is_empty() {
177            return None;
178        }
179
180        // Score indexes based on how well they match the WHERE conditions
181        let mut best_index = None;
182        let mut best_score = 0;
183
184        for index in table_indexes {
185            let score = self.score_index_for_conditions(index, where_conditions);
186            if score > best_score {
187                best_score = score;
188                best_index = Some(index);
189            }
190        }
191
192        best_index
193    }
194
195    /// Score an index based on how well it matches WHERE conditions
196    fn score_index_for_conditions(&self, index: &IndexMeta, conditions: &[String]) -> usize {
197        let mut score = 0;
198
199        for condition in conditions {
200            for column in index.columns {
201                if condition.contains(column) {
202                    score += 1;
203                }
204            }
205        }
206
207        // Bonus for unique indexes
208        if index.unique {
209            score += 2;
210        }
211
212        // Bonus for B-tree indexes (most versatile)
213        if matches!(index.index_type, crate::schema::IndexType::BTree) {
214            score += 1;
215        }
216
217        score
218    }
219
220    /// Generate index hints for the query
221    pub fn generate_index_hints(
222        &self,
223        table_name: &str,
224        where_conditions: &[String],
225    ) -> Option<String> {
226        if let Some(index) = self.find_best_index(where_conditions, table_name) {
227            Some(format!("/* Use index: {} */", index.name))
228        } else {
229            None
230        }
231    }
232
233    /// Check if a query can benefit from an index
234    pub fn can_use_index(&self, table_name: &str, columns: &[String]) -> bool {
235        self.available_indexes.iter().any(|idx| {
236            idx.table == table_name
237                && columns
238                    .iter()
239                    .any(|col| idx.columns.contains(&col.as_str()))
240        })
241    }
242}
243
244/// Join type for SQL queries
245#[derive(Debug, Clone, Hash)]
246pub enum JoinType {
247    Inner,
248    Left,
249    Right,
250    Full,
251}
252
253/// Join clause for queries
254#[derive(Debug, Clone)]
255pub struct JoinClause {
256    pub join_type: JoinType,
257    pub target: Source,
258    pub condition: String,
259}
260
261impl Hash for JoinClause {
262    fn hash<H: Hasher>(&self, state: &mut H) {
263        self.join_type.hash(state);
264        // Hash the target name instead of the full target
265        self.target.name().hash(state);
266        self.condition.hash(state);
267    }
268}
269
270/// Main query builder for Ignis
271#[derive(Debug, Clone)]
272pub struct Query {
273    pub from_source: Option<Source>,
274    pub select_columns: Vec<String>,
275    pub joins: Vec<JoinClause>,
276    pub where_clause: Option<String>,
277    pub group_by: Vec<String>,
278    pub having_clause: Option<String>,
279    pub order_by: Vec<String>,
280    pub limit: Option<usize>,
281    pub offset: Option<usize>,
282    pub index_optimizer: Option<IndexOptimizer>,
283}
284
285impl Hash for Query {
286    fn hash<H: Hasher>(&self, state: &mut H) {
287        // Hash the key components that affect SQL generation
288        if let Some(ref source) = self.from_source {
289            source.name().hash(state);
290        }
291        self.select_columns.hash(state);
292        self.joins.len().hash(state);
293        for join in &self.joins {
294            join.join_type.hash(state);
295            // Hash the target name instead of the full target
296            join.target.name().hash(state);
297            join.condition.hash(state);
298        }
299        self.where_clause.hash(state);
300        self.group_by.hash(state);
301        self.having_clause.hash(state);
302        self.order_by.hash(state);
303        self.limit.hash(state);
304        self.offset.hash(state);
305    }
306}
307
308impl Query {
309    /// Create a new query
310    pub fn new() -> Self {
311        Self {
312            from_source: None,
313            select_columns: Vec::new(),
314            joins: Vec::new(),
315            where_clause: None,
316            group_by: Vec::new(),
317            having_clause: None,
318            order_by: Vec::new(),
319            limit: None,
320            offset: None,
321            index_optimizer: None,
322        }
323    }
324
325    /// Set the table to query from
326    pub fn from(mut self, source: Source) -> Self {
327        self.from_source = Some(source);
328        self
329    }
330
331    /// Set the table to query from (convenience method)
332    pub fn from_table(mut self, table: Table) -> Self {
333        self.from_source = Some(Source::Table(table));
334        self
335    }
336
337    /// Set the table to query from using table name (convenience method)
338    pub fn from_table_name(mut self, table_name: impl Into<String>) -> Self {
339        self.from_source = Some(Source::Table(Table::new(table_name)));
340        self
341    }
342
343    /// Set the view to query from (convenience method)
344    pub fn from_view(mut self, view: View) -> Self {
345        self.from_source = Some(Source::View(view));
346        self
347    }
348
349    /// Call a stored procedure (convenience method)
350    pub fn call_procedure(mut self, procedure: StoredProcedure) -> Self {
351        self.from_source = Some(Source::Procedure(procedure));
352        self
353    }
354
355    /// Call a stored function (convenience method)
356    pub fn call_function(mut self, function: StoredFunction) -> Self {
357        self.from_source = Some(Source::Function(function));
358        self
359    }
360
361    /// Add columns to select
362    pub fn select_columns(mut self, columns: Vec<String>) -> Self {
363        self.select_columns = columns;
364        self
365    }
366
367    /// Add columns to select (convenience method for &[&str])
368    pub fn select_columns_str(mut self, columns: &[&str]) -> Self {
369        self.select_columns = columns.iter().map(|s| s.to_string()).collect();
370        self
371    }
372
373    /// Set the WHERE clause
374    pub fn filter(mut self, where_clause: impl Into<String>) -> Self {
375        self.where_clause = Some(where_clause.into());
376        self
377    }
378
379    /// Add composite field filter to WHERE clause
380    pub fn filter_composite_field(mut self, field_ref: CompositeFieldRef) -> Self {
381        let condition = field_ref.sql_expression;
382
383        if let Some(existing) = self.where_clause {
384            self.where_clause = Some(format!("({}) AND ({})", existing, condition));
385        } else {
386            self.where_clause = Some(condition);
387        }
388
389        self
390    }
391
392    /// Add composite field filter with OR logic
393    pub fn or_filter_composite_field(mut self, field_ref: CompositeFieldRef) -> Self {
394        let condition = field_ref.sql_expression;
395
396        if let Some(existing) = self.where_clause {
397            self.where_clause = Some(format!("({}) OR ({})", existing, condition));
398        } else {
399            self.where_clause = Some(condition);
400        }
401
402        self
403    }
404
405    /// Add ORDER BY clause
406    pub fn order_by(mut self, column: impl Into<String>) -> Self {
407        self.order_by.push(column.into());
408        self
409    }
410
411    /// Add ORDER BY clause using composite field
412    pub fn order_by_composite_field<T>(mut self, field: CompositeField<T>) -> Self {
413        self.order_by.push(field.to_sql_expression());
414        self
415    }
416
417    /// Add composite field to SELECT clause
418    pub fn select_composite_field<T>(
419        mut self,
420        field: CompositeField<T>,
421        alias: Option<String>,
422    ) -> Self {
423        let expression = if let Some(alias) = alias {
424            format!("{} AS \"{}\"", field.to_sql_expression(), alias)
425        } else {
426            field.to_sql_expression()
427        };
428
429        self.select_columns.push(expression);
430        self
431    }
432
433    /// Set the LIMIT
434    pub fn limit(mut self, limit: usize) -> Self {
435        self.limit = Some(limit);
436        self
437    }
438
439    /// Set the OFFSET
440    pub fn offset(mut self, offset: usize) -> Self {
441        self.offset = Some(offset);
442        self
443    }
444
445    /// Add an INNER JOIN
446    pub fn inner_join(mut self, target: Source, condition: impl Into<String>) -> Self {
447        self.joins.push(JoinClause {
448            join_type: JoinType::Inner,
449            target,
450            condition: condition.into(),
451        });
452        self
453    }
454
455    /// Add a LEFT JOIN
456    pub fn left_join(mut self, target: Source, condition: impl Into<String>) -> Self {
457        self.joins.push(JoinClause {
458            join_type: JoinType::Left,
459            target,
460            condition: condition.into(),
461        });
462        self
463    }
464
465    /// Add a RIGHT JOIN
466    pub fn right_join(mut self, target: Source, condition: impl Into<String>) -> Self {
467        self.joins.push(JoinClause {
468            join_type: JoinType::Right,
469            target,
470            condition: condition.into(),
471        });
472        self
473    }
474
475    /// Add a FULL OUTER JOIN
476    pub fn full_join(mut self, target: Source, condition: impl Into<String>) -> Self {
477        self.joins.push(JoinClause {
478            join_type: JoinType::Full,
479            target,
480            condition: condition.into(),
481        });
482        self
483    }
484
485    /// Add a JOIN using table (convenience method)
486    pub fn inner_join_table(mut self, table: Table, condition: impl Into<String>) -> Self {
487        self.joins.push(JoinClause {
488            join_type: JoinType::Inner,
489            target: Source::Table(table),
490            condition: condition.into(),
491        });
492        self
493    }
494
495    /// Add an INNER JOIN using table name (convenience method)
496    pub fn inner_join_table_name(
497        mut self,
498        table_name: impl Into<String>,
499        condition: impl Into<String>,
500    ) -> Self {
501        self.joins.push(JoinClause {
502            join_type: JoinType::Inner,
503            target: Source::Table(Table::new(table_name)),
504            condition: condition.into(),
505        });
506        self
507    }
508
509    /// Add a LEFT JOIN using table name (convenience method)
510    pub fn left_join_table_name(
511        mut self,
512        table_name: impl Into<String>,
513        condition: impl Into<String>,
514    ) -> Self {
515        self.joins.push(JoinClause {
516            join_type: JoinType::Left,
517            target: Source::Table(Table::new(table_name)),
518            condition: condition.into(),
519        });
520        self
521    }
522
523    /// Add a RIGHT JOIN using table name (convenience method)
524    pub fn right_join_table_name(
525        mut self,
526        table_name: impl Into<String>,
527        condition: impl Into<String>,
528    ) -> Self {
529        self.joins.push(JoinClause {
530            join_type: JoinType::Right,
531            target: Source::Table(Table::new(table_name)),
532            condition: condition.into(),
533        });
534        self
535    }
536
537    /// Add GROUP BY clause
538    pub fn group_by(mut self, column: impl Into<String>) -> Self {
539        self.group_by.push(column.into());
540        self
541    }
542
543    /// Set HAVING clause
544    pub fn having(mut self, condition: impl Into<String>) -> Self {
545        self.having_clause = Some(condition.into());
546        self
547    }
548
549    /// Add a SELECT with aggregation function
550    pub fn select(mut self, expression: impl Into<String>) -> Self {
551        self.select_columns.push(expression.into());
552        self
553    }
554
555    /// Add COUNT aggregation
556    pub fn count(mut self, column: impl Into<String>) -> Self {
557        self.select_columns
558            .push(format!("COUNT({})", column.into()));
559        self
560    }
561
562    /// Add SUM aggregation
563    pub fn sum(mut self, column: impl Into<String>) -> Self {
564        self.select_columns.push(format!("SUM({})", column.into()));
565        self
566    }
567
568    /// Add AVG aggregation
569    pub fn avg(mut self, column: impl Into<String>) -> Self {
570        self.select_columns.push(format!("AVG({})", column.into()));
571        self
572    }
573
574    /// Add MAX aggregation
575    pub fn max(mut self, column: impl Into<String>) -> Self {
576        self.select_columns.push(format!("MAX({})", column.into()));
577        self
578    }
579
580    /// Add MIN aggregation
581    pub fn min(mut self, column: impl Into<String>) -> Self {
582        self.select_columns.push(format!("MIN({})", column.into()));
583        self
584    }
585
586    /// Enable index-aware query optimization
587    pub fn with_indexes(mut self, indexes: Vec<IndexMeta>) -> Self {
588        self.index_optimizer = Some(IndexOptimizer::new(indexes));
589        self
590    }
591
592    /// Get index optimization hints for this query
593    pub fn get_index_hints(&self) -> Option<String> {
594        if let (Some(optimizer), Some(source), Some(where_clause)) =
595            (&self.index_optimizer, &self.from_source, &self.where_clause)
596        {
597            // Extract column names from WHERE clause for analysis
598            let conditions = vec![where_clause.clone()];
599            optimizer.generate_index_hints(source.name(), &conditions)
600        } else {
601            None
602        }
603    }
604
605    /// Check if this query is against a materialized view
606    pub fn is_materialized_view(&self) -> bool {
607        self.from_source
608            .as_ref()
609            .map(|s| s.is_materialized())
610            .unwrap_or(false)
611    }
612
613    /// Generate refresh SQL for materialized views
614    pub fn generate_refresh_sql(&self) -> Option<String> {
615        if let Some(ref source) = self.from_source {
616            if let Source::View(view) = source {
617                if view.materialized {
618                    return view.generate_refresh_ddl();
619                }
620            }
621        }
622        None
623    }
624
625    /// Check if this query is a procedure or function call
626    pub fn is_procedure_call(&self) -> bool {
627        matches!(
628            self.from_source,
629            Some(Source::Procedure(_)) | Some(Source::Function(_))
630        )
631    }
632
633    /// Generate CALL statement for procedures or SELECT statement for functions
634    pub fn generate_call_sql(&self, parameters: Vec<String>) -> String {
635        match &self.from_source {
636            Some(Source::Procedure(proc)) => {
637                let qualified_name = proc.qualified_name();
638                if parameters.is_empty() {
639                    format!("CALL {}()", qualified_name)
640                } else {
641                    format!("CALL {}({})", qualified_name, parameters.join(", "))
642                }
643            }
644            Some(Source::Function(func)) => {
645                let qualified_name = func.qualified_name();
646                if parameters.is_empty() {
647                    format!("SELECT {}() as result", qualified_name)
648                } else {
649                    format!(
650                        "SELECT {}({}) as result",
651                        qualified_name,
652                        parameters.join(", ")
653                    )
654                }
655            }
656            _ => panic!("generate_call_sql can only be used with procedure or function sources"),
657        }
658    }
659
660    /// Generate the SQL for this query with thread-safe caching for performance
661    pub fn to_sql(&self) -> String {
662        // Check cache first
663        let mut hasher = std::collections::hash_map::DefaultHasher::new();
664        self.hash(&mut hasher);
665        let hash = hasher.finish();
666
667        // Try to get from cache
668        if let Some(cache) = QUERY_CACHE.get() {
669            if let Some(cached_sql) = cache.get(hash) {
670                return cached_sql;
671            }
672        }
673
674        // Generate SQL with optimized string building
675        let sql = self.generate_sql_optimized();
676
677        // Cache the result in thread-safe manner
678        if let Some(cache) = QUERY_CACHE.get() {
679            cache.insert(hash, sql.clone());
680        }
681
682        sql
683    }
684
685    /// Optimized SQL generation using Cow and pre-allocated capacity
686    fn generate_sql_optimized(&self) -> String {
687        // Pre-allocate with reasonable capacity
688        let mut sql = String::with_capacity(512);
689
690        // Use Cow for static strings to avoid allocations
691        let select_keyword: Cow<'static, str> = Cow::Borrowed("SELECT");
692        let from_keyword: Cow<'static, str> = Cow::Borrowed(" FROM ");
693        let where_keyword: Cow<'static, str> = Cow::Borrowed(" WHERE ");
694        let group_by_keyword: Cow<'static, str> = Cow::Borrowed(" GROUP BY ");
695        let having_keyword: Cow<'static, str> = Cow::Borrowed(" HAVING ");
696        let order_by_keyword: Cow<'static, str> = Cow::Borrowed(" ORDER BY ");
697        let limit_keyword: Cow<'static, str> = Cow::Borrowed(" LIMIT ");
698        let offset_keyword: Cow<'static, str> = Cow::Borrowed(" OFFSET ");
699
700        // SELECT
701        if self.select_columns.is_empty() {
702            sql.push_str("SELECT *");
703        } else {
704            // Optimize column formatting
705            let cols: Vec<Cow<'_, str>> = self
706                .select_columns
707                .iter()
708                .map(|c| {
709                    if c.contains('(') || c.contains(' ') || c.contains('.') {
710                        Cow::Borrowed(c.as_str()) // Aggregates, complex expressions, or qualified names
711                    } else {
712                        Cow::Owned(format!("\"{}\"", c)) // Simple column names only
713                    }
714                })
715                .collect();
716            use std::fmt::Write;
717            write!(sql, "{} {}", select_keyword, cols.join(", ")).unwrap();
718        }
719
720        // FROM (skip for procedure/function calls)
721        if let Some(ref source) = self.from_source {
722            match source {
723                Source::Procedure(_) | Source::Function(_) => {
724                    // For procedure/function calls, we shouldn't generate SELECT FROM syntax
725                    // Use generate_call_sql instead
726                    return "-- Use generate_call_sql() for procedure/function calls".to_string();
727                }
728                _ => {
729                    sql.push_str(&from_keyword);
730                    sql.push_str(&source.qualified_name());
731                }
732            }
733        }
734
735        // JOINs
736        for join in &self.joins {
737            let join_keyword = match join.join_type {
738                JoinType::Inner => " INNER JOIN ",
739                JoinType::Left => " LEFT JOIN ",
740                JoinType::Right => " RIGHT JOIN ",
741                JoinType::Full => " FULL OUTER JOIN ",
742            };
743            sql.push_str(join_keyword);
744            sql.push_str(&join.target.qualified_name());
745            sql.push_str(" ON ");
746            sql.push_str(&join.condition);
747        }
748
749        // WHERE
750        if let Some(ref where_clause) = self.where_clause {
751            sql.push_str(&where_keyword);
752            sql.push_str(where_clause);
753        }
754
755        // GROUP BY
756        if !self.group_by.is_empty() {
757            sql.push_str(&group_by_keyword);
758            let group_cols: Vec<Cow<'_, str>> = self
759                .group_by
760                .iter()
761                .map(|c| {
762                    if c.contains('.') {
763                        Cow::Borrowed(c.as_str()) // Already qualified
764                    } else {
765                        Cow::Owned(format!("\"{}\"", c)) // Simple column name
766                    }
767                })
768                .collect();
769            sql.push_str(&group_cols.join(", "));
770        }
771
772        // HAVING
773        if let Some(ref having_clause) = self.having_clause {
774            sql.push_str(&having_keyword);
775            sql.push_str(having_clause);
776        }
777
778        // ORDER BY
779        if !self.order_by.is_empty() {
780            sql.push_str(&order_by_keyword);
781            let order_cols: Vec<Cow<'_, str>> = self
782                .order_by
783                .iter()
784                .map(|c| {
785                    if c.contains('.') || c.contains(' ') {
786                        Cow::Borrowed(c.as_str()) // Already qualified or complex
787                    } else {
788                        Cow::Owned(format!("\"{}\"", c)) // Simple column name
789                    }
790                })
791                .collect();
792            sql.push_str(&order_cols.join(", "));
793        }
794
795        // LIMIT
796        if let Some(limit) = self.limit {
797            sql.push_str(&limit_keyword);
798            sql.push_str(&limit.to_string());
799        }
800
801        // OFFSET
802        if let Some(offset) = self.offset {
803            sql.push_str(&offset_keyword);
804            sql.push_str(&offset.to_string());
805        }
806
807        sql
808    }
809
810    /// Get cache statistics for monitoring
811    pub fn cache_stats() -> (usize, usize) {
812        QUERY_CACHE
813            .get()
814            .map(|cache| cache.stats())
815            .unwrap_or((0, 0))
816    }
817
818    /// Initialize the query cache (call once at startup)
819    pub fn init_cache() {
820        let _ = QUERY_CACHE.set(Arc::new(QueryCache::new()));
821    }
822
823    /// Generate all SQL statements for this query (including refresh for materialized views)
824    pub fn generate_all_sql(&self) -> Vec<String> {
825        let mut statements = Vec::new();
826
827        // Main query
828        statements.push(self.to_sql());
829
830        // Refresh materialized view if applicable
831        if let Some(refresh_sql) = self.generate_refresh_sql() {
832            statements.push(refresh_sql);
833        }
834
835        statements
836    }
837}
838
839impl Default for Query {
840    fn default() -> Self {
841        Self::new()
842    }
843}
844
845/// Type-safe column reference for use in queries
846#[derive(Debug, Clone)]
847pub struct Column<T> {
848    pub name: String,
849    pub table: Option<String>,
850    pub schema: Option<String>,
851    _phantom: std::marker::PhantomData<T>,
852}
853
854impl<T> Column<T> {
855    /// Create a new column reference
856    pub fn new(name: impl Into<String>) -> Self {
857        Self {
858            name: name.into(),
859            table: None,
860            schema: None,
861            _phantom: std::marker::PhantomData,
862        }
863    }
864
865    /// Set the table for this column
866    pub fn from_table(mut self, table: impl Into<String>) -> Self {
867        self.table = Some(table.into());
868        self
869    }
870
871    /// Set the schema for this column
872    pub fn from_schema(mut self, schema: impl Into<String>) -> Self {
873        self.schema = Some(schema.into());
874        self
875    }
876
877    /// Get the fully qualified column name
878    pub fn qualified_name(&self) -> String {
879        let mut parts = Vec::new();
880
881        if let Some(ref schema) = self.schema {
882            parts.push(format!("\"{}\"", schema));
883        }
884
885        if let Some(ref table) = self.table {
886            parts.push(format!("\"{}\"", table));
887        }
888
889        parts.push(format!("\"{}\"", self.name));
890
891        parts.join(".")
892    }
893
894    /// Create an equality comparison
895    pub fn eq(self, _value: T) -> String {
896        format!("{} = ?", self.qualified_name())
897    }
898
899    /// Create a greater than comparison
900    pub fn gt(self, _value: T) -> String {
901        format!("{} > ?", self.qualified_name())
902    }
903
904    /// Create a less than comparison
905    pub fn lt(self, _value: T) -> String {
906        format!("{} < ?", self.qualified_name())
907    }
908
909    /// Create a LIKE comparison
910    pub fn like(self, _pattern: impl Into<String>) -> String {
911        format!("{} LIKE ?", self.qualified_name())
912    }
913
914    /// Create an IN comparison
915    pub fn in_(self, _values: Vec<T>) -> String {
916        let placeholders: Vec<String> = (0.._values.len()).map(|_| "?".to_string()).collect();
917        format!("{} IN ({})", self.qualified_name(), placeholders.join(", "))
918    }
919}