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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
//! PostgreSQL stored procedures and functions support for Ignis

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Parameter mode for stored procedures and functions
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ParameterMode {
    /// Input parameter (default)
    In,
    /// Output parameter (functions only)
    Out,
    /// Input/Output parameter
    InOut,
    /// Variadic parameter (variable number of arguments)
    Variadic,
}

impl Default for ParameterMode {
    fn default() -> Self {
        ParameterMode::In
    }
}

impl ParameterMode {
    pub fn to_sql(&self) -> &'static str {
        match self {
            ParameterMode::In => "IN",
            ParameterMode::Out => "OUT",
            ParameterMode::InOut => "INOUT",
            ParameterMode::Variadic => "VARIADIC",
        }
    }
}

/// Represents a parameter in a stored procedure or function
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ProcedureParameter {
    pub name: String,
    pub data_type: String,
    pub mode: ParameterMode,
    pub default_value: Option<String>,
}

impl ProcedureParameter {
    /// Create a new parameter
    pub fn new(name: impl Into<String>, data_type: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            data_type: data_type.into(),
            mode: ParameterMode::In,
            default_value: None,
        }
    }

    /// Set parameter mode
    pub fn with_mode(mut self, mode: ParameterMode) -> Self {
        self.mode = mode;
        self
    }

    /// Set default value
    pub fn with_default(mut self, default: impl Into<String>) -> Self {
        self.default_value = Some(default.into());
        self
    }

    /// Generate SQL parameter definition
    pub fn to_sql(&self) -> String {
        let mut sql = String::new();

        // Add mode if not IN (default)
        if self.mode != ParameterMode::In {
            sql.push_str(self.mode.to_sql());
            sql.push(' ');
        }

        sql.push_str(&self.name);
        sql.push(' ');
        sql.push_str(&self.data_type);

        // Add default value if specified
        if let Some(ref default) = self.default_value {
            sql.push_str(" DEFAULT ");
            sql.push_str(default);
        }

        sql
    }
}

/// Language used for stored procedures/functions
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ProcedureLanguage {
    /// PL/pgSQL (default procedural language)
    PlPgSql,
    /// SQL (simple SQL functions)
    Sql,
    /// Python (PL/Python)
    PlPython3,
    /// C language functions
    C,
    /// Custom language
    Custom(String),
}

impl Default for ProcedureLanguage {
    fn default() -> Self {
        ProcedureLanguage::PlPgSql
    }
}

impl ProcedureLanguage {
    pub fn to_sql(&self) -> &str {
        match self {
            ProcedureLanguage::PlPgSql => "plpgsql",
            ProcedureLanguage::Sql => "sql",
            ProcedureLanguage::PlPython3 => "plpython3u",
            ProcedureLanguage::C => "c",
            ProcedureLanguage::Custom(lang) => lang,
        }
    }
}

/// Represents a PostgreSQL stored function
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct StoredFunction {
    pub name: String,
    pub schema: Option<String>,
    pub parameters: Vec<ProcedureParameter>,
    pub return_type: Option<String>,
    pub language: ProcedureLanguage,
    pub body: String,
    pub volatility: FunctionVolatility,
    pub security: FunctionSecurity,
    pub strict: bool,
}

/// Represents a PostgreSQL stored procedure
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct StoredProcedure {
    pub name: String,
    pub schema: Option<String>,
    pub parameters: Vec<ProcedureParameter>,
    pub language: ProcedureLanguage,
    pub body: String,
    pub security: FunctionSecurity,
}

/// Function volatility categories
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum FunctionVolatility {
    /// Result depends only on parameters (can be cached)
    Immutable,
    /// Result depends on database content (default)
    Stable,
    /// Result can change even within single query
    Volatile,
}

impl Default for FunctionVolatility {
    fn default() -> Self {
        FunctionVolatility::Volatile
    }
}

impl FunctionVolatility {
    pub fn to_sql(&self) -> &'static str {
        match self {
            FunctionVolatility::Immutable => "IMMUTABLE",
            FunctionVolatility::Stable => "STABLE",
            FunctionVolatility::Volatile => "VOLATILE",
        }
    }
}

/// Function security mode
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum FunctionSecurity {
    /// Run with privileges of function caller (default)
    Invoker,
    /// Run with privileges of function owner
    Definer,
}

impl Default for FunctionSecurity {
    fn default() -> Self {
        FunctionSecurity::Invoker
    }
}

