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
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
use crate::builders::traits::{
    ConditionalBuilder, InspectableBuilder, SchemaBuilder, ValidatableBuilder,
};
use crate::builders::validation::ProcedureBuildError;
use crate::schema::{FunctionSecurity, ProcedureLanguage, ProcedureParameter, StoredProcedure};
use std::collections::HashSet;

/// Builder for constructing database stored procedures
#[derive(Debug, Clone)]
pub struct ProcedureBuilder {
    name: Option<String>,
    schema: Option<String>,
    parameters: Vec<ProcedureParameter>,
    language: Option<ProcedureLanguage>,
    security: Option<FunctionSecurity>,
    body: Option<String>,
    comment: Option<String>,
}

impl ProcedureBuilder {
    /// Create a new procedure builder
    pub fn new() -> Self {
        Self {
            name: None,
            schema: None,
            parameters: Vec::new(),
            language: None,
            security: None,
            body: None,
            comment: None,
        }
    }

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

    /// Set the procedure name (mutable reference version for conditional building)
    pub fn set_name(&mut self, name: impl Into<String>) {
        self.name = Some(name.into());
    }

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

    /// Set the schema name (mutable reference version for conditional building)
    pub fn set_schema(&mut self, schema: impl Into<String>) {
        self.schema = Some(schema.into());
    }

    /// Add a parameter to the procedure
    pub fn parameter(mut self, name: impl Into<String>, param_type: impl Into<String>) -> Self {
        let param = ProcedureParameter::new(name, param_type);
        self.parameters.push(param);
        self
    }

    /// Add a parameter to the procedure (mutable reference version for conditional building)
    pub fn add_parameter(&mut self, name: impl Into<String>, param_type: impl Into<String>) {
        let param = ProcedureParameter::new(name, param_type);
        self.parameters.push(param);
    }

    /// Add multiple parameters to the procedure
    pub fn parameters(
        mut self,
        params: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>,
    ) -> Self {
        for (name, param_type) in params {
            let param = ProcedureParameter::new(name, param_type);
            self.parameters.push(param);
        }
        self
    }

    /// Add multiple parameters to the procedure (mutable reference version for conditional building)
    pub fn add_parameters(
        &mut self,
        params: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>,
    ) {
        for (name, param_type) in params {
            let param = ProcedureParameter::new(name, param_type);
            self.parameters.push(param);
        }
    }

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

    /// Set the procedure language (mutable reference version for conditional building)
    pub fn set_language(&mut self, language: ProcedureLanguage) {
        self.language = Some(language);
    }

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

    /// Set the procedure security (mutable reference version for conditional building)
    pub fn set_security(&mut self, security: FunctionSecurity) {
        self.security = Some(security);
    }

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

    /// Set the procedure body (mutable reference version for conditional building)
    pub fn set_body(&mut self, body: impl Into<String>) {
        self.body = Some(body.into());
    }

    /// Set a comment on the procedure
    pub fn comment(mut self, comment: impl Into<String>) -> Self {
        self.comment = Some(comment.into());
        self
    }

    /// Set a comment on the procedure (mutable reference version for conditional building)
    pub fn set_comment(&mut self, comment: impl Into<String>) {
        self.comment = Some(comment.into());
    }

    // Convenience methods for specific procedure patterns
    /// Create a simple procedure
    pub fn simple() -> Self {
        Self::new()
    }

    /// Create a PL/pgSQL procedure
    pub fn plpgsql() -> Self {
        Self::new().language(ProcedureLanguage::PlPgSql)
    }

    /// Create a SQL procedure
    pub fn sql() -> Self {
        Self::new().language(ProcedureLanguage::Sql)
    }

    /// Create a Python procedure
    pub fn python() -> Self {
        Self::new().language(ProcedureLanguage::PlPython3)
    }

    /// Create a C procedure
    pub fn c() -> Self {
        Self::new().language(ProcedureLanguage::C)
    }

    /// Create a procedure with invoker security
    pub fn invoker() -> Self {
        Self::new().security(FunctionSecurity::Invoker)
    }

