Skip to main content

ignis_db/macros/
procedure.rs

1//! Procedural macros for defining PostgreSQL stored functions and procedures
2
3/// Macro for defining PostgreSQL stored functions
4///
5/// # Example
6/// ```rust
7/// use ignis_db::function;
8///
9/// // Simple function with return type
10/// function! {
11///     calculate_age(birth_date: Date) -> Integer {
12///         language: plpgsql,
13///         volatility: immutable,
14///         body: r#"
15///             BEGIN
16///                 RETURN EXTRACT(YEAR FROM AGE(birth_date));
17///             END;
18///         "#
19///     }
20/// }
21///
22/// // Function with multiple OUT parameters
23/// function! {
24///     get_user_stats(user_id: Integer) -> Record {
25///         out: {
26///             total_posts: Integer,
27///             last_login: Timestamptz
28///         },
29///         language: plpgsql,
30///         body: r#"
31///             BEGIN
32///                 SELECT COUNT(*), MAX(login_time)
33///                 INTO total_posts, last_login
34///                 FROM user_activity
35///                 WHERE user_id = user_id;
36///             END;
37///         "#
38///     }
39/// }
40/// ```
41#[macro_export]
42macro_rules! function {
43    // Function with simple return type
44    (
45        $func_name:ident($($param_name:ident: $param_type:ident),* $(,)?) -> $return_type:ident {
46            $(language: $language:ident,)?
47            $(volatility: $volatility:ident,)?
48            $(security: $security:ident,)?
49            $(strict: $strict:ident,)?
50            body: $body:expr
51        }
52    ) => {
53        pub mod $func_name {
54            use $crate::schema::{StoredFunction, ProcedureParameter, ParameterMode, ProcedureLanguage, FunctionVolatility, FunctionSecurity};
55
56            /// Get the function definition
57            pub fn function() -> StoredFunction {
58                let mut func = StoredFunction::new(stringify!($func_name));
59
60                // Add parameters
61                $(
62                    func = func.with_parameter(
63                        ProcedureParameter::new(stringify!($param_name), $crate::function!(@pg_type $param_type))
64                    );
65                )*
66
67                // Set return type
68                func = func.with_return_type($crate::function!(@pg_type $return_type));
69
70                // Set language (default: plpgsql)
71                func = func.with_language($crate::function!(@language $($language)?));
72
73                // Set volatility (default: volatile)
74                func = func.with_volatility($crate::function!(@volatility $($volatility)?));
75
76                // Set security (default: invoker)
77                func = func.with_security($crate::function!(@security $($security)?));
78
79                // Set strict mode (default: false)
80                func = func.with_strict($crate::function!(@strict $($strict)?));
81
82                // Set body
83                func = func.with_body($body);
84
85                func
86            }
87
88            /// Get function metadata
89            pub fn name() -> &'static str {
90                stringify!($func_name)
91            }
92        }
93
94        // Register function in inventory system
95        inventory::submit! {
96            $crate::RegisteredObject($crate::SchemaObject {
97                kind: "function",
98                name: stringify!($func_name),
99                ddl: "", // Will be generated dynamically
100                schema: None,
101            })
102        }
103    };
104
105    // Function with OUT parameters
106    (
107        $func_name:ident($($param_name:ident: $param_type:ident),* $(,)?) -> Record {
108            out: {
109                $($out_param_name:ident: $out_param_type:ident),* $(,)?
110            },
111            $(language: $language:ident,)?
112            $(volatility: $volatility:ident,)?
113            $(security: $security:ident,)?
114            $(strict: $strict:ident,)?
115            body: $body:expr
116        }
117    ) => {
118        pub mod $func_name {
119            use $crate::schema::{StoredFunction, ProcedureParameter, ParameterMode, ProcedureLanguage, FunctionVolatility, FunctionSecurity};
120
121            /// Get the function definition
122            pub fn function() -> StoredFunction {
123                let mut func = StoredFunction::new(stringify!($func_name));
124
125                // Add IN parameters
126                $(
127                    func = func.with_parameter(
128                        ProcedureParameter::new(stringify!($param_name), $crate::function!(@pg_type $param_type))
129                            .with_mode(ParameterMode::In)
130                    );
131                )*
132
133                // Add OUT parameters
134                $(
135                    func = func.with_parameter(
136                        ProcedureParameter::new(stringify!($out_param_name), $crate::function!(@pg_type $out_param_type))
137                            .with_mode(ParameterMode::Out)
138                    );
139                )*
140
141                // Set language (default: plpgsql)
142                func = func.with_language($crate::function!(@language $($language)?));
143
144                // Set volatility (default: volatile)
145                func = func.with_volatility($crate::function!(@volatility $($volatility)?));
146
147                // Set security (default: invoker)
148                func = func.with_security($crate::function!(@security $($security)?));
149
150                // Set strict mode (default: false)
151                func = func.with_strict($crate::function!(@strict $($strict)?));
152
153                // Set body
154                func = func.with_body($body);
155
156                func
157            }
158
159            /// Get function metadata
160            pub fn name() -> &'static str {
161                stringify!($func_name)
162            }
163        }
164
165        // Register function in inventory system
166        inventory::submit! {
167            $crate::RegisteredObject($crate::SchemaObject {
168                kind: "function",
169                name: stringify!($func_name),
170                ddl: "", // Will be generated dynamically
171                schema: None,
172            })
173        }
174    };
175
176    // Helper macros for type mapping
177    (@pg_type Integer) => { "INTEGER" };
178    (@pg_type Int4) => { "INTEGER" };
179    (@pg_type Int8) => { "BIGINT" };
180    (@pg_type Int2) => { "SMALLINT" };
181    (@pg_type Text) => { "TEXT" };
182    (@pg_type Varchar) => { "VARCHAR" };
183    (@pg_type Bool) => { "BOOLEAN" };
184    (@pg_type Date) => { "DATE" };
185    (@pg_type Timestamptz) => { "TIMESTAMPTZ" };
186    (@pg_type Timestamp) => { "TIMESTAMP" };
187    (@pg_type Numeric) => { "NUMERIC" };
188    (@pg_type Real) => { "REAL" };
189    (@pg_type DoublePrecision) => { "DOUBLE PRECISION" };
190    (@pg_type Uuid) => { "UUID" };
191    (@pg_type Json) => { "JSON" };
192    (@pg_type Jsonb) => { "JSONB" };
193    (@pg_type Record) => { "RECORD" };
194
195    // Language mapping
196    (@language) => { ProcedureLanguage::PlPgSql };
197    (@language plpgsql) => { ProcedureLanguage::PlPgSql };
198    (@language sql) => { ProcedureLanguage::Sql };
199    (@language python) => { ProcedureLanguage::PlPython3 };
200    (@language c) => { ProcedureLanguage::C };
201
202    // Volatility mapping
203    (@volatility) => { FunctionVolatility::Volatile };
204    (@volatility volatile) => { FunctionVolatility::Volatile };
205    (@volatility stable) => { FunctionVolatility::Stable };
206    (@volatility immutable) => { FunctionVolatility::Immutable };
207
208    // Security mapping
209    (@security) => { FunctionSecurity::Invoker };
210    (@security invoker) => { FunctionSecurity::Invoker };
211    (@security definer) => { FunctionSecurity::Definer };
212
213    // Strict mapping
214    (@strict) => { false };
215    (@strict true) => { true };
216    (@strict false) => { false };
217}
218
219/// Macro for defining PostgreSQL stored procedures
220///
221/// # Example
222/// ```rust
223/// use ignis_db::procedure;
224///
225/// // Simple procedure with parameters
226/// procedure! {
227///     update_user_status(user_id: Integer, new_status: Text) {
228///         language: plpgsql,
229///         body: r#"
230///             BEGIN
231///                 UPDATE users SET status = new_status WHERE id = user_id;
232///                 COMMIT;
233///             END;
234///         "#
235///     }
236/// }
237///
238/// // Procedure with INOUT parameters
239/// procedure! {
240///     process_batch(batch_size: Integer) {
241///         inout: {
242///             processed_count: Integer
243///         },
244///         language: plpgsql,
245///         body: r#"
246///             BEGIN
247///                 FOR i IN 1..batch_size LOOP
248///                     -- Process logic here
249///                     processed_count := processed_count + 1;
250///                     
251///                     IF i % 10 = 0 THEN
252///                         COMMIT;
253///                     END IF;
254///                 END LOOP;
255///             END;
256///         "#
257///     }
258/// }
259/// ```
260#[macro_export]
261macro_rules! procedure {
262    // Simple procedure with parameters
263    (
264        $proc_name:ident($($param_name:ident: $param_type:ident),* $(,)?) {
265            $(language: $language:ident,)?
266            $(security: $security:ident,)?
267            body: $body:expr
268        }
269    ) => {
270        pub mod $proc_name {
271            use $crate::schema::{StoredProcedure, ProcedureParameter, ParameterMode, ProcedureLanguage, FunctionSecurity};
272
273            /// Get the procedure definition
274            pub fn procedure() -> StoredProcedure {
275                let mut proc = StoredProcedure::new(stringify!($proc_name));
276
277                // Add parameters
278                $(
279                    proc = proc.with_parameter(
280                        ProcedureParameter::new(stringify!($param_name), $crate::procedure!(@pg_type $param_type))
281                    );
282                )*
283
284                // Set language (default: plpgsql)
285                proc = proc.with_language($crate::procedure!(@language $($language)?));
286
287                // Set security (default: invoker)
288                proc = proc.with_security($crate::procedure!(@security $($security)?));
289
290                // Set body
291                proc = proc.with_body($body);
292
293                proc
294            }
295
296            /// Get procedure metadata
297            pub fn name() -> &'static str {
298                stringify!($proc_name)
299            }
300        }
301
302        // Register procedure in inventory system
303        inventory::submit! {
304            $crate::RegisteredObject($crate::SchemaObject {
305                kind: "procedure",
306                name: stringify!($proc_name),
307                ddl: "", // Will be generated dynamically
308                schema: None,
309            })
310        }
311    };
312
313    // Procedure with INOUT parameters
314    (
315        $proc_name:ident($($param_name:ident: $param_type:ident),* $(,)?) {
316            inout: {
317                $($inout_param_name:ident: $inout_param_type:ident),* $(,)?
318            },
319            $(language: $language:ident,)?
320            $(security: $security:ident,)?
321            body: $body:expr
322        }
323    ) => {
324        pub mod $proc_name {
325            use $crate::schema::{StoredProcedure, ProcedureParameter, ParameterMode, ProcedureLanguage, FunctionSecurity};
326
327            /// Get the procedure definition
328            pub fn procedure() -> StoredProcedure {
329                let mut proc = StoredProcedure::new(stringify!($proc_name));
330
331                // Add IN parameters
332                $(
333                    proc = proc.with_parameter(
334                        ProcedureParameter::new(stringify!($param_name), $crate::procedure!(@pg_type $param_type))
335                            .with_mode(ParameterMode::In)
336                    );
337                )*
338
339                // Add INOUT parameters
340                $(
341                    proc = proc.with_parameter(
342                        ProcedureParameter::new(stringify!($inout_param_name), $crate::procedure!(@pg_type $inout_param_type))
343                            .with_mode(ParameterMode::InOut)
344                    );
345                )*
346
347                // Set language (default: plpgsql)
348                proc = proc.with_language($crate::procedure!(@language $($language)?));
349
350                // Set security (default: invoker)
351                proc = proc.with_security($crate::procedure!(@security $($security)?));
352
353                // Set body
354                proc = proc.with_body($body);
355
356                proc
357            }
358
359            /// Get procedure metadata
360            pub fn name() -> &'static str {
361                stringify!($proc_name)
362            }
363        }
364
365        // Register procedure in inventory system
366        inventory::submit! {
367            $crate::RegisteredObject($crate::SchemaObject {
368                kind: "procedure",
369                name: stringify!($proc_name),
370                ddl: "", // Will be generated dynamically
371                schema: None,
372            })
373        }
374    };
375
376    // Helper macros for type mapping (same as function!)
377    (@pg_type Integer) => { "INTEGER" };
378    (@pg_type Int4) => { "INTEGER" };
379    (@pg_type Int8) => { "BIGINT" };
380    (@pg_type Int2) => { "SMALLINT" };
381    (@pg_type Text) => { "TEXT" };
382    (@pg_type Varchar) => { "VARCHAR" };
383    (@pg_type Bool) => { "BOOLEAN" };
384    (@pg_type Date) => { "DATE" };
385    (@pg_type Timestamptz) => { "TIMESTAMPTZ" };
386    (@pg_type Timestamp) => { "TIMESTAMP" };
387    (@pg_type Numeric) => { "NUMERIC" };
388    (@pg_type Real) => { "REAL" };
389    (@pg_type DoublePrecision) => { "DOUBLE PRECISION" };
390    (@pg_type Uuid) => { "UUID" };
391    (@pg_type Json) => { "JSON" };
392    (@pg_type Jsonb) => { "JSONB" };
393
394    // Language mapping
395    (@language) => { ProcedureLanguage::PlPgSql };
396    (@language plpgsql) => { ProcedureLanguage::PlPgSql };
397    (@language sql) => { ProcedureLanguage::Sql };
398    (@language python) => { ProcedureLanguage::PlPython3 };
399    (@language c) => { ProcedureLanguage::C };
400
401    // Security mapping
402    (@security) => { FunctionSecurity::Invoker };
403    (@security invoker) => { FunctionSecurity::Invoker };
404    (@security definer) => { FunctionSecurity::Definer };
405}
406
407#[cfg(test)]
408mod tests {
409    use super::*;
410    use crate::schema::*;
411
412    // Test function definition
413    function! {
414        test_calculate_age(birth_date: Date) -> Integer {
415            language: plpgsql,
416            volatility: immutable,
417            body: r#"
418                BEGIN
419                    RETURN EXTRACT(YEAR FROM AGE(birth_date));
420                END;
421            "#
422        }
423    }
424
425    // Test procedure definition
426    procedure! {
427        test_update_status(user_id: Integer, status: Text) {
428            language: plpgsql,
429            body: r#"
430                BEGIN
431                    UPDATE users SET status = status WHERE id = user_id;
432                    COMMIT;
433                END;
434            "#
435        }
436    }
437
438    #[test]
439    fn test_function_macro() {
440        let func = test_calculate_age::function();
441        assert_eq!(func.name, "test_calculate_age");
442        assert_eq!(func.parameters.len(), 1);
443        assert_eq!(func.parameters[0].name, "birth_date");
444        assert_eq!(func.parameters[0].data_type, "DATE");
445        assert_eq!(func.return_type, Some("INTEGER".to_string()));
446        assert_eq!(func.volatility, FunctionVolatility::Immutable);
447        assert_eq!(test_calculate_age::name(), "test_calculate_age");
448    }
449
450    #[test]
451    fn test_procedure_macro() {
452        let proc = test_update_status::procedure();
453        assert_eq!(proc.name, "test_update_status");
454        assert_eq!(proc.parameters.len(), 2);
455        assert_eq!(proc.parameters[0].name, "user_id");
456        assert_eq!(proc.parameters[0].data_type, "INTEGER");
457        assert_eq!(proc.parameters[1].name, "status");
458        assert_eq!(proc.parameters[1].data_type, "TEXT");
459        assert_eq!(test_update_status::name(), "test_update_status");
460    }
461
462    #[test]
463    fn test_function_ddl_generation() {
464        let func = test_calculate_age::function();
465        let ddl = func.generate_create_ddl();
466
467        assert!(ddl.contains("CREATE OR REPLACE FUNCTION \"test_calculate_age\""));
468        assert!(ddl.contains("birth_date DATE"));
469        assert!(ddl.contains("RETURNS INTEGER"));
470        assert!(ddl.contains("LANGUAGE plpgsql"));
471        assert!(ddl.contains("IMMUTABLE"));
472        assert!(ddl.contains("EXTRACT(YEAR FROM AGE(birth_date))"));
473    }
474
475    #[test]
476    fn test_procedure_ddl_generation() {
477        let proc = test_update_status::procedure();
478        let ddl = proc.generate_create_ddl();
479
480        assert!(ddl.contains("CREATE OR REPLACE PROCEDURE \"test_update_status\""));
481        assert!(ddl.contains("user_id INTEGER"));
482        assert!(ddl.contains("status TEXT"));
483        assert!(!ddl.contains("RETURNS")); // Procedures don't have return types
484        assert!(ddl.contains("LANGUAGE plpgsql"));
485        assert!(ddl.contains("UPDATE users SET"));
486    }
487}