Skip to main content

ignis_db/dsl/
typed_query.rs

1//! Type-safe query builder with compile-time column validation
2
3use super::{OrderBy, Source, TypedColumn, WhereCondition};
4use crate::schema::{Table, View};
5
6/// Trait for column-like objects that can be used in queries
7pub trait ColumnLike {
8    /// Get the qualified column name
9    fn qualified_name(&self) -> String;
10}
11
12impl<T> ColumnLike for TypedColumn<T> {
13    fn qualified_name(&self) -> String {
14        self.qualified_name()
15    }
16}
17
18/// A type-safe query builder (generic over column types)
19#[derive(Debug, Clone)]
20pub struct TypedQuery {
21    /// The source table or view
22    pub source: Option<Source>,
23    /// Selected columns (as strings for flexibility)
24    pub select_columns: Vec<String>,
25    /// WHERE conditions (type-safe)
26    pub where_conditions: Option<WhereCondition>,
27    /// ORDER BY clauses (as strings for flexibility)
28    pub order_by: Vec<String>,
29    /// LIMIT clause
30    pub limit: Option<usize>,
31    /// OFFSET clause
32    pub offset: Option<usize>,
33}
34
35impl TypedQuery {
36    /// Create a new typed query
37    pub fn new() -> Self {
38        Self {
39            source: None,
40            select_columns: Vec::new(),
41            where_conditions: None,
42            order_by: Vec::new(),
43            limit: None,
44            offset: None,
45        }
46    }
47
48    /// Set the source table
49    pub fn from_table(mut self, table: Table) -> Self {
50        self.source = Some(Source::Table(table));
51        self
52    }
53
54    /// Set the source view
55    pub fn from_view(mut self, view: View) -> Self {
56        self.source = Some(Source::View(view));
57        self
58    }
59
60    /// Select specific columns by converting them to strings
61    pub fn select_columns_from<I>(mut self, columns: I) -> Self
62    where
63        I: IntoIterator,
64        I::Item: Into<String>,
65    {
66        self.select_columns = columns.into_iter().map(|c| c.into()).collect();
67        self
68    }
69
70    /// Add a single column to select (accepts any TypedColumn<T>)
71    pub fn select_column<T>(mut self, column: TypedColumn<T>) -> Self {
72        self.select_columns.push(column.qualified_name());
73        self
74    }
75
76    /// Set WHERE conditions (type-safe)
77    pub fn where_clause(mut self, condition: WhereCondition) -> Self {
78        self.where_conditions = Some(condition);
79        self
80    }
81
82    /// Add ORDER BY (accepts any OrderBy<T>)
83    pub fn order_by<T>(mut self, order: OrderBy<T>) -> Self {
84        self.order_by.push(order.to_sql());
85        self
86    }
87
88    /// Set LIMIT
89    pub fn limit(mut self, limit: usize) -> Self {
90        self.limit = Some(limit);
91        self
92    }
93
94    /// Set OFFSET
95    pub fn offset(mut self, offset: usize) -> Self {
96        self.offset = Some(offset);
97        self
98    }
99
100    /// Generate SQL from the typed query
101    pub fn to_sql(&self) -> String {
102        let mut sql = String::from("SELECT ");
103
104        // Add columns
105        if self.select_columns.is_empty() {
106            sql.push('*');
107        } else {
108            sql.push_str(&self.select_columns.join(", "));
109        }
110
111        // Add FROM clause
112        if let Some(ref source) = self.source {
113            sql.push_str(" FROM ");
114            sql.push_str(&source.qualified_name());
115        }
116
117        // Add WHERE clause
118        if let Some(ref conditions) = self.where_conditions {
119            sql.push_str(" WHERE ");
120            sql.push_str(&conditions.to_sql());
121        }
122
123        // Add ORDER BY
124        if !self.order_by.is_empty() {
125            sql.push_str(" ORDER BY ");
126            sql.push_str(&self.order_by.join(", "));
127        }
128
129        // Add LIMIT
130        if let Some(_limit) = self.limit {
131            sql.push_str(" LIMIT ?");
132        }
133
134        // Add OFFSET
135        if let Some(_offset) = self.offset {
136            sql.push_str(" OFFSET ?");
137        }
138
139        sql
140    }
141}
142
143/// Builder methods for creating typed queries from macro-generated modules
144pub trait TypedQueryBuilder {
145    /// Start a new query for this source
146    fn query() -> TypedQuery;
147}