Skip to main content

ignis_db/dsl/
typed_column.rs

1//! Type-safe column references for compile-time validation
2
3use crate::common::qualified_column_name;
4use crate::schema::Column as SchemaColumn;
5use std::marker::PhantomData;
6
7/// A type-safe column reference that preserves type information
8#[derive(Debug, Clone)]
9pub struct TypedColumn<T> {
10    /// The actual column data
11    pub column: SchemaColumn,
12    /// The table or view this column belongs to
13    pub source_name: String,
14    /// Schema name if present
15    pub schema: Option<String>,
16    /// Phantom data to preserve type information
17    _phantom: PhantomData<T>,
18}
19
20impl<T> TypedColumn<T> {
21    /// Create a new typed column
22    pub fn new(column: SchemaColumn, source_name: String, schema: Option<String>) -> Self {
23        Self {
24            column,
25            source_name,
26            schema,
27            _phantom: PhantomData,
28        }
29    }
30
31    /// Get the column name
32    pub fn name(&self) -> &str {
33        &self.column.name
34    }
35
36    /// Get the fully qualified column name
37    pub fn qualified_name(&self) -> String {
38        qualified_column_name(self.schema.as_deref(), &self.source_name, &self.column.name)
39    }
40
41    /// Create an equality condition
42    pub fn eq(&self, value: T) -> WhereCondition
43    where
44        T: ToString,
45    {
46        WhereCondition::Eq(self.qualified_name(), value.to_string())
47    }
48
49    /// Create a greater than condition
50    pub fn gt(&self, value: T) -> WhereCondition
51    where
52        T: ToString,
53    {
54        WhereCondition::Gt(self.qualified_name(), value.to_string())
55    }
56
57    /// Create a less than condition
58    pub fn lt(&self, value: T) -> WhereCondition
59    where
60        T: ToString,
61    {
62        WhereCondition::Lt(self.qualified_name(), value.to_string())
63    }
64
65    /// Create an IN condition
66    pub fn in_values(&self, values: Vec<T>) -> WhereCondition
67    where
68        T: ToString,
69    {
70        WhereCondition::In(
71            self.qualified_name(),
72            values.into_iter().map(|v| v.to_string()).collect(),
73        )
74    }
75
76    /// Create a LIKE condition (for string columns)
77    pub fn like(&self, pattern: &str) -> WhereCondition {
78        WhereCondition::Like(self.qualified_name(), pattern.to_string())
79    }
80
81    /// Create an IS NULL condition
82    pub fn is_null(&self) -> WhereCondition {
83        WhereCondition::IsNull(self.qualified_name())
84    }
85
86    /// Create an IS NOT NULL condition
87    pub fn is_not_null(&self) -> WhereCondition {
88        WhereCondition::IsNotNull(self.qualified_name())
89    }
90}
91
92/// Type-safe WHERE conditions
93#[derive(Debug, Clone)]
94pub enum WhereCondition {
95    Eq(String, String),
96    Gt(String, String),
97    Lt(String, String),
98    Gte(String, String),
99    Lte(String, String),
100    In(String, Vec<String>),
101    Like(String, String),
102    IsNull(String),
103    IsNotNull(String),
104    And(Box<WhereCondition>, Box<WhereCondition>),
105    Or(Box<WhereCondition>, Box<WhereCondition>),
106}
107
108impl WhereCondition {
109    /// Combine with AND
110    pub fn and(self, other: WhereCondition) -> WhereCondition {
111        WhereCondition::And(Box::new(self), Box::new(other))
112    }
113
114    /// Combine with OR
115    pub fn or(self, other: WhereCondition) -> WhereCondition {
116        WhereCondition::Or(Box::new(self), Box::new(other))
117    }
118
119    /// Convert to SQL string with proper escaping
120    /// WARNING: This method should only be used for trusted column names
121    /// For user-provided data, use parameterized queries instead
122    pub fn to_sql(&self) -> String {
123        match self {
124            WhereCondition::Eq(col, _val) => format!("{} = ?", col),
125            WhereCondition::Gt(col, _val) => format!("{} > ?", col),
126            WhereCondition::Lt(col, _val) => format!("{} < ?", col),
127            WhereCondition::Gte(col, _val) => format!("{} >= ?", col),
128            WhereCondition::Lte(col, _val) => format!("{} <= ?", col),
129            WhereCondition::In(col, vals) => {
130                let placeholders = (0..vals.len()).map(|_| "?").collect::<Vec<_>>().join(", ");
131                format!("{} IN ({})", col, placeholders)
132            }
133            WhereCondition::Like(col, _pattern) => format!("{} LIKE ?", col),
134            WhereCondition::IsNull(col) => format!("{} IS NULL", col),
135            WhereCondition::IsNotNull(col) => format!("{} IS NOT NULL", col),
136            WhereCondition::And(left, right) => {
137                format!("({} AND {})", left.to_sql(), right.to_sql())
138            }
139            WhereCondition::Or(left, right) => format!("({} OR {})", left.to_sql(), right.to_sql()),
140        }
141    }
142
143    /// Get the values for parameter binding
144    /// This method returns the actual values that should be bound to the placeholders
145    pub fn get_bind_values(&self) -> Vec<String> {
146        match self {
147            WhereCondition::Eq(_, val) => vec![val.clone()],
148            WhereCondition::Gt(_, val) => vec![val.clone()],
149            WhereCondition::Lt(_, val) => vec![val.clone()],
150            WhereCondition::Gte(_, val) => vec![val.clone()],
151            WhereCondition::Lte(_, val) => vec![val.clone()],
152            WhereCondition::In(_, vals) => vals.clone(),
153            WhereCondition::Like(_, pattern) => vec![pattern.clone()],
154            WhereCondition::IsNull(_) => vec![],
155            WhereCondition::IsNotNull(_) => vec![],
156            WhereCondition::And(left, right) => {
157                let mut values = left.get_bind_values();
158                values.extend(right.get_bind_values());
159                values
160            }
161            WhereCondition::Or(left, right) => {
162                let mut values = left.get_bind_values();
163                values.extend(right.get_bind_values());
164                values
165            }
166        }
167    }
168}
169
170/// Type-safe column selector for queries
171#[derive(Debug, Clone)]
172pub struct ColumnSelector<T> {
173    columns: Vec<TypedColumn<T>>,
174}
175
176impl<T> ColumnSelector<T> {
177    /// Create a new column selector
178    pub fn new() -> Self {
179        Self {
180            columns: Vec::new(),
181        }
182    }
183
184    /// Add a column to select
185    pub fn column(mut self, column: TypedColumn<T>) -> Self {
186        self.columns.push(column);
187        self
188    }
189
190    /// Add multiple columns
191    pub fn columns(mut self, columns: Vec<TypedColumn<T>>) -> Self {
192        self.columns.extend(columns);
193        self
194    }
195
196    /// Get the column names
197    pub fn get_names(&self) -> Vec<String> {
198        self.columns.iter().map(|c| c.name().to_string()).collect()
199    }
200
201    /// Get the qualified column names
202    pub fn get_qualified_names(&self) -> Vec<String> {
203        self.columns.iter().map(|c| c.qualified_name()).collect()
204    }
205}
206
207/// Type-safe order by clause
208#[derive(Debug, Clone)]
209pub struct OrderBy<T> {
210    column: TypedColumn<T>,
211    direction: OrderDirection,
212}
213
214#[derive(Debug, Clone)]
215pub enum OrderDirection {
216    Asc,
217    Desc,
218}
219
220impl<T> OrderBy<T> {
221    /// Create ascending order
222    pub fn asc(column: TypedColumn<T>) -> Self {
223        Self {
224            column,
225            direction: OrderDirection::Asc,
226        }
227    }
228
229    /// Create descending order
230    pub fn desc(column: TypedColumn<T>) -> Self {
231        Self {
232            column,
233            direction: OrderDirection::Desc,
234        }
235    }
236
237    /// Convert to SQL string
238    pub fn to_sql(&self) -> String {
239        let dir = match self.direction {
240            OrderDirection::Asc => "ASC",
241            OrderDirection::Desc => "DESC",
242        };
243        format!("{} {}", self.column.qualified_name(), dir)
244    }
245}
246
247/// Convert TypedColumn to String for flexible query building
248impl<T> Into<String> for TypedColumn<T> {
249    fn into(self) -> String {
250        self.qualified_name()
251    }
252}
253
254/// Convert reference to TypedColumn to String
255impl<T> Into<String> for &TypedColumn<T> {
256    fn into(self) -> String {
257        self.qualified_name()
258    }
259}