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
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
use crate::builders::traits::{
    ConditionalBuilder, InspectableBuilder, SchemaBuilder, ValidatableBuilder,
};
use crate::builders::validation::FunctionBuildError;
use crate::schema::{
    FunctionSecurity, FunctionVolatility, ProcedureLanguage, ProcedureParameter, StoredFunction,
};
use std::collections::HashSet;

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

impl FunctionBuilder {
    /// Create a new function builder
    pub fn new() -> Self {
        Self {
            name: None,
            schema: None,
            parameters: Vec::new(),
            return_type: None,
            language: None,
            volatility: None,
            security: Option::None,
            body: None,
            comment: None,
        }
    }

    /// Set the function name (can be schema-qualified like "auth.my_function")
    pub fn name(mut self, name: impl Into<String>) -> Self {
        let full_name = name.into();

        // Check if the name is schema-qualified (contains a dot)
        if let Some(dot_pos) = full_name.find('.') {
            let schema_name = &full_name[..dot_pos];
            let function_name = &full_name[dot_pos + 1..];

            self.schema = Some(schema_name.to_string());
            self.name = Some(function_name.to_string());
        } else {
            self.name = Some(full_name);
        }

        self
    }

    /// Set the function name (mutable reference version for conditional building)
    /// Can be schema-qualified like "auth.my_function"
    pub fn set_name(&mut self, name: impl Into<String>) {
        let full_name = name.into();

        // Check if the name is schema-qualified (contains a dot)
        if let Some(dot_pos) = full_name.find('.') {
            let schema_name = &full_name[..dot_pos];
            let function_name = &full_name[dot_pos + 1..];

            self.schema = Some(schema_name.to_string());
            self.name = Some(function_name.to_string());
        } else {
            self.name = Some(full_name);
        }
    }

    /// 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 function
    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 function (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 function
    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 function (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 return type
    pub fn returns(mut self, return_type: impl Into<String>) -> Self {
        self.return_type = Some(return_type.into());
        self
    }

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

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

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

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

    /// Set the function volatility (mutable reference version for conditional building)
    pub fn set_volatility(&mut self, volatility: FunctionVolatility) {
        self.volatility = Some(volatility);
    }

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

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

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

    /// Set the function 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 function
    pub fn comment(mut self, comment: impl Into<String>) -> Self {
        self.comment = Some(comment.into());
        self
    }

    /// Set a comment on the function (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 function patterns
    /// Create a simple function
    pub fn simple() -> Self {
        Self::new()
    }

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

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

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

    /// Create an immutable function
    pub fn immutable() -> Self {
        Self::new().volatility(FunctionVolatility::Immutable)
    }

    /// Create a stable function
    pub fn stable() -> Self {
        Self::new().volatility(FunctionVolatility::Stable)
    }

    /// Create a volatile function
    pub fn volatile() -> Self {
        Self::new().volatility(FunctionVolatility::Volatile)
    }

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

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

    /// Create a math function
    pub fn math() -> Self {
        Self::new()
            .language(ProcedureLanguage::Sql)
            .volatility(FunctionVolatility::Immutable)
    }

    /// Create a utility function
    pub fn utility() -> Self {
        Self::new()
            .language(ProcedureLanguage::PlPgSql)
            .volatility(FunctionVolatility::Stable)
    }

    /// Create a trigger function
    pub fn trigger() -> Self {
        Self::new()
            .language(ProcedureLanguage::PlPgSql)
            .volatility(FunctionVolatility::Volatile)
            .returns("TRIGGER")
    }

    // Inspection methods
    /// Get the function name
    #[inline]
    pub fn get_name(&self) -> Option<&str> {
        self.name.as_deref()
    }

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

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

    /// Get the return type
    #[inline]
    pub fn get_return_type(&self) -> Option<&str> {
        self.return_type.as_deref()
    }

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

    /// Get the function volatility
    pub fn get_volatility(&self) -> Option<&FunctionVolatility> {
        self.volatility.as_ref()
    }

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

    /// Get the function 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 function
    pub fn parameter_count(&self) -> usize {
        self.parameters.len()
    }

    /// Check if the function 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 function has a name
    pub fn has_name(&self) -> bool {
        self.name.is_some()
    }

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

    /// Check if the function has a return type
    pub fn has_return_type(&self) -> bool {
        self.return_type.is_some()
    }

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

    /// Check if the function has a volatility
    pub fn has_volatility(&self) -> bool {
        self.volatility.is_some()
    }

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

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

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

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

impl SchemaBuilder for FunctionBuilder {
    type Output = StoredFunction;
    type Error = FunctionBuildError;

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

        // Build the function
        let function = StoredFunction {
            name: self.name.unwrap_or_else(|| "function".to_string()),
            schema: self.schema,
            parameters: self.parameters,
            return_type: self.return_type,
            language: self.language.unwrap_or(ProcedureLanguage::PlPgSql),
            body: self.body.unwrap_or_else(|| "SELECT 1".to_string()),
            volatility: self.volatility.unwrap_or(FunctionVolatility::Volatile),
            security: self.security.unwrap_or(FunctionSecurity::Invoker),
            strict: false, // Default to not strict
        };

        Ok(function)
    }
}

impl ValidatableBuilder for FunctionBuilder {
    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("Function 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("Function body cannot be empty".to_string());
            }
        }

        // Validate function name if provided
        if let Some(ref name) = self.name {
            if name.trim().is_empty() {
                errors.push("Function 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));
            }
        }

        // Validate return type if provided
        if let Some(ref return_type) = self.return_type {
            if return_type.trim().is_empty() {
                errors.push("Return type cannot be empty".to_string());
            }
        }

        errors
    }
}

impl ConditionalBuilder for FunctionBuilder {
    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 FunctionBuilder {
    fn debug_info(&self) -> String {
        format!(
            "FunctionBuilder {{ name: {:?}, schema: {:?}, parameters: {:?}, return_type: {:?}, language: {:?}, volatility: {:?}, security: {:?} }}",
            self.name, self.schema, self.parameters, self.return_type, self.language, self.volatility, self.security
        )
    }

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

        parts.push("Function".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(", ")
            ));
        }

