ignis-db 0.2.0

A comprehensive PostgreSQL ORM with macro-driven schema management
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
//! Procedural macros for defining PostgreSQL stored functions and procedures

/// Macro for defining PostgreSQL stored functions
///
/// # Example
/// ```rust
/// use ignis_db::function;
///
/// // Simple function with return type
/// function! {
///     calculate_age(birth_date: Date) -> Integer {
///         language: plpgsql,
///         volatility: immutable,
///         body: r#"
///             BEGIN
///                 RETURN EXTRACT(YEAR FROM AGE(birth_date));
///             END;
///         "#
///     }
/// }
///
/// // Function with multiple OUT parameters
/// function! {
///     get_user_stats(user_id: Integer) -> Record {
///         out: {
///             total_posts: Integer,
///             last_login: Timestamptz
///         },
///         language: plpgsql,
///         body: r#"
///             BEGIN
///                 SELECT COUNT(*), MAX(login_time)
///                 INTO total_posts, last_login
///                 FROM user_activity
///                 WHERE user_id = user_id;
///             END;
///         "#
///     }
/// }
/// ```
#[macro_export]
macro_rules! function {
    // Function with simple return type
    (
        $func_name:ident($($param_name:ident: $param_type:ident),* $(,)?) -> $return_type:ident {
            $(language: $language:ident,)?
            $(volatility: $volatility:ident,)?
            $(security: $security:ident,)?
            $(strict: $strict:ident,)?
            body: $body:expr
        }
    ) => {
        pub mod $func_name {
            use $crate::schema::{StoredFunction, ProcedureParameter, ParameterMode, ProcedureLanguage, FunctionVolatility, FunctionSecurity};

            /// Get the function definition
            pub fn function() -> StoredFunction {
                let mut func = StoredFunction::new(stringify!($func_name));

                // Add parameters
                $(
                    func = func.with_parameter(
                        ProcedureParameter::new(stringify!($param_name), $crate::function!(@pg_type $param_type))
                    );
                )*

                // Set return type
                func = func.with_return_type($crate::function!(@pg_type $return_type));

                // Set language (default: plpgsql)
                func = func.with_language($crate::function!(@language $($language)?));

                // Set volatility (default: volatile)
                func = func.with_volatility($crate::function!(@volatility $($volatility)?));

                // Set security (default: invoker)
                func = func.with_security($crate::function!(@security $($security)?));

                // Set strict mode (default: false)
                func = func.with_strict($crate::function!(@strict $($strict)?));

                // Set body
                func = func.with_body($body);

                func
            }

            /// Get function metadata
            pub fn name() -> &'static str {
                stringify!($func_name)
            }
        }

        // Register function in inventory system
        inventory::submit! {
            $crate::RegisteredObject($crate::SchemaObject {
                kind: "function",
                name: stringify!($func_name),
                ddl: "", // Will be generated dynamically
                schema: None,
            })
        }
    };

    // Function with OUT parameters
    (
        $func_name:ident($($param_name:ident: $param_type:ident),* $(,)?) -> Record {
            out: {
                $($out_param_name:ident: $out_param_type:ident),* $(,)?
            },
            $(language: $language:ident,)?
            $(volatility: $volatility:ident,)?
            $(security: $security:ident,)?
            $(strict: $strict:ident,)?
            body: $body:expr
        }
    ) => {
        pub mod $func_name {
            use $crate::schema::{StoredFunction, ProcedureParameter, ParameterMode, ProcedureLanguage, FunctionVolatility, FunctionSecurity};

            /// Get the function definition
            pub fn function() -> StoredFunction {
                let mut func = StoredFunction::new(stringify!($func_name));

                // Add IN parameters
                $(
                    func = func.with_parameter(
                        ProcedureParameter::new(stringify!($param_name), $crate::function!(@pg_type $param_type))
                            .with_mode(ParameterMode::In)
                    );
                )*

                // Add OUT parameters
                $(
                    func = func.with_parameter(
                        ProcedureParameter::new(stringify!($out_param_name), $crate::function!(@pg_type $out_param_type))
                            .with_mode(ParameterMode::Out)
                    );
                )*

                // Set language (default: plpgsql)
                func = func.with_language($crate::function!(@language $($language)?));

                // Set volatility (default: volatile)
                func = func.with_volatility($crate::function!(@volatility $($volatility)?));

                // Set security (default: invoker)
                func = func.with_security($crate::function!(@security $($security)?));

                // Set strict mode (default: false)
                func = func.with_strict($crate::function!(@strict $($strict)?));

                // Set body
                func = func.with_body($body);

                func
            }

            /// Get function metadata
            pub fn name() -> &'static str {
                stringify!($func_name)
            }
        }

        // Register function in inventory system
        inventory::submit! {
            $crate::RegisteredObject($crate::SchemaObject {
                kind: "function",
                name: stringify!($func_name),
                ddl: "", // Will be generated dynamically
                schema: None,
            })
        }
    };

    // Helper macros for type mapping
    (@pg_type Integer) => { "INTEGER" };
    (@pg_type Int4) => { "INTEGER" };
    (@pg_type Int8) => { "BIGINT" };
    (@pg_type Int2) => { "SMALLINT" };
    (@pg_type Text) => { "TEXT" };
    (@pg_type Varchar) => { "VARCHAR" };
    (@pg_type Bool) => { "BOOLEAN" };
    (@pg_type Date) => { "DATE" };
    (@pg_type Timestamptz) => { "TIMESTAMPTZ" };
    (@pg_type Timestamp) => { "TIMESTAMP" };
    (@pg_type Numeric) => { "NUMERIC" };
    (@pg_type Real) => { "REAL" };
    (@pg_type DoublePrecision) => { "DOUBLE PRECISION" };
    (@pg_type Uuid) => { "UUID" };
    (@pg_type Json) => { "JSON" };
    (@pg_type Jsonb) => { "JSONB" };
    (@pg_type Record) => { "RECORD" };

    // Language mapping
    (@language) => { ProcedureLanguage::PlPgSql };
    (@language plpgsql) => { ProcedureLanguage::PlPgSql };
    (@language sql) => { ProcedureLanguage::Sql };
    (@language python) => { ProcedureLanguage::PlPython3 };
    (@language c) => { ProcedureLanguage::C };

    // Volatility mapping
    (@volatility) => { FunctionVolatility::Volatile };
    (@volatility volatile) => { FunctionVolatility::Volatile };
    (@volatility stable) => { FunctionVolatility::Stable };
    (@volatility immutable) => { FunctionVolatility::Immutable };

    // Security mapping
    (@security) => { FunctionSecurity::Invoker };
    (@security invoker) => { FunctionSecurity::Invoker };
    (@security definer) => { FunctionSecurity::Definer };

    // Strict mapping
    (@strict) => { false };
    (@strict true) => { true };
    (@strict false) => { false };
}

