1use crate::builders::traits::{
2 ConditionalBuilder, InspectableBuilder, SchemaBuilder, ValidatableBuilder,
3};
4use crate::builders::validation::FunctionBuildError;
5use crate::schema::{
6 FunctionSecurity, FunctionVolatility, ProcedureLanguage, ProcedureParameter, StoredFunction,
7};
8use std::collections::HashSet;
9
10#[derive(Debug, Clone)]
12pub struct FunctionBuilder {
13 name: Option<String>,
14 schema: Option<String>,
15 parameters: Vec<ProcedureParameter>,
16 return_type: Option<String>,
17 language: Option<ProcedureLanguage>,
18 volatility: Option<FunctionVolatility>,
19 security: Option<FunctionSecurity>,
20 body: Option<String>,
21 comment: Option<String>,
22}
23
24impl FunctionBuilder {
25 pub fn new() -> Self {
27 Self {
28 name: None,
29 schema: None,
30 parameters: Vec::new(),
31 return_type: None,
32 language: None,
33 volatility: None,
34 security: Option::None,
35 body: None,
36 comment: None,
37 }
38 }
39
40 pub fn name(mut self, name: impl Into<String>) -> Self {
42 let full_name = name.into();
43
44 if let Some(dot_pos) = full_name.find('.') {
46 let schema_name = &full_name[..dot_pos];
47 let function_name = &full_name[dot_pos + 1..];
48
49 self.schema = Some(schema_name.to_string());
50 self.name = Some(function_name.to_string());
51 } else {
52 self.name = Some(full_name);
53 }
54
55 self
56 }
57
58 pub fn set_name(&mut self, name: impl Into<String>) {
61 let full_name = name.into();
62
63 if let Some(dot_pos) = full_name.find('.') {
65 let schema_name = &full_name[..dot_pos];
66 let function_name = &full_name[dot_pos + 1..];
67
68 self.schema = Some(schema_name.to_string());
69 self.name = Some(function_name.to_string());
70 } else {
71 self.name = Some(full_name);
72 }
73 }
74
75 pub fn in_schema(mut self, schema: impl Into<String>) -> Self {
77 self.schema = Some(schema.into());
78 self
79 }
80
81 pub fn set_schema(&mut self, schema: impl Into<String>) {
83 self.schema = Some(schema.into());
84 }
85
86 pub fn parameter(mut self, name: impl Into<String>, param_type: impl Into<String>) -> Self {
88 let param = ProcedureParameter::new(name, param_type);
89 self.parameters.push(param);
90 self
91 }
92
93 pub fn add_parameter(&mut self, name: impl Into<String>, param_type: impl Into<String>) {
95 let param = ProcedureParameter::new(name, param_type);
96 self.parameters.push(param);
97 }
98
99 pub fn parameters(
101 mut self,
102 params: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>,
103 ) -> Self {
104 for (name, param_type) in params {
105 let param = ProcedureParameter::new(name, param_type);
106 self.parameters.push(param);
107 }
108 self
109 }
110
111 pub fn add_parameters(
113 &mut self,
114 params: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>,
115 ) {
116 for (name, param_type) in params {
117 let param = ProcedureParameter::new(name, param_type);
118 self.parameters.push(param);
119 }
120 }
121
122 pub fn returns(mut self, return_type: impl Into<String>) -> Self {
124 self.return_type = Some(return_type.into());
125 self
126 }
127
128 pub fn set_return_type(&mut self, return_type: impl Into<String>) {
130 self.return_type = Some(return_type.into());
131 }
132
133 pub fn language(mut self, language: ProcedureLanguage) -> Self {
135 self.language = Some(language);
136 self
137 }
138
139 pub fn set_language(&mut self, language: ProcedureLanguage) {
141 self.language = Some(language);
142 }
143
144 pub fn volatility(mut self, volatility: FunctionVolatility) -> Self {
146 self.volatility = Some(volatility);
147 self
148 }
149
150 pub fn set_volatility(&mut self, volatility: FunctionVolatility) {
152 self.volatility = Some(volatility);
153 }
154
155 pub fn security(mut self, security: FunctionSecurity) -> Self {
157 self.security = Some(security);
158 self
159 }
160
161 pub fn set_security(&mut self, security: FunctionSecurity) {
163 self.security = Some(security);
164 }
165
166 pub fn body(mut self, body: impl Into<String>) -> Self {
168 self.body = Some(body.into());
169 self
170 }
171
172 pub fn set_body(&mut self, body: impl Into<String>) {
174 self.body = Some(body.into());
175 }
176
177 pub fn comment(mut self, comment: impl Into<String>) -> Self {
179 self.comment = Some(comment.into());
180 self
181 }
182
183 pub fn set_comment(&mut self, comment: impl Into<String>) {
185 self.comment = Some(comment.into());
186 }
187
188 pub fn simple() -> Self {
191 Self::new()
192 }
193
194 pub fn plpgsql() -> Self {
196 Self::new().language(ProcedureLanguage::PlPgSql)
197 }
198
199 pub fn sql() -> Self {
201 Self::new().language(ProcedureLanguage::Sql)
202 }
203
204 pub fn c() -> Self {
206 Self::new().language(ProcedureLanguage::C)
207 }
208
209 pub fn immutable() -> Self {
211 Self::new().volatility(FunctionVolatility::Immutable)
212 }
213
214 pub fn stable() -> Self {
216 Self::new().volatility(FunctionVolatility::Stable)
217 }
218
219 pub fn volatile() -> Self {
221 Self::new().volatility(FunctionVolatility::Volatile)
222 }
223
224 pub fn invoker() -> Self {
226 Self::new().security(FunctionSecurity::Invoker)
227 }
228
229 pub fn definer() -> Self {
231 Self::new().security(FunctionSecurity::Definer)
232 }
233
234 pub fn math() -> Self {
236 Self::new()
237 .language(ProcedureLanguage::Sql)
238 .volatility(FunctionVolatility::Immutable)
239 }
240
241 pub fn utility() -> Self {
243 Self::new()
244 .language(ProcedureLanguage::PlPgSql)
245 .volatility(FunctionVolatility::Stable)
246 }
247
248 pub fn trigger() -> Self {
250 Self::new()
251 .language(ProcedureLanguage::PlPgSql)
252 .volatility(FunctionVolatility::Volatile)
253 .returns("TRIGGER")
254 }
255
256 #[inline]
259 pub fn get_name(&self) -> Option<&str> {
260 self.name.as_deref()
261 }
262
263 #[inline]
265 pub fn get_schema(&self) -> Option<&str> {
266 self.schema.as_deref()
267 }
268
269 #[inline]
271 pub fn get_parameters(&self) -> &[ProcedureParameter] {
272 &self.parameters
273 }
274
275 #[inline]
277 pub fn get_return_type(&self) -> Option<&str> {
278 self.return_type.as_deref()
279 }
280
281 pub fn get_language(&self) -> Option<&ProcedureLanguage> {
283 self.language.as_ref()
284 }
285
286 pub fn get_volatility(&self) -> Option<&FunctionVolatility> {
288 self.volatility.as_ref()
289 }
290
291 pub fn get_security(&self) -> Option<&FunctionSecurity> {
293 self.security.as_ref()
294 }
295
296 pub fn get_body(&self) -> Option<&str> {
298 self.body.as_deref()
299 }
300
301 pub fn get_comment(&self) -> Option<&str> {
303 self.comment.as_deref()
304 }
305
306 pub fn parameter_count(&self) -> usize {
308 self.parameters.len()
309 }
310
311 pub fn has_parameter(&self, param_name: &str) -> bool {
313 self.parameters.iter().any(|p| p.name == param_name)
314 }
315
316 pub fn get_parameter(&self, param_name: &str) -> Option<&ProcedureParameter> {
318 self.parameters.iter().find(|p| p.name == param_name)
319 }
320
321 pub fn has_name(&self) -> bool {
323 self.name.is_some()
324 }
325
326 pub fn has_schema(&self) -> bool {
328 self.schema.is_some()
329 }
330
331 pub fn has_return_type(&self) -> bool {
333 self.return_type.is_some()
334 }
335
336 pub fn has_language(&self) -> bool {
338 self.language.is_some()
339 }
340
341 pub fn has_volatility(&self) -> bool {
343 self.volatility.is_some()
344 }
345
346 pub fn has_security(&self) -> bool {
348 self.security.is_some()
349 }
350
351 pub fn has_body(&self) -> bool {
353 self.body.is_some()
354 }
355
356 pub fn has_comment(&self) -> bool {
358 self.comment.is_some()
359 }
360
361 pub fn has_parameters(&self) -> bool {
363 !self.parameters.is_empty()
364 }
365}
366
367impl SchemaBuilder for FunctionBuilder {
368 type Output = StoredFunction;
369 type Error = FunctionBuildError;
370
371 fn build(self) -> Result<Self::Output, Self::Error> {
372 if !self.is_valid() {
374 let errors = self.validation_errors();
375 return Err(FunctionBuildError::ValidationError(errors.join("; ")));
376 }
377
378 let function = StoredFunction {
380 name: self.name.unwrap_or_else(|| "function".to_string()),
381 schema: self.schema,
382 parameters: self.parameters,
383 return_type: self.return_type,
384 language: self.language.unwrap_or(ProcedureLanguage::PlPgSql),
385 body: self.body.unwrap_or_else(|| "SELECT 1".to_string()),
386 volatility: self.volatility.unwrap_or(FunctionVolatility::Volatile),
387 security: self.security.unwrap_or(FunctionSecurity::Invoker),
388 strict: false, };
390
391 Ok(function)
392 }
393}
394
395impl ValidatableBuilder for FunctionBuilder {
396 fn is_valid(&self) -> bool {
397 self.validation_errors().is_empty()
398 }
399
400 fn validation_errors(&self) -> Vec<String> {
401 let mut errors = Vec::new();
402
403 if self.body.is_none() {
405 errors.push("Function must have a body".to_string());
406 }
407
408 if let Some(ref body) = self.body {
410 if body.trim().is_empty() {
411 errors.push("Function body cannot be empty".to_string());
412 }
413 }
414
415 if let Some(ref name) = self.name {
417 if name.trim().is_empty() {
418 errors.push("Function name cannot be empty".to_string());
419 }
420 }
421
422 if let Some(ref schema) = self.schema {
424 if schema.trim().is_empty() {
425 errors.push("Schema name cannot be empty".to_string());
426 }
427 }
428
429 for (i, param) in self.parameters.iter().enumerate() {
431 if param.name.trim().is_empty() {
432 errors.push(format!("Parameter {} at index {} cannot be empty", i, i));
433 }
434 }
435
436 let mut seen_params = HashSet::new();
438 for param in &self.parameters {
439 if !seen_params.insert(¶m.name) {
440 errors.push(format!("Duplicate parameter name: {}", param.name));
441 }
442 }
443
444 if let Some(ref return_type) = self.return_type {
446 if return_type.trim().is_empty() {
447 errors.push("Return type cannot be empty".to_string());
448 }
449 }
450
451 errors
452 }
453}
454
455impl ConditionalBuilder for FunctionBuilder {
456 fn when<F>(mut self, condition: bool, config_fn: F) -> Self
457 where
458 F: FnOnce(&mut Self),
459 Self: Sized,
460 {
461 if condition {
462 config_fn(&mut self);
463 }
464 self
465 }
466}
467
468impl InspectableBuilder for FunctionBuilder {
469 fn debug_info(&self) -> String {
470 format!(
471 "FunctionBuilder {{ name: {:?}, schema: {:?}, parameters: {:?}, return_type: {:?}, language: {:?}, volatility: {:?}, security: {:?} }}",
472 self.name, self.schema, self.parameters, self.return_type, self.language, self.volatility, self.security
473 )
474 }
475
476 fn summary(&self) -> String {
477 let mut parts = Vec::new();
478
479 parts.push("Function".to_string());
480
481 if let Some(ref name) = self.name {
483 if let Some(ref schema) = self.schema {
484 parts.push(format!("{}.{}", schema, name));
485 } else {
486 parts.push(format!("'{}'", name));
487 }
488 }
489
490 if !self.parameters.is_empty() {
492 let param_descriptions: Vec<String> = self
493 .parameters
494 .iter()
495 .map(|p| format!("{}: {}", p.name, p.data_type))
496 .collect();
497 parts.push(format!(
498 "with parameters: {}",
499 param_descriptions.join(", ")
500 ));
501 }
502
503 if let Some(ref return_type) = self.return_type {
505 parts.push(format!("returns: {}", return_type));
506 }
507
508 if let Some(ref language) = self.language {
510 parts.push(format!("language: {:?}", language));
511 }
512
513 if let Some(ref volatility) = self.volatility {
515 parts.push(format!("volatility: {:?}", volatility));
516 }
517
518 if let Some(ref security) = self.security {
520 parts.push(format!("security: {:?}", security));
521 }
522
523 if let Some(ref comment) = self.comment {
525 parts.push(format!("with comment: {}", comment));
526 }
527
528 parts.join(", ")
529 }
530}
531
532#[cfg(test)]
533mod tests {
534 use super::*;
535 use crate::schema::{FunctionSecurity, FunctionVolatility, ProcedureLanguage};
536
537 #[test]
538 fn test_basic_function() {
539 let function = FunctionBuilder::new()
540 .name("add_numbers")
541 .parameter("a", "INTEGER")
542 .parameter("b", "INTEGER")
543 .returns("INTEGER")
544 .language(ProcedureLanguage::Sql)
545 .body("SELECT a + b")
546 .build()
547 .unwrap();
548
549 assert_eq!(function.name, "add_numbers");
550 assert_eq!(function.parameters.len(), 2);
551 assert_eq!(function.parameters[0].name, "a");
552 assert_eq!(function.parameters[0].data_type, "INTEGER");
553 assert_eq!(function.parameters[1].name, "b");
554 assert_eq!(function.parameters[1].data_type, "INTEGER");
555 assert_eq!(function.return_type, Some("INTEGER".to_string()));
556 assert_eq!(function.language, ProcedureLanguage::Sql);
557 assert_eq!(function.body, "SELECT a + b");
558 }
559
560 #[test]
561 fn test_function_with_schema() {
562 let function = FunctionBuilder::new()
563 .name("calculate_area")
564 .in_schema("math")
565 .parameter("radius", "DOUBLE PRECISION")
566 .returns("DOUBLE PRECISION")
567 .body("SELECT PI() * radius * radius")
568 .build()
569 .unwrap();
570
571 assert_eq!(function.name, "calculate_area");
572 assert_eq!(function.schema, Some("math".to_string()));
573 assert_eq!(function.parameters.len(), 1);
574 }
575
576 #[test]
577 fn test_convenience_methods() {
578 let plpgsql_func = FunctionBuilder::plpgsql()
579 .name("get_user_count")
580 .returns("INTEGER")
581 .body("SELECT COUNT(*) FROM users")
582 .build()
583 .unwrap();
584
585 let immutable_func = FunctionBuilder::immutable()
586 .name("get_constant")
587 .returns("TEXT")
588 .body("SELECT 'constant'")
589 .build()
590 .unwrap();
591
592 let invoker_func = FunctionBuilder::invoker()
593 .name("get_user_info")
594 .parameter("user_id", "INTEGER")
595 .returns("TEXT")
596 .body("SELECT name FROM users WHERE id = user_id")
597 .build()
598 .unwrap();
599
600 assert_eq!(plpgsql_func.language, ProcedureLanguage::PlPgSql);
601 assert_eq!(immutable_func.volatility, FunctionVolatility::Immutable);
602 assert_eq!(invoker_func.security, FunctionSecurity::Invoker);
603 }
604
605 #[test]
606 fn test_function_with_multiple_parameters() {
607 let function = FunctionBuilder::new()
608 .name("create_user")
609 .parameters(vec![
610 ("name", "VARCHAR(255)"),
611 ("email", "VARCHAR(255)"),
612 ("age", "INTEGER"),
613 ("is_active", "BOOLEAN"),
614 ])
615 .returns("INTEGER")
616 .body("INSERT INTO users (name, email, age, is_active) VALUES (name, email, age, is_active) RETURNING id")
617 .build()
618 .unwrap();
619
620 assert_eq!(function.name, "create_user");
621 assert_eq!(function.parameters.len(), 4);
622 assert_eq!(function.parameters[0].name, "name");
623 assert_eq!(function.parameters[0].data_type, "VARCHAR(255)");
624 assert_eq!(function.parameters[3].name, "is_active");
625 assert_eq!(function.parameters[3].data_type, "BOOLEAN");
626 }
627
628 #[test]
629 fn test_function_with_comment() {
630 let function = FunctionBuilder::new()
631 .name("validate_email")
632 .parameter("email", "TEXT")
633 .returns("BOOLEAN")
634 .body("SELECT email ~ '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$'")
635 .comment("Validates email format using regex")
636 .build()
637 .unwrap();
638
639 assert_eq!(function.name, "validate_email");
640 }
642
643 #[test]
644 fn test_validation_errors() {
645 let result = FunctionBuilder::new().name("test").build();
647 assert!(result.is_err());
648 assert!(matches!(
649 result.unwrap_err(),
650 FunctionBuildError::ValidationError(_)
651 ));
652
653 let result = FunctionBuilder::new().name("test").body("").build();
655 assert!(result.is_err());
656 assert!(matches!(
657 result.unwrap_err(),
658 FunctionBuildError::ValidationError(_)
659 ));
660 }
661
662 #[test]
663 fn test_conditional_builder() {
664 let condition = true;
665 let function = FunctionBuilder::new()
666 .when(condition, |f| {
667 f.set_name("function_when_true");
668 f.add_parameter("param1", "INTEGER");
669 f.set_body("SELECT param1 * 2");
670 })
671 .build()
672 .unwrap();
673
674 assert_eq!(function.name, "function_when_true");
675 assert_eq!(function.parameters.len(), 1);
676 }
677
678 #[test]
679 fn test_inspection_methods() {
680 let builder = FunctionBuilder::new()
681 .name("test_function")
682 .in_schema("public")
683 .parameters(vec![("param1", "TEXT"), ("param2", "INTEGER")]);
684
685 assert_eq!(builder.get_name(), Some("test_function"));
686 assert_eq!(builder.get_schema(), Some("public"));
687 assert_eq!(builder.get_parameters().len(), 2);
688 assert_eq!(builder.parameter_count(), 2);
689 assert!(builder.has_parameter("param1"));
690 assert!(!builder.has_parameter("nonexistent"));
691 assert!(builder.has_name());
692 assert!(builder.has_schema());
693 assert!(builder.has_parameters());
694 assert!(!builder.has_return_type());
695 assert!(!builder.has_language());
696 assert!(!builder.has_volatility());
697 assert!(!builder.has_security());
698 assert!(!builder.has_body());
699 assert!(!builder.has_comment());
700
701 let param = builder.get_parameter("param1");
702 assert!(param.is_some());
703 assert_eq!(param.unwrap().name, "param1");
704 assert_eq!(param.unwrap().data_type, "TEXT");
705 }
706
707 #[test]
708 fn test_debug_info_and_summary() {
709 let builder = FunctionBuilder::new()
710 .name("calculate_distance")
711 .in_schema("geometry")
712 .parameters(vec![
713 ("x1", "DOUBLE PRECISION"),
714 ("y1", "DOUBLE PRECISION"),
715 ("x2", "DOUBLE PRECISION"),
716 ("y2", "DOUBLE PRECISION"),
717 ])
718 .returns("DOUBLE PRECISION")
719 .language(ProcedureLanguage::Sql)
720 .volatility(FunctionVolatility::Immutable)
721 .comment("Calculates Euclidean distance between two points");
722
723 let debug_info = builder.debug_info();
724 let summary = builder.summary();
725
726 assert!(debug_info.contains("FunctionBuilder"));
727 assert!(debug_info.contains("calculate_distance"));
728 assert!(debug_info.contains("geometry"));
729
730 assert!(summary.contains("Function"));
731 assert!(summary.contains("geometry.calculate_distance"));
732 assert!(summary.contains("with parameters: x1: DOUBLE PRECISION, y1: DOUBLE PRECISION, x2: DOUBLE PRECISION, y2: DOUBLE PRECISION"));
733 assert!(summary.contains("returns: DOUBLE PRECISION"));
734 assert!(summary.contains("language: Sql"));
735 assert!(summary.contains("volatility: Immutable"));
736 }
738
739 #[test]
740 fn test_specialized_function_types() {
741 let math_func = FunctionBuilder::math()
742 .name("square_root")
743 .parameter("value", "DOUBLE PRECISION")
744 .returns("DOUBLE PRECISION")
745 .body("SELECT SQRT(value)")
746 .build()
747 .unwrap();
748
749 let utility_func = FunctionBuilder::utility()
750 .name("get_current_user")
751 .returns("TEXT")
752 .body("SELECT current_user")
753 .build()
754 .unwrap();
755
756 let trigger_func = FunctionBuilder::trigger()
757 .name("audit_changes")
758 .body("RETURN NEW")
759 .build()
760 .unwrap();
761
762 assert_eq!(math_func.language, ProcedureLanguage::Sql);
763 assert_eq!(math_func.volatility, FunctionVolatility::Immutable);
764 assert_eq!(utility_func.language, ProcedureLanguage::PlPgSql);
765 assert_eq!(utility_func.volatility, FunctionVolatility::Stable);
766 assert_eq!(trigger_func.language, ProcedureLanguage::PlPgSql);
767 assert_eq!(trigger_func.volatility, FunctionVolatility::Volatile);
768 assert_eq!(trigger_func.return_type, Some("TRIGGER".to_string()));
769 }
770
771 #[test]
772 fn test_function_with_all_properties() {
773 let function = FunctionBuilder::new()
774 .name("complex_calculation")
775 .in_schema("finance")
776 .parameters(vec![
777 ("principal", "NUMERIC(19,4)"),
778 ("rate", "NUMERIC(5,4)"),
779 ("time", "NUMERIC(5,2)"),
780 ])
781 .returns("NUMERIC(19,4)")
782 .language(ProcedureLanguage::PlPgSql)
783 .volatility(FunctionVolatility::Immutable)
784 .security(FunctionSecurity::Invoker)
785 .body("RETURN principal * POWER(1 + rate, time)")
786 .comment("Calculates compound interest")
787 .build()
788 .unwrap();
789
790 assert_eq!(function.name, "complex_calculation");
791 assert_eq!(function.schema, Some("finance".to_string()));
792 assert_eq!(function.parameters.len(), 3);
793 assert_eq!(function.return_type, Some("NUMERIC(19,4)".to_string()));
794 assert_eq!(function.language, ProcedureLanguage::PlPgSql);
795 assert_eq!(function.volatility, FunctionVolatility::Immutable);
796 assert_eq!(function.security, FunctionSecurity::Invoker);
797 assert_eq!(function.body, "RETURN principal * POWER(1 + rate, time)");
798 }
800}