        // Return type
        if let Some(ref return_type) = self.return_type {
            parts.push(format!("returns: {}", return_type));
        }

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

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

        // 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, FunctionVolatility, ProcedureLanguage};

    #[test]
    fn test_basic_function() {
        let function = FunctionBuilder::new()
            .name("add_numbers")
            .parameter("a", "INTEGER")
            .parameter("b", "INTEGER")
            .returns("INTEGER")
            .language(ProcedureLanguage::Sql)
            .body("SELECT a + b")
            .build()
            .unwrap();

        assert_eq!(function.name, "add_numbers");
        assert_eq!(function.parameters.len(), 2);
        assert_eq!(function.parameters[0].name, "a");
        assert_eq!(function.parameters[0].data_type, "INTEGER");
        assert_eq!(function.parameters[1].name, "b");
        assert_eq!(function.parameters[1].data_type, "INTEGER");
        assert_eq!(function.return_type, Some("INTEGER".to_string()));
        assert_eq!(function.language, ProcedureLanguage::Sql);
        assert_eq!(function.body, "SELECT a + b");
    }

    #[test]
    fn test_function_with_schema() {
        let function = FunctionBuilder::new()
            .name("calculate_area")
            .in_schema("math")
            .parameter("radius", "DOUBLE PRECISION")
            .returns("DOUBLE PRECISION")
            .body("SELECT PI() * radius * radius")
            .build()
            .unwrap();

        assert_eq!(function.name, "calculate_area");
        assert_eq!(function.schema, Some("math".to_string()));
        assert_eq!(function.parameters.len(), 1);
    }

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

        let immutable_func = FunctionBuilder::immutable()
            .name("get_constant")
            .returns("TEXT")
            .body("SELECT 'constant'")
            .build()
            .unwrap();

        let invoker_func = FunctionBuilder::invoker()
            .name("get_user_info")
            .parameter("user_id", "INTEGER")
            .returns("TEXT")
            .body("SELECT name FROM users WHERE id = user_id")
            .build()
            .unwrap();