impl FunctionSecurity {
    pub fn to_sql(&self) -> &'static str {
        match self {
            FunctionSecurity::Invoker => "SECURITY INVOKER",
            FunctionSecurity::Definer => "SECURITY DEFINER",
        }
    }
}

impl StoredFunction {
    /// Create a new stored function
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            schema: None,
            parameters: Vec::new(),
            return_type: None,
            language: ProcedureLanguage::PlPgSql,
            body: String::new(),
            volatility: FunctionVolatility::Volatile,
            security: FunctionSecurity::Invoker,
            strict: false,
        }
    }

    /// Get the fully qualified name
    pub fn qualified_name(&self) -> String {
        if let Some(ref schema) = self.schema {
            format!("\"{}\".\"{}\"", schema, self.name)
        } else {
            format!("\"{}\"", self.name)
        }
    }

    /// Set schema
    pub fn with_schema(mut self, schema: impl Into<String>) -> Self {
        self.schema = Some(schema.into());
        self
    }

    /// Add parameter
    pub fn with_parameter(mut self, param: ProcedureParameter) -> Self {
        self.parameters.push(param);
        self
    }

    /// Set return type
    pub fn with_return_type(mut self, return_type: impl Into<String>) -> Self {
        self.return_type = Some(return_type.into());
        self
    }

    /// Set language
    pub fn with_language(mut self, language: ProcedureLanguage) -> Self {
        self.language = language;
        self
    }

    /// Set function body
    pub fn with_body(mut self, body: impl Into<String>) -> Self {
        self.body = body.into();
        self
    }

    /// Set volatility
    pub fn with_volatility(mut self, volatility: FunctionVolatility) -> Self {
        self.volatility = volatility;
        self
    }

    /// Set security mode
    pub fn with_security(mut self, security: FunctionSecurity) -> Self {
        self.security = security;
        self
    }

    /// Mark function as strict (returns NULL if any parameter is NULL)
    pub fn with_strict(mut self, strict: bool) -> Self {
        self.strict = strict;
        self
    }

    /// Get full function name including schema with proper escaping
    pub fn full_name(&self) -> String {
        match &self.schema {
            Some(schema) => format!("\"{}\".\"{}\"", schema, self.name),
            None => format!("\"{}\"", self.name),
        }
    }

    /// Generate CREATE FUNCTION DDL
    pub fn generate_create_ddl(&self) -> String {
        let mut ddl = String::from("CREATE OR REPLACE FUNCTION ");

        // Function name with schema
        ddl.push_str(&self.full_name());
        ddl.push('(');

        // Parameters
        let param_strings: Vec<String> = self.parameters.iter().map(|p| p.to_sql()).collect();
        ddl.push_str(&param_strings.join(", "));
        ddl.push(')');

        // Return type (if specified or inferred from OUT parameters)
        if let Some(ref return_type) = self.return_type {
            ddl.push_str(" RETURNS ");
            ddl.push_str(return_type);
        } else {
            // Infer return type from OUT parameters
            let out_params: Vec<&ProcedureParameter> = self
                .parameters
                .iter()
                .filter(|p| matches!(p.mode, ParameterMode::Out | ParameterMode::InOut))
                .collect();

            if !out_params.is_empty() {
                ddl.push_str(" RETURNS ");
                if out_params.len() == 1 {
                    ddl.push_str(&out_params[0].data_type);
                } else {
                    ddl.push_str("RECORD");
                }
            }
        }

        // Language
        ddl.push_str(" LANGUAGE ");
        ddl.push_str(self.language.to_sql());

        // Volatility
        ddl.push(' ');
        ddl.push_str(self.volatility.to_sql());

        // Security
        ddl.push(' ');
        ddl.push_str(self.security.to_sql());

        // Strict
        if self.strict {
            ddl.push_str(" STRICT");
        }

        // Function body
        ddl.push_str(" AS $$\n");
        ddl.push_str(&self.body);
        ddl.push_str("\n$$;");

        ddl
    }

    /// Generate DROP FUNCTION DDL
    pub fn generate_drop_ddl(&self) -> String {
        let param_types: Vec<String> = self
            .parameters
            .iter()
            .filter(|p| p.mode == ParameterMode::In || p.mode == ParameterMode::InOut)
            .map(|p| p.data_type.clone())
            .collect();

        format!(
            "DROP FUNCTION IF EXISTS {}({}) CASCADE;",
            self.full_name(),
            param_types.join(", ")
        )
    }
}

