Skip to main content

ignis_db/dsl/
clean_projection.rs

1//! Clean, ergonomic projections without boilerplate
2
3use super::TypedQuery;
4use std::marker::PhantomData;
5
6/// A clean row accessor that returns values directly (no .into() needed)
7pub struct CleanRow {
8    source_name: String,
9    schema: Option<String>,
10}
11
12impl CleanRow {
13    pub fn new(source_name: String, schema: Option<String>) -> Self {
14        Self {
15            source_name,
16            schema,
17        }
18    }
19
20    /// Get column values directly as their target types
21    pub fn column<T>(&self, name: &str) -> CleanColumn<T> {
22        CleanColumn {
23            name: name.to_string(),
24            source_name: self.source_name.clone(),
25            schema: self.schema.clone(),
26            _phantom: PhantomData,
27        }
28    }
29
30    // Common column accessors - in real implementation would extract from row data
31    pub fn id(&self) -> i32 {
32        0
33    }
34    pub fn name(&self) -> String {
35        String::new()
36    }
37    pub fn email(&self) -> String {
38        String::new()
39    }
40    pub fn age(&self) -> i32 {
41        0
42    }
43    pub fn active(&self) -> bool {
44        false
45    }
46    pub fn title(&self) -> String {
47        String::new()
48    }
49    pub fn views(&self) -> i32 {
50        0
51    }
52    pub fn user_id(&self) -> i32 {
53        0
54    }
55    pub fn created_at(&self) -> chrono::DateTime<chrono::Utc> {
56        chrono::Utc::now()
57    }
58}
59
60/// A column that can be extracted cleanly
61pub struct CleanColumn<T> {
62    name: String,
63    source_name: String,
64    schema: Option<String>,
65    _phantom: PhantomData<T>,
66}
67
68impl<T> CleanColumn<T> {
69    pub fn qualified_name(&self) -> String {
70        if let Some(ref schema) = self.schema {
71            format!("\"{}\".\"{}\".\"{}\"", schema, self.source_name, self.name)
72        } else {
73            format!("\"{}\".\"{}\"", self.source_name, self.name)
74        }
75    }
76}
77
78/// Enhanced typed query with clean projection syntax
79impl TypedQuery {
80    /// Ultra-clean struct projection (no .into() needed!)
81    pub fn select_clean<S, P>(self, projection: P) -> CleanProjectedQuery<S>
82    where
83        P: Fn(CleanRow) -> S + 'static,
84        S: AutoProjection,
85    {
86        let _row = CleanRow::new(
87            self.source
88                .as_ref()
89                .map(|s| s.name().to_string())
90                .unwrap_or_default(),
91            self.source
92                .as_ref()
93                .and_then(|s| s.schema().map(|s| s.to_string())),
94        );
95
96        // For demo, we'll use the auto-projection columns
97        let projection_sql = S::column_names();
98
99        CleanProjectedQuery {
100            base_query: self,
101            projection_sql,
102            _projection: Box::new(projection),
103            _phantom: PhantomData,
104        }
105    }
106
107    /// Automatic projection based on struct field names
108    pub fn select_auto<S>(self) -> CleanProjectedQuery<S>
109    where
110        S: AutoProjection + Default,
111    {
112        let projection_sql = S::column_names();
113
114        CleanProjectedQuery {
115            base_query: self,
116            projection_sql,
117            _projection: Box::new(|_| S::default()),
118            _phantom: PhantomData,
119        }
120    }
121}
122
123/// A query with clean projection
124pub struct CleanProjectedQuery<T> {
125    base_query: TypedQuery,
126    projection_sql: Vec<String>,
127    _projection: Box<dyn Fn(CleanRow) -> T>,
128    _phantom: PhantomData<T>,
129}
130
131impl<T> CleanProjectedQuery<T> {
132    /// Generate SQL for the clean projected query
133    pub fn to_sql(&self) -> String {
134        let mut sql = String::from("SELECT ");
135        sql.push_str(&self.projection_sql.join(", "));
136
137        if let Some(ref source) = self.base_query.source {
138            sql.push_str(" FROM ");
139            sql.push_str(&source.qualified_name());
140        }
141
142        if let Some(ref conditions) = self.base_query.where_conditions {
143            sql.push_str(" WHERE ");
144            sql.push_str(&conditions.to_sql());
145        }
146
147        if !self.base_query.order_by.is_empty() {
148            sql.push_str(" ORDER BY ");
149            sql.push_str(&self.base_query.order_by.join(", "));
150        }
151
152        if let Some(_limit) = self.base_query.limit {
153            sql.push_str(&format!(" LIMIT ?"));
154        }
155
156        if let Some(_offset) = self.base_query.offset {
157            sql.push_str(&format!(" OFFSET ?"));
158        }
159
160        sql
161    }
162
163    /// Execute and collect results (mock implementation)
164    pub fn collect<C: FromIterator<T>>(self) -> C {
165        // In real implementation, this would execute SQL and map results
166        std::iter::empty().collect()
167    }
168}
169
170/// Trait for automatic field mapping
171pub trait AutoProjection {
172    /// Get the column names for this projection
173    fn column_names() -> Vec<String>;
174
175    /// Map from database row to struct (in real implementation)
176    fn from_row(row: &CleanRow) -> Self;
177}
178
179/// Macro to automatically implement AutoProjection
180#[macro_export]
181macro_rules! auto_projection {
182    ($struct_name:ident { $($field:ident: $column:ident),* $(,)? }) => {
183        impl $crate::dsl::clean_projection::AutoProjection for $struct_name {
184            fn column_names() -> Vec<String> {
185                vec![
186                    $(
187                        format!("\"{}\"", stringify!($column)),
188                    )*
189                ]
190            }
191
192            fn from_row(row: &$crate::dsl::clean_projection::CleanRow) -> Self {
193                Self {
194                    $(
195                        $field: row.$column(),
196                    )*
197                }
198            }
199        }
200    };
201
202    // Simplified version where field names match column names
203    ($struct_name:ident { $($field:ident),* $(,)? }) => {
204        impl $crate::dsl::clean_projection::AutoProjection for $struct_name {
205            fn column_names() -> Vec<String> {
206                vec![
207                    $(
208                        format!("\"{}\"", stringify!($field)),
209                    )*
210                ]
211            }
212
213            fn from_row(row: &$crate::dsl::clean_projection::CleanRow) -> Self {
214                Self {
215                    $(
216                        $field: row.$field(),
217                    )*
218                }
219            }
220        }
221    };
222}
223
224/// Shorthand query builders
225impl TypedQuery {
226    /// Super clean syntax for common patterns
227    pub fn select<S>(self) -> CleanProjectedQuery<S>
228    where
229        S: AutoProjection + Default,
230    {
231        self.select_auto()
232    }
233
234    /// Clean where + select in one call
235    pub fn where_select<S, W>(self, where_clause: W) -> CleanProjectedQuery<S>
236    where
237        W: Into<super::WhereCondition>,
238        S: AutoProjection + Default,
239    {
240        self.where_clause(where_clause.into()).select()
241    }
242}