        assert_eq!(plpgsql_func.language, ProcedureLanguage::PlPgSql);
        assert_eq!(immutable_func.volatility, FunctionVolatility::Immutable);
        assert_eq!(invoker_func.security, FunctionSecurity::Invoker);
    }

    #[test]
    fn test_function_with_multiple_parameters() {
        let function = FunctionBuilder::new()
            .name("create_user")
            .parameters(vec![
                ("name", "VARCHAR(255)"),
                ("email", "VARCHAR(255)"),
                ("age", "INTEGER"),
                ("is_active", "BOOLEAN"),
            ])
            .returns("INTEGER")
            .body("INSERT INTO users (name, email, age, is_active) VALUES (name, email, age, is_active) RETURNING id")
            .build()
            .unwrap();

        assert_eq!(function.name, "create_user");
        assert_eq!(function.parameters.len(), 4);
        assert_eq!(function.parameters[0].name, "name");
        assert_eq!(function.parameters[0].data_type, "VARCHAR(255)");
        assert_eq!(function.parameters[3].name, "is_active");
        assert_eq!(function.parameters[3].data_type, "BOOLEAN");
    }

    #[test]
    fn test_function_with_comment() {
        let function = FunctionBuilder::new()
            .name("validate_email")
            .parameter("email", "TEXT")
            .returns("BOOLEAN")
            .body("SELECT email ~ '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$'")
            .comment("Validates email format using regex")
            .build()
            .unwrap();

        assert_eq!(function.name, "validate_email");
        // Note: comment is not stored in the actual StoredFunction struct
    }

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

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

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

        assert_eq!(function.name, "function_when_true");
        assert_eq!(function.parameters.len(), 1);
    }

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

        assert_eq!(builder.get_name(), Some("test_function"));
        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_return_type());
        assert!(!builder.has_language());
        assert!(!builder.has_volatility());
        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 = FunctionBuilder::new()
            .name("calculate_distance")
            .in_schema("geometry")
            .parameters(vec![
                ("x1", "DOUBLE PRECISION"),
                ("y1", "DOUBLE PRECISION"),
                ("x2", "DOUBLE PRECISION"),
                ("y2", "DOUBLE PRECISION"),
            ])
            .returns("DOUBLE PRECISION")
            .language(ProcedureLanguage::Sql)
            .volatility(FunctionVolatility::Immutable)
            .comment("Calculates Euclidean distance between two points");

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

        assert!(debug_info.contains("FunctionBuilder"));
        assert!(debug_info.contains("calculate_distance"));
        assert!(debug_info.contains("geometry"));

        assert!(summary.contains("Function"));
        assert!(summary.contains("geometry.calculate_distance"));
        assert!(summary.contains("with parameters: x1: DOUBLE PRECISION, y1: DOUBLE PRECISION, x2: DOUBLE PRECISION, y2: DOUBLE PRECISION"));
        assert!(summary.contains("returns: DOUBLE PRECISION"));
        assert!(summary.contains("language: Sql"));
        assert!(summary.contains("volatility: Immutable"));
        // Note: comment is not stored in the actual StoredFunction struct
    }

    #[test]
    fn test_specialized_function_types() {
        let math_func = FunctionBuilder::math()
            .name("square_root")
            .parameter("value", "DOUBLE PRECISION")
            .returns("DOUBLE PRECISION")
            .body("SELECT SQRT(value)")
            .build()
            .unwrap();

        let utility_func = FunctionBuilder::utility()
            .name("get_current_user")
            .returns("TEXT")
            .body("SELECT current_user")
            .build()
            .unwrap();

        let trigger_func = FunctionBuilder::trigger()
            .name("audit_changes")
            .body("RETURN NEW")
            .build()
            .unwrap();

        assert_eq!(math_func.language, ProcedureLanguage::Sql);
        assert_eq!(math_func.volatility, FunctionVolatility::Immutable);
        assert_eq!(utility_func.language, ProcedureLanguage::PlPgSql);
        assert_eq!(utility_func.volatility, FunctionVolatility::Stable);
        assert_eq!(trigger_func.language, ProcedureLanguage::PlPgSql);
        assert_eq!(trigger_func.volatility, FunctionVolatility::Volatile);
        assert_eq!(trigger_func.return_type, Some("TRIGGER".to_string()));
    }

    #[test]
    fn test_function_with_all_properties() {
        let function = FunctionBuilder::new()
            .name("complex_calculation")
            .in_schema("finance")
            .parameters(vec![
                ("principal", "NUMERIC(19,4)"),
                ("rate", "NUMERIC(5,4)"),
                ("time", "NUMERIC(5,2)"),
            ])
            .returns("NUMERIC(19,4)")
            .language(ProcedureLanguage::PlPgSql)
            .volatility(FunctionVolatility::Immutable)
            .security(FunctionSecurity::Invoker)
            .body("RETURN principal * POWER(1 + rate, time)")
            .comment("Calculates compound interest")
            .build()
            .unwrap();

        assert_eq!(function.name, "complex_calculation");
        assert_eq!(function.schema, Some("finance".to_string()));
        assert_eq!(function.parameters.len(), 3);
        assert_eq!(function.return_type, Some("NUMERIC(19,4)".to_string()));
        assert_eq!(function.language, ProcedureLanguage::PlPgSql);
        assert_eq!(function.volatility, FunctionVolatility::Immutable);
        assert_eq!(function.security, FunctionSecurity::Invoker);
        assert_eq!(function.body, "RETURN principal * POWER(1 + rate, time)");
        // Note: comment is not stored in the actual StoredFunction struct
    }
}