Skip to main content

ignis_db/dsl/
projection.rs

1//! LINQ-style projections for type-safe database queries
2
3use super::{TypedColumn, TypedQuery};
4use std::marker::PhantomData;
5
6/// A projection that can transform query results
7pub trait Projection<T> {
8    type Output;
9
10    /// Apply the projection to transform the input type
11    fn project(&self, input: T) -> Self::Output;
12
13    /// Get the SQL column list for this projection
14    fn sql_columns(&self) -> Vec<String>;
15}
16
17/// A selector for extracting single fields
18pub struct FieldSelector<T, F> {
19    selector: fn(T) -> F,
20    column_name: String,
21    _phantom: PhantomData<(T, F)>,
22}
23
24impl<T, F> FieldSelector<T, F> {
25    pub fn new(selector: fn(T) -> F, column_name: String) -> Self {
26        Self {
27            selector,
28            column_name,
29            _phantom: PhantomData,
30        }
31    }
32}
33
34impl<T, F> Projection<T> for FieldSelector<T, F> {
35    type Output = F;
36
37    fn project(&self, input: T) -> Self::Output {
38        (self.selector)(input)
39    }
40
41    fn sql_columns(&self) -> Vec<String> {
42        vec![self.column_name.clone()]
43    }
44}
45
46/// A selector for creating new structs
47pub struct StructSelector<T, S> {
48    selector: fn(T) -> S,
49    column_names: Vec<String>,
50    _phantom: PhantomData<(T, S)>,
51}
52
53impl<T, S> StructSelector<T, S> {
54    pub fn new(selector: fn(T) -> S, column_names: Vec<String>) -> Self {
55        Self {
56            selector,
57            column_names,
58            _phantom: PhantomData,
59        }
60    }
61}
62
63impl<T, S> Projection<T> for StructSelector<T, S> {
64    type Output = S;
65
66    fn project(&self, input: T) -> Self::Output {
67        (self.selector)(input)
68    }
69
70    fn sql_columns(&self) -> Vec<String> {
71        self.column_names.clone()
72    }
73}
74
75/// A typed row accessor for LINQ-style operations
76pub struct TypedRow {
77    source_name: String,
78    schema: Option<String>,
79}
80
81impl TypedRow {
82    pub fn new(source_name: String, schema: Option<String>) -> Self {
83        Self {
84            source_name,
85            schema,
86        }
87    }
88
89    /// Get a typed column accessor
90    pub fn column<T>(&self, name: &str) -> TypedColumn<T> {
91        TypedColumn::new(
92            crate::schema::Column::new(name.to_string(), Default::default()),
93            self.source_name.clone(),
94            self.schema.clone(),
95        )
96    }
97
98    // Common column accessors for examples and convenience
99    pub fn id(&self) -> TypedColumn<i32> {
100        self.column("id")
101    }
102    pub fn name(&self) -> TypedColumn<String> {
103        self.column("name")
104    }
105    pub fn email(&self) -> TypedColumn<String> {
106        self.column("email")
107    }
108    pub fn age(&self) -> TypedColumn<i32> {
109        self.column("age")
110    }
111    pub fn active(&self) -> TypedColumn<bool> {
112        self.column("active")
113    }
114    pub fn title(&self) -> TypedColumn<String> {
115        self.column("title")
116    }
117    pub fn views(&self) -> TypedColumn<i32> {
118        self.column("views")
119    }
120    pub fn user_id(&self) -> TypedColumn<i32> {
121        self.column("user_id")
122    }
123    pub fn created_at(&self) -> TypedColumn<chrono::DateTime<chrono::Utc>> {
124        self.column("created_at")
125    }
126}
127
128/// Enhanced typed query with LINQ-style projections
129impl TypedQuery {
130    /// Select a single field (equivalent to C# Select(p => p.Name))
131    pub fn select_field<F, P>(self, projection: P) -> ProjectedQuery<F>
132    where
133        P: Fn(TypedRow) -> TypedColumn<F> + 'static,
134    {
135        let row = TypedRow::new(
136            self.source
137                .as_ref()
138                .map(|s| s.name().to_string())
139                .unwrap_or_default(),
140            self.source
141                .as_ref()
142                .and_then(|s| s.schema().map(|s| s.to_string())),
143        );
144
145        let column = projection(row);
146        let column_sql = column.qualified_name();
147
148        ProjectedQuery {
149            base_query: self,
150            projection_sql: vec![column_sql],
151            _phantom: PhantomData,
152        }
153    }
154
155    /// Select into a custom struct (equivalent to C# Select(p => new PersonSummary { ... }))
156    pub fn select_into<S, P>(self, _projection: P) -> ProjectedQuery<S>
157    where
158        P: Fn(TypedRow) -> S + 'static,
159        S: ProjectionTarget,
160    {
161        let row = TypedRow::new(
162            self.source
163                .as_ref()
164                .map(|s| s.name().to_string())
165                .unwrap_or_default(),
166            self.source
167                .as_ref()
168                .and_then(|s| s.schema().map(|s| s.to_string())),
169        );
170
171        // This is where we'd analyze the projection to extract column names
172        // For now, we'll use a simpler approach with the ProjectionTarget trait
173        let projection_sql = S::required_columns(&row);
174
175        ProjectedQuery {
176            base_query: self,
177            projection_sql,
178            _phantom: PhantomData,
179        }
180    }
181}
182
183/// A query with a projection applied
184pub struct ProjectedQuery<T> {
185    base_query: TypedQuery,
186    projection_sql: Vec<String>,
187    _phantom: PhantomData<T>,
188}
189
190impl<T> ProjectedQuery<T> {
191    /// Generate SQL for the projected query
192    pub fn to_sql(&self) -> String {
193        let mut sql = String::from("SELECT ");
194        sql.push_str(&self.projection_sql.join(", "));
195
196        if let Some(ref source) = self.base_query.source {
197            sql.push_str(" FROM ");
198            sql.push_str(&source.qualified_name());
199        }
200
201        if let Some(ref conditions) = self.base_query.where_conditions {
202            sql.push_str(" WHERE ");
203            sql.push_str(&conditions.to_sql());
204        }
205
206        if !self.base_query.order_by.is_empty() {
207            sql.push_str(" ORDER BY ");
208            sql.push_str(&self.base_query.order_by.join(", "));
209        }
210
211        if let Some(_limit) = self.base_query.limit {
212            sql.push_str(" LIMIT ?");
213        }
214
215        if let Some(_offset) = self.base_query.offset {
216            sql.push_str(" OFFSET ?");
217        }
218
219        sql
220    }
221
222    /// Simulate collecting results (in real implementation, this would execute the query)
223    pub fn collect<C: FromIterator<T>>(self) -> C {
224        // This would actually execute the query and map results
225        // For demo purposes, we'll return an empty collection
226        std::iter::empty().collect()
227    }
228}
229
230/// Trait for types that can be used as projection targets
231pub trait ProjectionTarget {
232    /// Get the list of required columns for this projection
233    fn required_columns(row: &TypedRow) -> Vec<String>;
234}
235
236/// Macro to automatically implement ProjectionTarget
237#[macro_export]
238macro_rules! projection_target {
239    ($struct_name:ident { $($field:ident: $column:ident),* $(,)? }) => {
240        impl $crate::dsl::projection::ProjectionTarget for $struct_name {
241            fn required_columns(row: &$crate::dsl::projection::TypedRow) -> Vec<String> {
242                vec![
243                    $(
244                        row.$column().qualified_name(),
245                    )*
246                ]
247            }
248        }
249    };
250}
251
252/// Macro for anonymous projections (like C# anonymous objects)
253#[macro_export]
254macro_rules! select_anonymous {
255    ($query:expr; $($column:ident),* $(,)?) => {{
256        let row = $crate::dsl::projection::TypedRow::new(
257            String::new(), // Would be filled from query context
258            None
259        );
260        let columns = vec![
261            $(
262                row.$column().qualified_name(),
263            )*
264        ];
265        $crate::dsl::projection::ProjectedQuery {
266            base_query: $query,
267            projection_sql: columns,
268            _phantom: std::marker::PhantomData,
269        }
270    }};
271}