    /// Create a procedure with definer security
    pub fn definer() -> Self {
        Self::new().security(FunctionSecurity::Definer)
    }

    /// Create a data manipulation procedure
    pub fn dml() -> Self {
        Self::new()
            .language(ProcedureLanguage::PlPgSql)
            .security(FunctionSecurity::Invoker)
    }

    /// Create an administrative procedure
    pub fn admin() -> Self {
        Self::new()
            .language(ProcedureLanguage::PlPgSql)
            .security(FunctionSecurity::Definer)
    }

    /// Create a utility procedure
    pub fn utility() -> Self {
        Self::new()
            .language(ProcedureLanguage::PlPgSql)
            .security(FunctionSecurity::Invoker)
    }

    // Inspection methods
    /// Get the procedure name
    pub fn get_name(&self) -> Option<&str> {
        self.name.as_deref()
    }

    /// Get the schema name
    pub fn get_schema(&self) -> Option<&str> {
        self.schema.as_deref()
    }

    /// Get the parameters in the procedure
    pub fn get_parameters(&self) -> &[ProcedureParameter] {
        &self.parameters
    }

    /// Get the procedure language
    pub fn get_language(&self) -> Option<&ProcedureLanguage> {
        self.language.as_ref()
    }

    /// Get the procedure security
    pub fn get_security(&self) -> Option<&FunctionSecurity> {
        self.security.as_ref()
    }

    /// Get the procedure body
    pub fn get_body(&self) -> Option<&str> {
        self.body.as_deref()
    }

    /// Get the comment
    pub fn get_comment(&self) -> Option<&str> {
        self.comment.as_deref()
    }

    /// Get the number of parameters in the procedure
    pub fn parameter_count(&self) -> usize {
        self.parameters.len()
    }

    /// Check if the procedure has a specific parameter
    pub fn has_parameter(&self, param_name: &str) -> bool {
        self.parameters.iter().any(|p| p.name == param_name)
    }

    /// Get a specific parameter by name
    pub fn get_parameter(&self, param_name: &str) -> Option<&ProcedureParameter> {
        self.parameters.iter().find(|p| p.name == param_name)
    }

    /// Check if the procedure has a name
    pub fn has_name(&self) -> bool {
        self.name.is_some()
    }

    /// Check if the procedure has a schema
    pub fn has_schema(&self) -> bool {
        self.schema.is_some()
    }

    /// Check if the procedure has a language
    pub fn has_language(&self) -> bool {
        self.language.is_some()
    }

    /// Check if the procedure has a security setting
    pub fn has_security(&self) -> bool {
        self.security.is_some()
    }

    /// Check if the procedure has a body
    pub fn has_body(&self) -> bool {
        self.body.is_some()
    }

    /// Check if the procedure has a comment
    pub fn has_comment(&self) -> bool {
        self.comment.is_some()
    }

    /// Check if the procedure has parameters
    pub fn has_parameters(&self) -> bool {
        !self.parameters.is_empty()
    }
}

impl SchemaBuilder for ProcedureBuilder {
    type Output = StoredProcedure;
    type Error = ProcedureBuildError;

    fn build(self) -> Result<Self::Output, Self::Error> {
        // Validate the procedure before building
        if !self.is_valid() {
            let errors = self.validation_errors();
            return Err(ProcedureBuildError::ValidationError(errors.join("; ")));
        }

        // Build the procedure
        let procedure = StoredProcedure {
            name: self.name.unwrap_or_else(|| "procedure".to_string()),
            schema: self.schema,
            parameters: self.parameters,
            language: self.language.unwrap_or(ProcedureLanguage::PlPgSql),
            body: self.body.unwrap_or_else(|| "SELECT 1".to_string()),
            security: self.security.unwrap_or(FunctionSecurity::Invoker),
        };

        Ok(procedure)
    }
}

impl ValidatableBuilder for ProcedureBuilder {
    fn is_valid(&self) -> bool {
        self.validation_errors().is_empty()
    }

