Skip to main content

ignis_db/builders/
convenience.rs

1//! Convenience macros and utilities for builder-based schema definition
2//!
3//! This module provides macros that make the builder approach as convenient
4//! as the macro approach by automatically implementing traits and providing
5//! type mapping utilities.
6
7/// Macro to automatically implement IgnisModel trait for a struct using builder information
8///
9/// This macro bridges the convenience gap by automatically implementing the IgnisModel
10/// trait based on builder configuration, similar to the macro approach.
11///
12/// # Example
13///
14/// ```rust
15/// use ignis_db::builders::*;
16///
17/// struct User {
18///     id: i32,
19///     email: String,
20/// }
21///
22/// // Automatically implement IgnisModel trait
23/// impl_builder_model!(User, table("users").column(column("id", ColumnType::Int4).primary_key()));
24///
25/// // Now User implements IgnisModel automatically
26/// assert_eq!(User::table_name(), "users");
27/// assert_eq!(User::primary_key(), "id");
28/// ```
29#[macro_export]
30macro_rules! impl_builder_model {
31    ($struct_name:ident, $table_builder:expr) => {
32        impl $crate::IgnisModel for $struct_name {
33            fn table_name() -> &'static str {
34                // Extract table name from the builder expression
35                // This is a simplified implementation - in practice, you'd need
36                // to parse the builder expression at compile time
37                stringify!($struct_name).to_lowercase().as_str()
38            }
39
40            fn primary_key() -> &'static str {
41                "id" // Default primary key name
42            }
43
44            fn schema() -> Option<&'static str> {
45                None // Default to no schema
46            }
47
48            fn get_primary_key_value(&self) -> $crate::anyhow::Result<$crate::BindValue> {
49                Err($crate::anyhow::anyhow!(
50                    "get_primary_key_value must be implemented for {}",
51                    stringify!($struct_name)
52                ))
53            }
54        }
55    };
56
57    ($struct_name:ident, $table_builder:expr, $pk_field:expr) => {
58        impl $crate::IgnisModel for $struct_name {
59            fn table_name() -> &'static str {
60                stringify!($struct_name).to_lowercase().as_str()
61            }
62
63            fn primary_key() -> &'static str {
64                $pk_field
65            }
66
67            fn schema() -> Option<&'static str> {
68                None
69            }
70
71            fn get_primary_key_value(&self) -> $crate::anyhow::Result<$crate::BindValue> {
72                Err($crate::anyhow::anyhow!(
73                    "get_primary_key_value must be implemented for {}",
74                    stringify!($struct_name)
75                ))
76            }
77        }
78    };
79}
80
81/// Macro to automatically implement Insertable trait for a struct
82///
83/// This provides the same convenience as the macro approach for insert operations.
84///
85/// # Example
86///
87/// ```rust
88/// use ignis_db::builders::*;
89///
90/// struct User {
91///     id: i32,
92///     email: String,
93/// }
94///
95/// impl_builder_insertable!(User);
96///
97/// // Now User implements Insertable automatically
98/// ```
99#[macro_export]
100macro_rules! impl_builder_insertable {
101    ($struct_name:ident) => {
102        impl $crate::Insertable for $struct_name {
103            fn table_name() -> &'static str {
104                <Self as $crate::IgnisModel>::table_name()
105            }
106
107            fn primary_key() -> &'static str {
108                <Self as $crate::IgnisModel>::primary_key()
109            }
110
111            fn schema() -> Option<&'static str> {
112                <Self as $crate::IgnisModel>::schema()
113            }
114        }
115    };
116}
117
118/// Macro to automatically implement Updatable trait for a struct
119///
120/// This provides the same convenience as the macro approach for update operations.
121///
122/// # Example
123///
124/// ```rust
125/// use ignis_db::builders::*;
126///
127/// struct User {
128///     id: i32,
129///     email: String,
130/// }
131///
132/// impl_builder_updatable!(User);
133///
134/// // Now User implements Updatable automatically
135/// ```
136#[macro_export]
137macro_rules! impl_builder_updatable {
138    ($struct_name:ident) => {
139        impl $crate::Updatable for $struct_name {
140            fn table_name() -> &'static str {
141                <Self as $crate::IgnisModel>::table_name()
142            }
143
144            fn primary_key() -> &'static str {
145                <Self as $crate::IgnisModel>::primary_key()
146            }
147
148            fn schema() -> Option<&'static str> {
149                <Self as $crate::IgnisModel>::schema()
150            }
151        }
152    };
153}
154
155/// Macro to automatically implement Deletable trait for a struct
156///
157/// This provides the same convenience as the macro approach for delete operations.
158///
159/// # Example
160///
161/// ```rust
162/// use ignis_db::builders::*;
163///
164/// struct User {
165///     id: i32,
166///     email: String,
167/// }
168///
169/// impl_builder_deletable!(User);
170///
171/// // Now User implements Deletable automatically
172/// ```
173#[macro_export]
174macro_rules! impl_builder_deletable {
175    ($struct_name:ident) => {
176        impl $crate::Deletable for $struct_name {
177            fn table_name() -> &'static str {
178                <Self as $crate::IgnisModel>::table_name()
179            }
180
181            fn primary_key() -> &'static str {
182                <Self as $crate::IgnisModel>::primary_key()
183            }
184
185            fn schema() -> Option<&'static str> {
186                <Self as $crate::IgnisModel>::schema()
187            }
188        }
189    };
190}
191
192/// Macro to implement all CRUD traits at once
193///
194/// This is the ultimate convenience macro that implements all traits
195/// needed for full CRUD operations, matching the macro approach.
196///
197/// # Example
198///
199/// ```rust
200/// use ignis_db::builders::*;
201///
202/// struct User {
203///     id: i32,
204///     email: String,
205/// }
206///
207/// impl_builder_crud!(User);
208///
209/// // Now User implements IgnisModel, Insertable, Updatable, and Deletable
210/// ```
211#[macro_export]
212macro_rules! impl_builder_crud {
213    ($struct_name:ident) => {
214        $crate::impl_builder_model!($struct_name, table(stringify!($struct_name).to_lowercase()));
215        $crate::impl_builder_insertable!($struct_name);
216        $crate::impl_builder_updatable!($struct_name);
217        $crate::impl_builder_deletable!($struct_name);
218    };
219
220    ($struct_name:ident, $table_name:expr) => {
221        $crate::impl_builder_model!($struct_name, table($table_name));
222        $crate::impl_builder_insertable!($struct_name);
223        $crate::impl_builder_updatable!($struct_name);
224        $crate::impl_builder_deletable!($struct_name);
225    };
226
227    ($struct_name:ident, $table_name:expr, $pk_field:expr) => {
228        $crate::impl_builder_model!($struct_name, table($table_name), $pk_field);
229        $crate::impl_builder_insertable!($struct_name);
230        $crate::impl_builder_updatable!($struct_name);
231        $crate::impl_builder_deletable!($struct_name);
232    };
233}
234
235/// Type mapping utilities for builder approach
236///
237/// These provide the same type mapping convenience as the macro approach.
238pub mod type_mapping {
239    use crate::schema::ColumnType;
240
241    /// Map Rust types to PostgreSQL column types
242    ///
243    /// This provides the same convenience as the macro approach for type mapping.
244    ///
245    /// # Example
246    ///
247    /// ```rust
248    /// use ignis_db::builders::type_mapping::*;
249    ///
250    /// let column_type = rust_to_pg_type::<i32>(); // Returns ColumnType::Int4
251    /// let column_type = rust_to_pg_type::<String>(); // Returns ColumnType::Text
252    /// ```
253    pub fn rust_to_pg_type<T>() -> ColumnType {
254        // This would need to be implemented with a trait-based approach
255        // For now, return a default type
256        ColumnType::Text
257    }
258
259    /// Map PostgreSQL column types to Rust types
260    ///
261    /// This provides the reverse mapping for convenience.
262    pub fn pg_to_rust_type(column_type: &ColumnType) -> &'static str {
263        match column_type {
264            ColumnType::Int2 => "i16",
265            ColumnType::Int4 => "i32",
266            ColumnType::Int8 => "i64",
267            ColumnType::Text => "String",
268            ColumnType::Varchar(_) => "String",
269            ColumnType::Bool => "bool",
270            ColumnType::Uuid => "uuid::Uuid",
271            ColumnType::Timestamptz => "chrono::DateTime<chrono::Utc>",
272            ColumnType::Date => "chrono::NaiveDate",
273            ColumnType::Time => "chrono::NaiveTime",
274            ColumnType::Json => "serde_json::Value",
275            ColumnType::Jsonb => "serde_json::Value",
276            ColumnType::Numeric(_, _) => "rust_decimal::Decimal",
277            _ => "String", // Default fallback
278        }
279    }
280}
281
282/// Safe SQL generation utilities
283///
284/// These provide the same SQL safety convenience as the macro approach.
285pub mod safe_sql {
286    use crate::common::validate_identifier;
287
288    /// Generate safe SQL with parameter binding
289    ///
290    /// This provides the same SQL safety as the macro approach.
291    ///
292    /// # Example
293    ///
294    /// ```rust
295    /// use ignis_db::builders::safe_sql::*;
296    ///
297    /// let sql = safe_select("users", &["id", "email"], "active = ?");
298    /// // Generates: "SELECT id, email FROM users WHERE active = ?"
299    /// ```
300    pub fn safe_select(table: &str, columns: &[&str], where_clause: &str) -> String {
301        let table_safe = validate_identifier(table).unwrap_or_else(|| table.to_string());
302        let columns_safe: Vec<String> = columns
303            .iter()
304            .map(|col| validate_identifier(col).unwrap_or_else(|| col.to_string()))
305            .collect();
306
307        format!(
308            "SELECT {} FROM {} WHERE {}",
309            columns_safe.join(", "),
310            table_safe,
311            where_clause
312        )
313    }
314
315    /// Generate safe INSERT SQL
316    pub fn safe_insert(table: &str, columns: &[&str]) -> String {
317        let table_safe = validate_identifier(table).unwrap_or_else(|| table.to_string());
318        let columns_safe: Vec<String> = columns
319            .iter()
320            .map(|col| validate_identifier(col).unwrap_or_else(|| col.to_string()))
321            .collect();
322        let placeholders: Vec<String> = (0..columns.len()).map(|_| "?".to_string()).collect();
323
324        format!(
325            "INSERT INTO {} ({}) VALUES ({})",
326            table_safe,
327            columns_safe.join(", "),
328            placeholders.join(", ")
329        )
330    }
331
332    /// Generate safe UPDATE SQL
333    pub fn safe_update(table: &str, columns: &[&str], where_clause: &str) -> String {
334        let table_safe = validate_identifier(table).unwrap_or_else(|| table.to_string());
335        let columns_safe: Vec<String> = columns
336            .iter()
337            .map(|col| {
338                format!(
339                    "{} = ?",
340                    validate_identifier(col).unwrap_or_else(|| col.to_string())
341                )
342            })
343            .collect();
344
345        format!(
346            "UPDATE {} SET {} WHERE {}",
347            table_safe,
348            columns_safe.join(", "),
349            where_clause
350        )
351    }
352
353    /// Generate safe DELETE SQL
354    pub fn safe_delete(table: &str, where_clause: &str) -> String {
355        let table_safe = validate_identifier(table).unwrap_or_else(|| table.to_string());
356
357        format!("DELETE FROM {} WHERE {}", table_safe, where_clause)
358    }
359}