1use crate::builders::traits::{
2 ConditionalBuilder, InspectableBuilder, SchemaBuilder, ValidatableBuilder,
3};
4use crate::builders::validation::TriggerBuildError;
5use crate::schema::{Trigger, TriggerEvent, TriggerOrientation, TriggerReferencing, TriggerTiming};
6
7#[derive(Debug, Clone)]
9pub struct TriggerBuilder {
10 name: Option<String>,
11 schema: Option<String>,
12 table_name: Option<String>,
13 table_schema: Option<String>,
14 timing: Option<TriggerTiming>,
15 events: Vec<TriggerEvent>,
16 orientation: Option<TriggerOrientation>,
17 function_name: Option<String>,
18 function_schema: Option<String>,
19 condition: Option<String>,
20 update_columns: Option<Vec<String>>,
21 referencing: Option<TriggerReferencing>,
22 comment: Option<String>,
23}
24
25impl TriggerBuilder {
26 pub fn new() -> Self {
28 Self {
29 name: None,
30 schema: None,
31 table_name: None,
32 table_schema: None,
33 timing: None,
34 events: Vec::new(),
35 orientation: None,
36 function_name: None,
37 function_schema: None,
38 condition: None,
39 update_columns: None,
40 referencing: None,
41 comment: None,
42 }
43 }
44
45 pub fn name(mut self, name: impl Into<String>) -> Self {
47 self.name = Some(name.into());
48 self
49 }
50
51 pub fn set_name(&mut self, name: impl Into<String>) {
53 self.name = Some(name.into());
54 }
55
56 pub fn in_schema(mut self, schema: impl Into<String>) -> Self {
58 self.schema = Some(schema.into());
59 self
60 }
61
62 pub fn set_schema(&mut self, schema: impl Into<String>) {
64 self.schema = Some(schema.into());
65 }
66
67 pub fn on_table(mut self, table_name: impl Into<String>) -> Self {
69 self.table_name = Some(table_name.into());
70 self
71 }
72
73 pub fn set_table_name(&mut self, table_name: impl Into<String>) {
75 self.table_name = Some(table_name.into());
76 }
77
78 pub fn on_table_in_schema(mut self, table_schema: impl Into<String>) -> Self {
80 self.table_schema = Some(table_schema.into());
81 self
82 }
83
84 pub fn set_table_schema(&mut self, table_schema: impl Into<String>) {
86 self.table_schema = Some(table_schema.into());
87 }
88
89 pub fn timing(mut self, timing: TriggerTiming) -> Self {
91 self.timing = Some(timing);
92 self
93 }
94
95 pub fn set_timing(&mut self, timing: TriggerTiming) {
97 self.timing = Some(timing);
98 }
99
100 pub fn event(mut self, event: TriggerEvent) -> Self {
102 self.events.push(event);
103 self
104 }
105
106 pub fn add_event(&mut self, event: TriggerEvent) {
108 self.events.push(event);
109 }
110
111 pub fn events(mut self, events: impl IntoIterator<Item = TriggerEvent>) -> Self {
113 self.events.extend(events);
114 self
115 }
116
117 pub fn add_events(&mut self, events: impl IntoIterator<Item = TriggerEvent>) {
119 self.events.extend(events);
120 }
121
122 pub fn orientation(mut self, orientation: TriggerOrientation) -> Self {
124 self.orientation = Some(orientation);
125 self
126 }
127
128 pub fn set_orientation(&mut self, orientation: TriggerOrientation) {
130 self.orientation = Some(orientation);
131 }
132
133 pub fn function(mut self, function_name: impl Into<String>) -> Self {
135 self.function_name = Some(function_name.into());
136 self
137 }
138
139 pub fn set_function(&mut self, function_name: impl Into<String>) {
141 self.function_name = Some(function_name.into());
142 }
143
144 pub fn function_in_schema(mut self, function_schema: impl Into<String>) -> Self {
146 self.function_schema = Some(function_schema.into());
147 self
148 }
149
150 pub fn set_function_schema(&mut self, function_schema: impl Into<String>) {
152 self.function_schema = Some(function_schema.into());
153 }
154
155 pub fn condition(mut self, condition: impl Into<String>) -> Self {
157 self.condition = Some(condition.into());
158 self
159 }
160
161 pub fn set_condition(&mut self, condition: impl Into<String>) {
163 self.condition = Some(condition.into());
164 }
165
166 pub fn update_columns(mut self, columns: impl IntoIterator<Item = impl Into<String>>) -> Self {
168 self.update_columns = Some(columns.into_iter().map(|c| c.into()).collect());
169 self
170 }
171
172 pub fn set_update_columns(&mut self, columns: impl IntoIterator<Item = impl Into<String>>) {
174 self.update_columns = Some(columns.into_iter().map(|c| c.into()).collect());
175 }
176
177 pub fn referencing(mut self, old_table: Option<String>, new_table: Option<String>) -> Self {
179 self.referencing = Some(TriggerReferencing {
180 old_table,
181 new_table,
182 });
183 self
184 }
185
186 pub fn set_referencing(&mut self, old_table: Option<String>, new_table: Option<String>) {
188 self.referencing = Some(TriggerReferencing {
189 old_table,
190 new_table,
191 });
192 }
193
194 pub fn comment(mut self, comment: impl Into<String>) -> Self {
196 self.comment = Some(comment.into());
197 self
198 }
199
200 pub fn set_comment(&mut self, comment: impl Into<String>) {
202 self.comment = Some(comment.into());
203 }
204
205 pub fn simple() -> Self {
208 Self::new()
209 }
210
211 pub fn before() -> Self {
213 Self::new().timing(TriggerTiming::Before)
214 }
215
216 pub fn after() -> Self {
218 Self::new().timing(TriggerTiming::After)
219 }
220
221 pub fn instead_of() -> Self {
223 Self::new().timing(TriggerTiming::InsteadOf)
224 }
225
226 pub fn row() -> Self {
228 Self::new().orientation(TriggerOrientation::Row)
229 }
230
231 pub fn statement() -> Self {
233 Self::new().orientation(TriggerOrientation::Statement)
234 }
235
236 pub fn on_insert() -> Self {
238 Self::new().event(TriggerEvent::Insert)
239 }
240
241 pub fn on_update() -> Self {
243 Self::new().event(TriggerEvent::Update)
244 }
245
246 pub fn on_delete() -> Self {
248 Self::new().event(TriggerEvent::Delete)
249 }
250
251 pub fn on_truncate() -> Self {
253 Self::new().event(TriggerEvent::Truncate)
254 }
255
256 pub fn audit() -> Self {
258 Self::new()
259 .timing(TriggerTiming::After)
260 .events(vec![
261 TriggerEvent::Insert,
262 TriggerEvent::Update,
263 TriggerEvent::Delete,
264 ])
265 .orientation(TriggerOrientation::Row)
266 }
267
268 pub fn validation() -> Self {
270 Self::new()
271 .timing(TriggerTiming::Before)
272 .orientation(TriggerOrientation::Row)
273 }
274
275 pub fn logging() -> Self {
277 Self::new()
278 .timing(TriggerTiming::After)
279 .orientation(TriggerOrientation::Row)
280 }
281
282 pub fn get_name(&self) -> Option<&str> {
285 self.name.as_deref()
286 }
287
288 pub fn get_schema(&self) -> Option<&str> {
290 self.schema.as_deref()
291 }
292
293 pub fn get_table_name(&self) -> Option<&str> {
295 self.table_name.as_deref()
296 }
297
298 pub fn get_table_schema(&self) -> Option<&str> {
300 self.table_schema.as_deref()
301 }
302
303 pub fn get_timing(&self) -> Option<&TriggerTiming> {
305 self.timing.as_ref()
306 }
307
308 pub fn get_events(&self) -> &[TriggerEvent] {
310 &self.events
311 }
312
313 pub fn get_orientation(&self) -> Option<&TriggerOrientation> {
315 self.orientation.as_ref()
316 }
317
318 pub fn get_function_name(&self) -> Option<&str> {
320 self.function_name.as_deref()
321 }
322
323 pub fn get_function_schema(&self) -> Option<&str> {
325 self.function_schema.as_deref()
326 }
327
328 pub fn get_condition(&self) -> Option<&str> {
330 self.condition.as_deref()
331 }
332
333 pub fn get_update_columns(&self) -> Option<&[String]> {
335 self.update_columns.as_deref()
336 }
337
338 pub fn get_referencing(&self) -> Option<&TriggerReferencing> {
340 self.referencing.as_ref()
341 }
342
343 pub fn get_comment(&self) -> Option<&str> {
345 self.comment.as_deref()
346 }
347
348 pub fn event_count(&self) -> usize {
350 self.events.len()
351 }
352
353 pub fn has_event(&self, event: &TriggerEvent) -> bool {
355 self.events.contains(event)
356 }
357
358 pub fn has_name(&self) -> bool {
360 self.name.is_some()
361 }
362
363 pub fn has_schema(&self) -> bool {
365 self.schema.is_some()
366 }
367
368 pub fn has_table_name(&self) -> bool {
370 self.table_name.is_some()
371 }
372
373 pub fn has_table_schema(&self) -> bool {
375 self.table_schema.is_some()
376 }
377
378 pub fn has_timing(&self) -> bool {
380 self.timing.is_some()
381 }
382
383 pub fn has_events(&self) -> bool {
385 !self.events.is_empty()
386 }
387
388 pub fn has_orientation(&self) -> bool {
390 self.orientation.is_some()
391 }
392
393 pub fn has_function_name(&self) -> bool {
395 self.function_name.is_some()
396 }
397
398 pub fn has_function_schema(&self) -> bool {
400 self.function_schema.is_some()
401 }
402
403 pub fn has_condition(&self) -> bool {
405 self.condition.is_some()
406 }
407
408 pub fn has_update_columns(&self) -> bool {
410 self.update_columns.is_some()
411 }
412
413 pub fn has_referencing(&self) -> bool {
415 self.referencing.is_some()
416 }
417
418 pub fn has_comment(&self) -> bool {
420 self.comment.is_some()
421 }
422}
423
424impl SchemaBuilder for TriggerBuilder {
425 type Output = Trigger;
426 type Error = TriggerBuildError;
427
428 fn build(self) -> Result<Self::Output, Self::Error> {
429 if !self.is_valid() {
431 let errors = self.validation_errors();
432 return Err(TriggerBuildError::ValidationError(errors.join("; ")));
433 }
434
435 let trigger = Trigger {
437 name: self.name.unwrap_or_else(|| "trigger".to_string()),
438 schema: self.schema,
439 table_name: self.table_name.unwrap_or_else(|| "table".to_string()),
440 table_schema: self.table_schema,
441 timing: self.timing.unwrap_or(TriggerTiming::After),
442 events: self.events,
443 orientation: self.orientation.unwrap_or(TriggerOrientation::Row),
444 function_name: self.function_name.unwrap_or_else(|| "function".to_string()),
445 function_schema: self.function_schema,
446 condition: self.condition,
447 update_columns: self.update_columns,
448 referencing: self.referencing,
449 };
450
451 Ok(trigger)
452 }
453}
454
455impl ValidatableBuilder for TriggerBuilder {
456 fn is_valid(&self) -> bool {
457 self.validation_errors().is_empty()
458 }
459
460 fn validation_errors(&self) -> Vec<String> {
461 let mut errors = Vec::new();
462
463 if self.events.is_empty() {
465 errors.push("Trigger must have at least one event".to_string());
466 }
467
468 if self.function_name.is_none() {
470 errors.push("Trigger must have a function name".to_string());
471 }
472
473 if let Some(ref name) = self.name {
475 if name.trim().is_empty() {
476 errors.push("Trigger name cannot be empty".to_string());
477 }
478 }
479
480 if let Some(ref schema) = self.schema {
482 if schema.trim().is_empty() {
483 errors.push("Schema name cannot be empty".to_string());
484 }
485 }
486
487 if let Some(ref table_name) = self.table_name {
489 if table_name.trim().is_empty() {
490 errors.push("Table name cannot be empty".to_string());
491 }
492 }
493
494 if let Some(ref table_schema) = self.table_schema {
496 if table_schema.trim().is_empty() {
497 errors.push("Table schema name cannot be empty".to_string());
498 }
499 }
500
501 if let Some(ref function_name) = self.function_name {
503 if function_name.trim().is_empty() {
504 errors.push("Function name cannot be empty".to_string());
505 }
506 }
507
508 if let Some(ref function_schema) = self.function_schema {
510 if function_schema.trim().is_empty() {
511 errors.push("Function schema name cannot be empty".to_string());
512 }
513 }
514
515 if let Some(ref condition) = self.condition {
517 if condition.trim().is_empty() {
518 errors.push("Trigger condition cannot be empty".to_string());
519 }
520 }
521
522 if let Some(ref update_columns) = self.update_columns {
524 for (i, column) in update_columns.iter().enumerate() {
525 if column.trim().is_empty() {
526 errors.push(format!(
527 "Update column {} at index {} cannot be empty",
528 i, i
529 ));
530 }
531 }
532 }
533
534 errors
535 }
536}
537
538impl ConditionalBuilder for TriggerBuilder {
539 fn when<F>(mut self, condition: bool, config_fn: F) -> Self
540 where
541 F: FnOnce(&mut Self),
542 Self: Sized,
543 {
544 if condition {
545 config_fn(&mut self);
546 }
547 self
548 }
549}
550
551impl InspectableBuilder for TriggerBuilder {
552 fn debug_info(&self) -> String {
553 format!(
554 "TriggerBuilder {{ name: {:?}, schema: {:?}, table_name: {:?}, timing: {:?}, events: {:?}, orientation: {:?}, function_name: {:?} }}",
555 self.name, self.schema, self.table_name, self.timing, self.events, self.orientation, self.function_name
556 )
557 }
558
559 fn summary(&self) -> String {
560 let mut parts = Vec::new();
561
562 parts.push("Trigger".to_string());
563
564 if let Some(ref name) = self.name {
566 if let Some(ref schema) = self.schema {
567 parts.push(format!("{}.{}", schema, name));
568 } else {
569 parts.push(format!("'{}'", name));
570 }
571 }
572
573 if let Some(ref table_name) = self.table_name {
575 if let Some(ref table_schema) = self.table_schema {
576 parts.push(format!("on {}.{}", table_schema, table_name));
577 } else {
578 parts.push(format!("on '{}'", table_name));
579 }
580 }
581
582 if let Some(ref timing) = self.timing {
584 parts.push(format!("{:?}", timing));
585 }
586
587 if !self.events.is_empty() {
589 let event_descriptions: Vec<String> =
590 self.events.iter().map(|e| format!("{:?}", e)).collect();
591 parts.push(format!("on {}", event_descriptions.join(", ")));
592 }
593
594 if let Some(ref orientation) = self.orientation {
596 parts.push(format!("{:?}", orientation));
597 }
598
599 if let Some(ref function_name) = self.function_name {
601 if let Some(ref function_schema) = self.function_schema {
602 parts.push(format!("calls {}.{}", function_schema, function_name));
603 } else {
604 parts.push(format!("calls '{}'", function_name));
605 }
606 }
607
608 if let Some(ref condition) = self.condition {
610 parts.push(format!("when {}", condition));
611 }
612
613 if let Some(ref update_columns) = self.update_columns {
615 parts.push(format!("of columns: {}", update_columns.join(", ")));
616 }
617
618 if let Some(ref referencing) = self.referencing {
620 let mut ref_parts = Vec::new();
621 if let Some(ref old_table) = referencing.old_table {
622 ref_parts.push(format!("OLD AS {}", old_table));
623 }
624 if let Some(ref new_table) = referencing.new_table {
625 ref_parts.push(format!("NEW AS {}", new_table));
626 }
627 if !ref_parts.is_empty() {
628 parts.push(format!("referencing {}", ref_parts.join(", ")));
629 }
630 }
631
632 if let Some(ref comment) = self.comment {
634 parts.push(format!("with comment: {}", comment));
635 }
636
637 parts.join(", ")
638 }
639}
640
641#[cfg(test)]
642mod tests {
643 use super::*;
644 use crate::schema::{TriggerEvent, TriggerOrientation, TriggerTiming};
645
646 #[test]
647 fn test_basic_trigger() {
648 let trigger = TriggerBuilder::new()
649 .name("audit_users")
650 .on_table("users")
651 .timing(TriggerTiming::After)
652 .event(TriggerEvent::Insert)
653 .event(TriggerEvent::Update)
654 .function("audit_function")
655 .build()
656 .unwrap();
657
658 assert_eq!(trigger.name, "audit_users");
659 assert_eq!(trigger.table_name, "users");
660 assert_eq!(trigger.timing, TriggerTiming::After);
661 assert_eq!(trigger.events.len(), 2);
662 assert_eq!(trigger.events[0], TriggerEvent::Insert);
663 assert_eq!(trigger.events[1], TriggerEvent::Update);
664 assert_eq!(trigger.function_name, "audit_function");
665 }
666
667 #[test]
668 fn test_trigger_with_schema() {
669 let trigger = TriggerBuilder::new()
670 .name("validate_user")
671 .in_schema("public")
672 .on_table("users")
673 .on_table_in_schema("public")
674 .timing(TriggerTiming::Before)
675 .event(TriggerEvent::Insert)
676 .function("validate_function")
677 .function_in_schema("validation")
678 .build()
679 .unwrap();
680
681 assert_eq!(trigger.name, "validate_user");
682 assert_eq!(trigger.schema, Some("public".to_string()));
683 assert_eq!(trigger.table_name, "users");
684 assert_eq!(trigger.table_schema, Some("public".to_string()));
685 assert_eq!(trigger.function_schema, Some("validation".to_string()));
686 }
687
688 #[test]
689 fn test_convenience_methods() {
690 let before_trigger = TriggerBuilder::before()
691 .name("before_insert")
692 .on_table("users")
693 .event(TriggerEvent::Insert)
694 .function("before_function")
695 .build()
696 .unwrap();
697
698 let after_trigger = TriggerBuilder::after()
699 .name("after_update")
700 .on_table("users")
701 .event(TriggerEvent::Update)
702 .function("after_function")
703 .build()
704 .unwrap();
705
706 let row_trigger = TriggerBuilder::row()
707 .name("row_trigger")
708 .on_table("users")
709 .event(TriggerEvent::Delete)
710 .function("row_function")
711 .build()
712 .unwrap();
713
714 let statement_trigger = TriggerBuilder::statement()
715 .name("statement_trigger")
716 .on_table("users")
717 .event(TriggerEvent::Truncate)
718 .function("statement_function")
719 .build()
720 .unwrap();
721
722 assert_eq!(before_trigger.timing, TriggerTiming::Before);
723 assert_eq!(after_trigger.timing, TriggerTiming::After);
724 assert_eq!(row_trigger.orientation, TriggerOrientation::Row);
725 assert_eq!(statement_trigger.orientation, TriggerOrientation::Statement);
726 }
727
728 #[test]
729 fn test_event_convenience_methods() {
730 let insert_trigger = TriggerBuilder::on_insert()
731 .name("insert_trigger")
732 .on_table("users")
733 .function("insert_function")
734 .build()
735 .unwrap();
736
737 let update_trigger = TriggerBuilder::on_update()
738 .name("update_trigger")
739 .on_table("users")
740 .function("update_function")
741 .build()
742 .unwrap();
743
744 let delete_trigger = TriggerBuilder::on_delete()
745 .name("delete_trigger")
746 .on_table("users")
747 .function("delete_function")
748 .build()
749 .unwrap();
750
751 let truncate_trigger = TriggerBuilder::on_truncate()
752 .name("truncate_trigger")
753 .on_table("users")
754 .function("truncate_function")
755 .build()
756 .unwrap();
757
758 assert_eq!(insert_trigger.events.len(), 1);
759 assert_eq!(insert_trigger.events[0], TriggerEvent::Insert);
760 assert_eq!(update_trigger.events.len(), 1);
761 assert_eq!(update_trigger.events[0], TriggerEvent::Update);
762 assert_eq!(delete_trigger.events.len(), 1);
763 assert_eq!(delete_trigger.events[0], TriggerEvent::Delete);
764 assert_eq!(truncate_trigger.events.len(), 1);
765 assert_eq!(truncate_trigger.events[0], TriggerEvent::Truncate);
766 }
767
768 #[test]
769 fn test_specialized_trigger_types() {
770 let audit_trigger = TriggerBuilder::audit()
771 .name("audit_trigger")
772 .on_table("users")
773 .function("audit_function")
774 .build()
775 .unwrap();
776
777 let validation_trigger = TriggerBuilder::validation()
778 .name("validation_trigger")
779 .on_table("users")
780 .event(TriggerEvent::Insert)
781 .function("validation_function")
782 .build()
783 .unwrap();
784
785 let logging_trigger = TriggerBuilder::logging()
786 .name("logging_trigger")
787 .on_table("users")
788 .event(TriggerEvent::Update)
789 .function("logging_function")
790 .build()
791 .unwrap();
792
793 assert_eq!(audit_trigger.timing, TriggerTiming::After);
794 assert_eq!(audit_trigger.orientation, TriggerOrientation::Row);
795 assert_eq!(audit_trigger.events.len(), 3);
796 assert_eq!(validation_trigger.timing, TriggerTiming::Before);
797 assert_eq!(logging_trigger.timing, TriggerTiming::After);
798 }
799
800 #[test]
801 fn test_trigger_with_condition() {
802 let trigger = TriggerBuilder::new()
803 .name("conditional_trigger")
804 .on_table("users")
805 .timing(TriggerTiming::Before)
806 .event(TriggerEvent::Update)
807 .function("conditional_function")
808 .condition("NEW.status != OLD.status")
809 .build()
810 .unwrap();
811
812 assert_eq!(trigger.name, "conditional_trigger");
813 assert_eq!(
814 trigger.condition,
815 Some("NEW.status != OLD.status".to_string())
816 );
817 }
818
819 #[test]
820 fn test_trigger_with_update_columns() {
821 let trigger = TriggerBuilder::new()
822 .name("column_trigger")
823 .on_table("users")
824 .timing(TriggerTiming::Before)
825 .event(TriggerEvent::Update)
826 .function("column_function")
827 .update_columns(vec!["status", "email"])
828 .build()
829 .unwrap();
830
831 assert_eq!(trigger.name, "column_trigger");
832 assert_eq!(
833 trigger.update_columns,
834 Some(vec!["status".to_string(), "email".to_string()])
835 );
836 }
837
838 #[test]
839 fn test_trigger_with_referencing() {
840 let trigger = TriggerBuilder::new()
841 .name("referencing_trigger")
842 .on_table("users")
843 .timing(TriggerTiming::After)
844 .event(TriggerEvent::Update)
845 .function("referencing_function")
846 .referencing(Some("old_users".to_string()), Some("new_users".to_string()))
847 .build()
848 .unwrap();
849
850 assert_eq!(trigger.name, "referencing_trigger");
851 assert!(trigger.referencing.is_some());
852 let referencing = trigger.referencing.unwrap();
853 assert_eq!(referencing.old_table, Some("old_users".to_string()));
854 assert_eq!(referencing.new_table, Some("new_users".to_string()));
855 }
856
857 #[test]
858 fn test_trigger_with_multiple_events() {
859 let trigger = TriggerBuilder::new()
860 .name("multi_event_trigger")
861 .on_table("users")
862 .timing(TriggerTiming::After)
863 .events(vec![
864 TriggerEvent::Insert,
865 TriggerEvent::Update,
866 TriggerEvent::Delete,
867 ])
868 .function("multi_function")
869 .build()
870 .unwrap();
871
872 assert_eq!(trigger.name, "multi_event_trigger");
873 assert_eq!(trigger.events.len(), 3);
874 assert_eq!(trigger.events[0], TriggerEvent::Insert);
875 assert_eq!(trigger.events[1], TriggerEvent::Update);
876 assert_eq!(trigger.events[2], TriggerEvent::Delete);
877 }
878
879 #[test]
880 fn test_validation_errors() {
881 let result = TriggerBuilder::new()
883 .name("test")
884 .function("test_function")
885 .build();
886 assert!(result.is_err());
887 assert!(matches!(
888 result.unwrap_err(),
889 TriggerBuildError::ValidationError(_)
890 ));
891
892 let result = TriggerBuilder::new()
894 .name("test")
895 .event(TriggerEvent::Insert)
896 .build();
897 assert!(result.is_err());
898 assert!(matches!(
899 result.unwrap_err(),
900 TriggerBuildError::ValidationError(_)
901 ));
902 }
903
904 #[test]
905 fn test_conditional_builder() {
906 let condition = true;
907 let trigger = TriggerBuilder::new()
908 .when(condition, |t| {
909 t.set_name("trigger_when_true");
910 t.set_table_name("users");
911 t.add_event(TriggerEvent::Insert);
912 t.set_function("test_function");
913 })
914 .build()
915 .unwrap();
916
917 assert_eq!(trigger.name, "trigger_when_true");
918 assert_eq!(trigger.table_name, "users");
919 assert_eq!(trigger.events.len(), 1);
920 assert_eq!(trigger.events[0], TriggerEvent::Insert);
921 }
922
923 #[test]
924 fn test_inspection_methods() {
925 let builder = TriggerBuilder::new()
926 .name("test_trigger")
927 .in_schema("public")
928 .on_table("users")
929 .on_table_in_schema("public")
930 .timing(TriggerTiming::After)
931 .events(vec![TriggerEvent::Insert, TriggerEvent::Update])
932 .orientation(TriggerOrientation::Row)
933 .function("test_function")
934 .function_in_schema("functions")
935 .condition("NEW.id > 0")
936 .update_columns(vec!["status", "email"])
937 .referencing(Some("old_users".to_string()), Some("new_users".to_string()))
938 .comment("This is a test trigger");
939
940 assert_eq!(builder.get_name(), Some("test_trigger"));
941 assert_eq!(builder.get_schema(), Some("public"));
942 assert_eq!(builder.get_table_name(), Some("users"));
943 assert_eq!(builder.get_table_schema(), Some("public"));
944 assert_eq!(builder.get_timing(), Some(&TriggerTiming::After));
945 assert_eq!(builder.get_events().len(), 2);
946 assert_eq!(builder.get_orientation(), Some(&TriggerOrientation::Row));
947 assert_eq!(builder.get_function_name(), Some("test_function"));
948 assert_eq!(builder.get_function_schema(), Some("functions"));
949 assert_eq!(builder.get_condition(), Some("NEW.id > 0"));
950 assert_eq!(
951 builder.get_update_columns(),
952 Some(&vec!["status".to_string(), "email".to_string()]).map(|v| &**v)
953 );
954 assert!(builder.get_referencing().is_some());
955 assert_eq!(builder.get_comment(), Some("This is a test trigger"));
956
957 assert_eq!(builder.event_count(), 2);
958 assert!(builder.has_event(&TriggerEvent::Insert));
959 assert!(builder.has_event(&TriggerEvent::Update));
960 assert!(!builder.has_event(&TriggerEvent::Delete));
961
962 assert!(builder.has_name());
963 assert!(builder.has_schema());
964 assert!(builder.has_table_name());
965 assert!(builder.has_table_schema());
966 assert!(builder.has_timing());
967 assert!(builder.has_events());
968 assert!(builder.has_orientation());
969 assert!(builder.has_function_name());
970 assert!(builder.has_function_schema());
971 assert!(builder.has_condition());
972 assert!(builder.has_update_columns());
973 assert!(builder.has_referencing());
974 assert!(builder.has_comment());
975 }
976
977 #[test]
978 fn test_debug_info_and_summary() {
979 let builder = TriggerBuilder::new()
980 .name("audit_users")
981 .in_schema("public")
982 .on_table("users")
983 .timing(TriggerTiming::After)
984 .events(vec![TriggerEvent::Insert, TriggerEvent::Update])
985 .orientation(TriggerOrientation::Row)
986 .function("audit_function")
987 .condition("NEW.status != OLD.status")
988 .update_columns(vec!["status", "email"])
989 .comment("Audits user changes");
990
991 let debug_info = builder.debug_info();
992 let summary = builder.summary();
993
994 assert!(debug_info.contains("TriggerBuilder"));
995 assert!(debug_info.contains("audit_users"));
996 assert!(debug_info.contains("users"));
997
998 assert!(summary.contains("Trigger"));
999 assert!(summary.contains("public.audit_users"));
1000 assert!(summary.contains("on 'users'"));
1001 assert!(summary.contains("After"));
1002 assert!(summary.contains("on Insert, Update"));
1003 assert!(summary.contains("Row"));
1004 assert!(summary.contains("calls 'audit_function'"));
1005 assert!(summary.contains("when NEW.status != OLD.status"));
1006 assert!(summary.contains("of columns: status, email"));
1007 assert!(summary.contains("with comment: Audits user changes"));
1008 }
1009
1010 #[test]
1011 fn test_trigger_with_all_properties() {
1012 let trigger = TriggerBuilder::new()
1013 .name("comprehensive_trigger")
1014 .in_schema("audit")
1015 .on_table("users")
1016 .on_table_in_schema("public")
1017 .timing(TriggerTiming::After)
1018 .events(vec![
1019 TriggerEvent::Insert,
1020 TriggerEvent::Update,
1021 TriggerEvent::Delete,
1022 ])
1023 .orientation(TriggerOrientation::Row)
1024 .function("comprehensive_function")
1025 .function_in_schema("audit_functions")
1026 .condition("NEW.id > 0 AND OLD.id > 0")
1027 .update_columns(vec!["status", "email", "last_modified"])
1028 .referencing(Some("old_users".to_string()), Some("new_users".to_string()))
1029 .comment("Comprehensive audit trigger for user changes")
1030 .build()
1031 .unwrap();
1032
1033 assert_eq!(trigger.name, "comprehensive_trigger");
1034 assert_eq!(trigger.schema, Some("audit".to_string()));
1035 assert_eq!(trigger.table_name, "users");
1036 assert_eq!(trigger.table_schema, Some("public".to_string()));
1037 assert_eq!(trigger.timing, TriggerTiming::After);
1038 assert_eq!(trigger.events.len(), 3);
1039 assert_eq!(trigger.orientation, TriggerOrientation::Row);
1040 assert_eq!(trigger.function_name, "comprehensive_function");
1041 assert_eq!(trigger.function_schema, Some("audit_functions".to_string()));
1042 assert_eq!(
1043 trigger.condition,
1044 Some("NEW.id > 0 AND OLD.id > 0".to_string())
1045 );
1046 assert_eq!(
1047 trigger.update_columns,
1048 Some(vec![
1049 "status".to_string(),
1050 "email".to_string(),
1051 "last_modified".to_string()
1052 ])
1053 );
1054 assert!(trigger.referencing.is_some());
1055 let referencing = trigger.referencing.unwrap();
1056 assert_eq!(referencing.old_table, Some("old_users".to_string()));
1057 assert_eq!(referencing.new_table, Some("new_users".to_string()));
1058 }
1060}