impl StoredProcedure {
    /// Create a new stored procedure
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            schema: None,
            parameters: Vec::new(),
            language: ProcedureLanguage::PlPgSql,
            body: String::new(),
            security: FunctionSecurity::Invoker,
        }
    }

    /// Get the fully qualified name
    pub fn qualified_name(&self) -> String {
        if let Some(ref schema) = self.schema {
            format!("\"{}\".\"{}\"", schema, self.name)
        } else {
            format!("\"{}\"", self.name)
        }
    }

    /// Set schema
    pub fn with_schema(mut self, schema: impl Into<String>) -> Self {
        self.schema = Some(schema.into());
        self
    }

    /// Add parameter
    pub fn with_parameter(mut self, param: ProcedureParameter) -> Self {
        self.parameters.push(param);
        self
    }

    /// Set language
    pub fn with_language(mut self, language: ProcedureLanguage) -> Self {
        self.language = language;
        self
    }

    /// Set procedure body
    pub fn with_body(mut self, body: impl Into<String>) -> Self {
        self.body = body.into();
        self
    }

    /// Set security mode
    pub fn with_security(mut self, security: FunctionSecurity) -> Self {
        self.security = security;
        self
    }

    /// Get full procedure name including schema with proper escaping
    pub fn full_name(&self) -> String {
        match &self.schema {
            Some(schema) => format!("\"{}\".\"{}\"", schema, self.name),
            None => format!("\"{}\"", self.name),
        }
    }

    /// Generate CREATE PROCEDURE DDL
    pub fn generate_create_ddl(&self) -> String {
        let mut ddl = String::from("CREATE OR REPLACE PROCEDURE ");

        // Procedure name with schema
        ddl.push_str(&self.full_name());
        ddl.push('(');

        // Parameters (procedures can't have OUT mode, only IN and INOUT)
        let param_strings: Vec<String> = self.parameters.iter().map(|p| p.to_sql()).collect();
        ddl.push_str(&param_strings.join(", "));
        ddl.push(')');

        // Language
        ddl.push_str(" LANGUAGE ");
        ddl.push_str(self.language.to_sql());

        // Security
        ddl.push(' ');
        ddl.push_str(self.security.to_sql());

        // Procedure body
        ddl.push_str(" AS $$\n");
        ddl.push_str(&self.body);
        ddl.push_str("\n$$;");

        ddl
    }

    /// Generate DROP PROCEDURE DDL
    pub fn generate_drop_ddl(&self) -> String {
        let param_types: Vec<String> = self
            .parameters
            .iter()
            .filter(|p| p.mode == ParameterMode::In || p.mode == ParameterMode::InOut)
            .map(|p| p.data_type.clone())
            .collect();

        format!(
            "DROP PROCEDURE IF EXISTS {}({}) CASCADE;",
            self.full_name(),
            param_types.join(", ")
        )
    }
}

/// Registry for stored procedures and functions
pub struct ProcedureRegistry {
    functions: HashMap<String, StoredFunction>,
    procedures: HashMap<String, StoredProcedure>,
}

impl ProcedureRegistry {
    /// Create a new registry
    pub fn new() -> Self {
        Self {
            functions: HashMap::new(),
            procedures: HashMap::new(),
        }
    }

    /// Register a function
    pub fn register_function(&mut self, function: StoredFunction) {
        self.functions.insert(function.full_name(), function);
    }

    /// Register a procedure
    pub fn register_procedure(&mut self, procedure: StoredProcedure) {
        self.procedures.insert(procedure.full_name(), procedure);
    }

    /// Get all registered functions
    pub fn all_functions(&self) -> impl Iterator<Item = &StoredFunction> {
        self.functions.values()
    }

    /// Get all registered procedures
    pub fn all_procedures(&self) -> impl Iterator<Item = &StoredProcedure> {
        self.procedures.values()
    }

    /// Get a specific function
    pub fn get_function(&self, name: &str) -> Option<&StoredFunction> {
        self.functions.get(name)
    }

    /// Get a specific procedure
    pub fn get_procedure(&self, name: &str) -> Option<&StoredProcedure> {
        self.procedures.get(name)
    }
}

impl Default for ProcedureRegistry {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[test]
    fn test_parameter_creation() {
        let param = ProcedureParameter::new("user_id", "INTEGER")
            .with_mode(ParameterMode::In)
            .with_default("0");

        assert_eq!(param.name, "user_id");
        assert_eq!(param.data_type, "INTEGER");
        assert_eq!(param.mode, ParameterMode::In);
        assert_eq!(param.default_value, Some("0".to_string()));
    }