    fn validation_errors(&self) -> Vec<String> {
        let mut errors = Vec::new();

        // Validate that a body is specified
        if self.body.is_none() {
            errors.push("Procedure must have a body".to_string());
        }

        // Validate body is not empty if provided
        if let Some(ref body) = self.body {
            if body.trim().is_empty() {
                errors.push("Procedure body cannot be empty".to_string());
            }
        }

        // Validate procedure name if provided
        if let Some(ref name) = self.name {
            if name.trim().is_empty() {
                errors.push("Procedure name cannot be empty".to_string());
            }
        }

        // Validate schema name if provided
        if let Some(ref schema) = self.schema {
            if schema.trim().is_empty() {
                errors.push("Schema name cannot be empty".to_string());
            }
        }

        // Validate parameter names are not empty
        for (i, param) in self.parameters.iter().enumerate() {
            if param.name.trim().is_empty() {
                errors.push(format!("Parameter {} at index {} cannot be empty", i, i));
            }
        }

        // Check for duplicate parameter names
        let mut seen_params = HashSet::new();
        for param in &self.parameters {
            if !seen_params.insert(&param.name) {
                errors.push(format!("Duplicate parameter name: {}", param.name));
            }
        }

        errors
    }
}

impl ConditionalBuilder for ProcedureBuilder {
    fn when<F>(mut self, condition: bool, config_fn: F) -> Self
    where
        F: FnOnce(&mut Self),
        Self: Sized,
    {
        if condition {
            config_fn(&mut self);
        }
        self
    }
}

impl InspectableBuilder for ProcedureBuilder {
    fn debug_info(&self) -> String {
        format!(
            "ProcedureBuilder {{ name: {:?}, schema: {:?}, parameters: {:?}, language: {:?}, security: {:?} }}",
            self.name, self.schema, self.parameters, self.language, self.security
        )
    }