/// Macro for defining PostgreSQL stored procedures
///
/// # Example
/// ```rust
/// use ignis_db::procedure;
///
/// // Simple procedure with parameters
/// procedure! {
///     update_user_status(user_id: Integer, new_status: Text) {
///         language: plpgsql,
///         body: r#"
///             BEGIN
///                 UPDATE users SET status = new_status WHERE id = user_id;
///                 COMMIT;
///             END;
///         "#
///     }
/// }
///
/// // Procedure with INOUT parameters
/// procedure! {
///     process_batch(batch_size: Integer) {
///         inout: {
///             processed_count: Integer
///         },
///         language: plpgsql,
///         body: r#"
///             BEGIN
///                 FOR i IN 1..batch_size LOOP
///                     -- Process logic here
///                     processed_count := processed_count + 1;
///                     
///                     IF i % 10 = 0 THEN
///                         COMMIT;
///                     END IF;
///                 END LOOP;
///             END;
///         "#
///     }
/// }
/// ```
#[macro_export]
macro_rules! procedure {
    // Simple procedure with parameters
    (
        $proc_name:ident($($param_name:ident: $param_type:ident),* $(,)?) {
            $(language: $language:ident,)?
            $(security: $security:ident,)?
            body: $body:expr
        }
    ) => {
        pub mod $proc_name {
            use $crate::schema::{StoredProcedure, ProcedureParameter, ParameterMode, ProcedureLanguage, FunctionSecurity};

            /// Get the procedure definition
            pub fn procedure() -> StoredProcedure {
                let mut proc = StoredProcedure::new(stringify!($proc_name));

                // Add parameters
                $(
                    proc = proc.with_parameter(
                        ProcedureParameter::new(stringify!($param_name), $crate::procedure!(@pg_type $param_type))
                    );
                )*

                // Set language (default: plpgsql)
                proc = proc.with_language($crate::procedure!(@language $($language)?));

                // Set security (default: invoker)
                proc = proc.with_security($crate::procedure!(@security $($security)?));

                // Set body
                proc = proc.with_body($body);

                proc
            }

            /// Get procedure metadata
            pub fn name() -> &'static str {
                stringify!($proc_name)
            }
        }

        // Register procedure in inventory system
        inventory::submit! {
            $crate::RegisteredObject($crate::SchemaObject {
                kind: "procedure",
                name: stringify!($proc_name),
                ddl: "", // Will be generated dynamically
                schema: None,
            })
        }
    };

    // Procedure with INOUT parameters
    (
        $proc_name:ident($($param_name:ident: $param_type:ident),* $(,)?) {
            inout: {
                $($inout_param_name:ident: $inout_param_type:ident),* $(,)?
            },
            $(language: $language:ident,)?
            $(security: $security:ident,)?
            body: $body:expr
        }
    ) => {
        pub mod $proc_name {
            use $crate::schema::{StoredProcedure, ProcedureParameter, ParameterMode, ProcedureLanguage, FunctionSecurity};

            /// Get the procedure definition
            pub fn procedure() -> StoredProcedure {
                let mut proc = StoredProcedure::new(stringify!($proc_name));

                // Add IN parameters
                $(
                    proc = proc.with_parameter(
                        ProcedureParameter::new(stringify!($param_name), $crate::procedure!(@pg_type $param_type))
                            .with_mode(ParameterMode::In)
                    );
                )*

                // Add INOUT parameters
                $(
                    proc = proc.with_parameter(
                        ProcedureParameter::new(stringify!($inout_param_name), $crate::procedure!(@pg_type $inout_param_type))
                            .with_mode(ParameterMode::InOut)
                    );
                )*

                // Set language (default: plpgsql)
                proc = proc.with_language($crate::procedure!(@language $($language)?));

                // Set security (default: invoker)
                proc = proc.with_security($crate::procedure!(@security $($security)?));

                // Set body
                proc = proc.with_body($body);

                proc
            }

            /// Get procedure metadata
            pub fn name() -> &'static str {
                stringify!($proc_name)
            }
        }

        // Register procedure in inventory system
        inventory::submit! {
            $crate::RegisteredObject($crate::SchemaObject {
                kind: "procedure",
                name: stringify!($proc_name),
                ddl: "", // Will be generated dynamically
                schema: None,
            })
        }
    };

    // Helper macros for type mapping (same as function!)
    (@pg_type Integer) => { "INTEGER" };
    (@pg_type Int4) => { "INTEGER" };
    (@pg_type Int8) => { "BIGINT" };
    (@pg_type Int2) => { "SMALLINT" };
    (@pg_type Text) => { "TEXT" };
    (@pg_type Varchar) => { "VARCHAR" };
    (@pg_type Bool) => { "BOOLEAN" };
    (@pg_type Date) => { "DATE" };
    (@pg_type Timestamptz) => { "TIMESTAMPTZ" };
    (@pg_type Timestamp) => { "TIMESTAMP" };
    (@pg_type Numeric) => { "NUMERIC" };
    (@pg_type Real) => { "REAL" };
    (@pg_type DoublePrecision) => { "DOUBLE PRECISION" };
    (@pg_type Uuid) => { "UUID" };
    (@pg_type Json) => { "JSON" };
    (@pg_type Jsonb) => { "JSONB" };

    // Language mapping
    (@language) => { ProcedureLanguage::PlPgSql };
    (@language plpgsql) => { ProcedureLanguage::PlPgSql };
    (@language sql) => { ProcedureLanguage::Sql };
    (@language python) => { ProcedureLanguage::PlPython3 };
    (@language c) => { ProcedureLanguage::C };

    // Security mapping
    (@security) => { FunctionSecurity::Invoker };
    (@security invoker) => { FunctionSecurity::Invoker };
    (@security definer) => { FunctionSecurity::Definer };
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::schema::*;

    // Test function definition
    function! {
        test_calculate_age(birth_date: Date) -> Integer {
            language: plpgsql,
            volatility: immutable,
            body: r#"
                BEGIN
                    RETURN EXTRACT(YEAR FROM AGE(birth_date));
                END;
            "#
        }
    }

    // Test procedure definition
    procedure! {
        test_update_status(user_id: Integer, status: Text) {
            language: plpgsql,
            body: r#"
                BEGIN
                    UPDATE users SET status = status WHERE id = user_id;
                    COMMIT;
                END;
            "#
        }
    }

    #[test]
    fn test_function_macro() {
        let func = test_calculate_age::function();
        assert_eq!(func.name, "test_calculate_age");
        assert_eq!(func.parameters.len(), 1);
        assert_eq!(func.parameters[0].name, "birth_date");
        assert_eq!(func.parameters[0].data_type, "DATE");
        assert_eq!(func.return_type, Some("INTEGER".to_string()));
        assert_eq!(func.volatility, FunctionVolatility::Immutable);
        assert_eq!(test_calculate_age::name(), "test_calculate_age");
    }

    #[test]
    fn test_procedure_macro() {
        let proc = test_update_status::procedure();
        assert_eq!(proc.name, "test_update_status");
        assert_eq!(proc.parameters.len(), 2);
        assert_eq!(proc.parameters[0].name, "user_id");
        assert_eq!(proc.parameters[0].data_type, "INTEGER");
        assert_eq!(proc.parameters[1].name, "status");
        assert_eq!(proc.parameters[1].data_type, "TEXT");
        assert_eq!(test_update_status::name(), "test_update_status");
    }

    #[test]
    fn test_function_ddl_generation() {
        let func = test_calculate_age::function();
        let ddl = func.generate_create_ddl();

        assert!(ddl.contains("CREATE OR REPLACE FUNCTION \"test_calculate_age\""));
        assert!(ddl.contains("birth_date DATE"));
        assert!(ddl.contains("RETURNS INTEGER"));
        assert!(ddl.contains("LANGUAGE plpgsql"));
        assert!(ddl.contains("IMMUTABLE"));
        assert!(ddl.contains("EXTRACT(YEAR FROM AGE(birth_date))"));
    }

    #[test]
    fn test_procedure_ddl_generation() {
        let proc = test_update_status::procedure();
        let ddl = proc.generate_create_ddl();

        assert!(ddl.contains("CREATE OR REPLACE PROCEDURE \"test_update_status\""));
        assert!(ddl.contains("user_id INTEGER"));
        assert!(ddl.contains("status TEXT"));
        assert!(!ddl.contains("RETURNS")); // Procedures don't have return types
        assert!(ddl.contains("LANGUAGE plpgsql"));
        assert!(ddl.contains("UPDATE users SET"));
    }
}