    #[test]
    fn test_parameter_sql_generation() {
        let in_param = ProcedureParameter::new("id", "INTEGER");
        assert_eq!(in_param.to_sql(), "id INTEGER");

        let out_param = ProcedureParameter::new("result", "TEXT").with_mode(ParameterMode::Out);
        assert_eq!(out_param.to_sql(), "OUT result TEXT");

        let inout_param = ProcedureParameter::new("counter", "INTEGER")
            .with_mode(ParameterMode::InOut)
            .with_default("1");
        assert_eq!(inout_param.to_sql(), "INOUT counter INTEGER DEFAULT 1");
    }

    #[test]
    fn test_stored_function_creation() {
        let function = StoredFunction::new("calculate_age")
            .with_parameter(ProcedureParameter::new("birth_date", "DATE"))
            .with_return_type("INTEGER")
            .with_body("BEGIN\n    RETURN EXTRACT(YEAR FROM AGE(birth_date));\nEND;")
            .with_volatility(FunctionVolatility::Immutable);

        assert_eq!(function.name, "calculate_age");
        assert_eq!(function.parameters.len(), 1);
        assert_eq!(function.return_type, Some("INTEGER".to_string()));
        assert_eq!(function.volatility, FunctionVolatility::Immutable);
    }

    #[test]
    fn test_stored_procedure_creation() {
        let procedure = StoredProcedure::new("update_user_status")
            .with_parameter(ProcedureParameter::new("user_id", "INTEGER"))
            .with_parameter(ProcedureParameter::new("new_status", "TEXT"))
            .with_body("BEGIN\n    UPDATE users SET status = new_status WHERE id = user_id;\n    COMMIT;\nEND;");

        assert_eq!(procedure.name, "update_user_status");
        assert_eq!(procedure.parameters.len(), 2);
    }

    #[test]
    fn test_function_ddl_generation() {
        let function = StoredFunction::new("get_user_name")
            .with_parameter(ProcedureParameter::new("user_id", "INTEGER"))
            .with_return_type("TEXT")
            .with_body("BEGIN\n    RETURN (SELECT name FROM users WHERE id = user_id);\nEND;");

        let ddl = function.generate_create_ddl();
        assert!(ddl.contains("CREATE OR REPLACE FUNCTION \"get_user_name\""));
        assert!(ddl.contains("user_id INTEGER"));
        assert!(ddl.contains("RETURNS TEXT"));
        assert!(ddl.contains("LANGUAGE plpgsql"));
        assert!(ddl.contains("VOLATILE"));
    }

    #[test]
    fn test_procedure_ddl_generation() {
        let procedure = StoredProcedure::new("batch_update")
            .with_parameter(ProcedureParameter::new("batch_size", "INTEGER"))
            .with_body("BEGIN\n    -- Update logic here\n    COMMIT;\nEND;");

        let ddl = procedure.generate_create_ddl();
        assert!(ddl.contains("CREATE OR REPLACE PROCEDURE \"batch_update\""));
        assert!(ddl.contains("batch_size INTEGER"));
        assert!(!ddl.contains("RETURNS")); // Procedures don't have return types
        assert!(ddl.contains("LANGUAGE plpgsql"));
    }

    #[test]
    fn test_function_with_out_parameters() {
        let function = StoredFunction::new("get_user_stats")
            .with_parameter(ProcedureParameter::new("user_id", "INTEGER"))
            .with_parameter(ProcedureParameter::new("total_posts", "INTEGER").with_mode(ParameterMode::Out))
            .with_parameter(ProcedureParameter::new("last_login", "TIMESTAMP").with_mode(ParameterMode::Out))
            .with_body("BEGIN\n    SELECT COUNT(*), MAX(login_time) INTO total_posts, last_login FROM user_activity WHERE user_id = user_id;\nEND;");

        let ddl = function.generate_create_ddl();
        assert!(ddl.contains("RETURNS RECORD")); // Multiple OUT parameters return RECORD
        assert!(ddl.contains("OUT total_posts INTEGER"));
        assert!(ddl.contains("OUT last_login TIMESTAMP"));
    }

    #[test]
    fn test_registry() {
        let mut registry = ProcedureRegistry::new();

        let function = StoredFunction::new("test_func").with_return_type("INTEGER");
        let procedure = StoredProcedure::new("test_proc");

        registry.register_function(function);
        registry.register_procedure(procedure);

        assert_eq!(registry.all_functions().count(), 1);
        assert_eq!(registry.all_procedures().count(), 1);
        assert!(registry.get_function("\"test_func\"").is_some());
        assert!(registry.get_procedure("\"test_proc\"").is_some());
    }
}