    fn summary(&self) -> String {
        let mut parts = Vec::new();

        parts.push("Procedure".to_string());

        // Name and schema
        if let Some(ref name) = self.name {
            if let Some(ref schema) = self.schema {
                parts.push(format!("{}.{}", schema, name));
            } else {
                parts.push(format!("'{}'", name));
            }
        }

        // Parameters
        if !self.parameters.is_empty() {
            let param_descriptions: Vec<String> = self
                .parameters
                .iter()
                .map(|p| format!("{}: {}", p.name, p.data_type))
                .collect();
            parts.push(format!(
                "with parameters: {}",
                param_descriptions.join(", ")
            ));
        }

        // Language
        if let Some(ref language) = self.language {
            parts.push(format!("language: {:?}", language));
        }

        // Security
        if let Some(ref security) = self.security {
            parts.push(format!("security: {:?}", security));
        }

        // Comment
        if let Some(ref comment) = self.comment {
            parts.push(format!("with comment: {}", comment));
        }

        parts.join(", ")
    }
}

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

    #[test]
    fn test_basic_procedure() {
        let procedure = ProcedureBuilder::new()
            .name("create_user")
            .parameter("name", "VARCHAR(255)")
            .parameter("email", "VARCHAR(255)")
            .language(ProcedureLanguage::PlPgSql)
            .body("INSERT INTO users (name, email) VALUES (name, email)")
            .build()
            .unwrap();

        assert_eq!(procedure.name, "create_user");
        assert_eq!(procedure.parameters.len(), 2);
        assert_eq!(procedure.parameters[0].name, "name");
        assert_eq!(procedure.parameters[0].data_type, "VARCHAR(255)");
        assert_eq!(procedure.parameters[1].name, "email");
        assert_eq!(procedure.parameters[1].data_type, "VARCHAR(255)");
        assert_eq!(procedure.language, ProcedureLanguage::PlPgSql);
        assert_eq!(
            procedure.body,
            "INSERT INTO users (name, email) VALUES (name, email)"
        );
    }

    #[test]
    fn test_procedure_with_schema() {
        let procedure = ProcedureBuilder::new()
            .name("update_user_status")
            .in_schema("user_management")
            .parameter("user_id", "INTEGER")
            .parameter("status", "TEXT")
            .body("UPDATE users SET status = update_user_status.status WHERE id = user_id")
            .build()
            .unwrap();

        assert_eq!(procedure.name, "update_user_status");
        assert_eq!(procedure.schema, Some("user_management".to_string()));
        assert_eq!(procedure.parameters.len(), 2);
    }

    #[test]
    fn test_convenience_methods() {
        let plpgsql_proc = ProcedureBuilder::plpgsql()
            .name("get_user_count")
            .body("SELECT COUNT(*) FROM users")
            .build()
            .unwrap();

        let invoker_proc = ProcedureBuilder::invoker()
            .name("get_user_info")
            .parameter("user_id", "INTEGER")
            .body("SELECT name FROM users WHERE id = user_id")
            .build()
            .unwrap();

        let definer_proc = ProcedureBuilder::definer()
            .name("admin_operation")
            .parameter("operation", "TEXT")
            .body("SELECT true")
            .build()
            .unwrap();

        assert_eq!(plpgsql_proc.language, ProcedureLanguage::PlPgSql);
        assert_eq!(invoker_proc.security, FunctionSecurity::Invoker);
        assert_eq!(definer_proc.security, FunctionSecurity::Definer);
    }

    #[test]
    fn test_procedure_with_multiple_parameters() {
        let procedure = ProcedureBuilder::new()
            .name("bulk_insert_users")
            .parameters(vec![
                ("names", "TEXT[]"),
                ("emails", "TEXT[]"),
                ("ages", "INTEGER[]"),
            ])
            .body("INSERT INTO users (name, email, age) SELECT unnest(names), unnest(emails), unnest(ages)")
            .build()
            .unwrap();

        assert_eq!(procedure.name, "bulk_insert_users");
        assert_eq!(procedure.parameters.len(), 3);
        assert_eq!(procedure.parameters[0].name, "names");
        assert_eq!(procedure.parameters[0].data_type, "TEXT[]");
        assert_eq!(procedure.parameters[2].name, "ages");
        assert_eq!(procedure.parameters[2].data_type, "INTEGER[]");
    }

    #[test]
    fn test_procedure_with_comment() {
        let procedure = ProcedureBuilder::new()
            .name("cleanup_old_records")
            .parameter("days_old", "INTEGER")
            .body("DELETE FROM logs WHERE created_at < NOW() - INTERVAL '1 day' * days_old")
            .comment("Removes log records older than specified days")
            .build()
            .unwrap();

        assert_eq!(procedure.name, "cleanup_old_records");
        // Note: comment is not stored in the actual StoredProcedure struct
    }

    #[test]
    fn test_validation_errors() {
        // No body
        let result = ProcedureBuilder::new().name("test").build();
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            ProcedureBuildError::ValidationError(_)
        ));

        // Empty body
        let result = ProcedureBuilder::new().name("test").body("").build();
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            ProcedureBuildError::ValidationError(_)
        ));
    }

    #[test]
    fn test_conditional_builder() {
        let condition = true;
        let procedure = ProcedureBuilder::new()
            .when(condition, |p| {
                p.set_name("procedure_when_true");
                p.add_parameter("param1", "INTEGER");
                p.set_body("SELECT param1 * 2");
            })
            .build()
            .unwrap();

        assert_eq!(procedure.name, "procedure_when_true");
        assert_eq!(procedure.parameters.len(), 1);
    }

    #[test]
    fn test_inspection_methods() {
        let builder = ProcedureBuilder::new()
            .name("test_procedure")
            .in_schema("public")
            .parameters(vec![("param1", "TEXT"), ("param2", "INTEGER")]);

        assert_eq!(builder.get_name(), Some("test_procedure"));
        assert_eq!(builder.get_schema(), Some("public"));
        assert_eq!(builder.get_parameters().len(), 2);
        assert_eq!(builder.parameter_count(), 2);
        assert!(builder.has_parameter("param1"));
        assert!(!builder.has_parameter("nonexistent"));
        assert!(builder.has_name());
        assert!(builder.has_schema());
        assert!(builder.has_parameters());
        assert!(!builder.has_language());
        assert!(!builder.has_security());
        assert!(!builder.has_body());
        assert!(!builder.has_comment());

        let param = builder.get_parameter("param1");
        assert!(param.is_some());
        assert_eq!(param.unwrap().name, "param1");
        assert_eq!(param.unwrap().data_type, "TEXT");
    }

    #[test]
    fn test_debug_info_and_summary() {
        let builder = ProcedureBuilder::new()
            .name("calculate_statistics")
            .in_schema("analytics")
            .parameters(vec![
                ("start_date", "DATE"),
                ("end_date", "DATE"),
                ("metric_type", "TEXT"),
            ])
            .language(ProcedureLanguage::PlPgSql)
            .security(FunctionSecurity::Invoker)
            .comment("Calculates various statistics for the given date range");

        let debug_info = builder.debug_info();
        let summary = builder.summary();

        assert!(debug_info.contains("ProcedureBuilder"));
        assert!(debug_info.contains("calculate_statistics"));
        assert!(debug_info.contains("analytics"));

        assert!(summary.contains("Procedure"));
        assert!(summary.contains("analytics.calculate_statistics"));
        assert!(summary
            .contains("with parameters: start_date: DATE, end_date: DATE, metric_type: TEXT"));
        assert!(summary.contains("language: PlPgSql"));
        assert!(summary.contains("security: Invoker"));
        // Note: comment is not stored in the actual StoredProcedure struct
    }

    #[test]
    fn test_specialized_procedure_types() {
        let dml_proc = ProcedureBuilder::dml()
            .name("insert_user")
            .parameter("name", "TEXT")
            .parameter("email", "TEXT")
            .body("INSERT INTO users (name, email) VALUES (name, email)")
            .build()
            .unwrap();

        let admin_proc = ProcedureBuilder::admin()
            .name("reset_database")
            .body("TRUNCATE TABLE users CASCADE")
            .build()
            .unwrap();

        let utility_proc = ProcedureBuilder::utility()
            .name("get_system_info")
            .body("SELECT version(), current_database()")
            .build()
            .unwrap();

        assert_eq!(dml_proc.language, ProcedureLanguage::PlPgSql);
        assert_eq!(dml_proc.security, FunctionSecurity::Invoker);
        assert_eq!(admin_proc.language, ProcedureLanguage::PlPgSql);
        assert_eq!(admin_proc.security, FunctionSecurity::Definer);
        assert_eq!(utility_proc.language, ProcedureLanguage::PlPgSql);
        assert_eq!(utility_proc.security, FunctionSecurity::Invoker);
    }

    #[test]
    fn test_procedure_with_all_properties() {
        let procedure = ProcedureBuilder::new()
            .name("complex_operation")
            .in_schema("operations")
            .parameters(vec![
                ("input_data", "JSONB"),
                ("options", "JSONB"),
                ("user_id", "INTEGER"),
            ])
            .language(ProcedureLanguage::PlPgSql)
            .security(FunctionSecurity::Definer)
            .body(
                "
                -- Complex multi-step operation
                BEGIN
                    -- Step 1: Validate input
                    IF input_data IS NULL THEN
                        RAISE EXCEPTION 'Input data cannot be null';
                    END IF;
                    
                    -- Step 2: Process data
                    -- ... complex logic here ...
                    
                    -- Step 3: Log operation
                    INSERT INTO operation_logs (user_id, operation_type, input_data, created_at)
                    VALUES (user_id, 'complex_operation', input_data, NOW());
                    
                    COMMIT;
                EXCEPTION
                    WHEN OTHERS THEN
                        ROLLBACK;
                        RAISE;
                END;
            ",
            )
            .comment("Performs complex multi-step operations with transaction management")
            .build()
            .unwrap();

        assert_eq!(procedure.name, "complex_operation");
        assert_eq!(procedure.schema, Some("operations".to_string()));
        assert_eq!(procedure.parameters.len(), 3);
        assert_eq!(procedure.language, ProcedureLanguage::PlPgSql);
        assert_eq!(procedure.security, FunctionSecurity::Definer);
        assert!(procedure.body.contains("BEGIN"));
        assert!(procedure.body.contains("COMMIT"));
        assert!(procedure.body.contains("ROLLBACK"));
        // Note: comment is not stored in the actual StoredProcedure struct
    }
}