1use crate::builders::traits::{
2 ConditionalBuilder, InspectableBuilder, SchemaBuilder, ValidatableBuilder,
3};
4use crate::builders::validation::SequenceBuildError;
5use crate::schema::Sequence;
6
7#[derive(Debug, Clone)]
9pub struct SequenceBuilder {
10 name: Option<String>,
11 schema: Option<String>,
12 data_type: Option<String>,
13 start_value: Option<i64>,
14 minimum_value: Option<i64>,
15 maximum_value: Option<i64>,
16 increment: Option<i64>,
17 cycle: Option<bool>,
18 cache: Option<i64>,
19 owner: Option<String>,
20 comment: Option<String>,
21}
22
23impl SequenceBuilder {
24 pub fn new() -> Self {
26 Self {
27 name: None,
28 schema: None,
29 data_type: None,
30 start_value: None,
31 minimum_value: None,
32 maximum_value: None,
33 increment: None,
34 cycle: None,
35 cache: None,
36 owner: None,
37 comment: None,
38 }
39 }
40
41 pub fn name(mut self, name: impl Into<String>) -> Self {
43 self.name = Some(name.into());
44 self
45 }
46
47 pub fn set_name(&mut self, name: impl Into<String>) {
49 self.name = Some(name.into());
50 }
51
52 pub fn in_schema(mut self, schema: impl Into<String>) -> Self {
54 self.schema = Some(schema.into());
55 self
56 }
57
58 pub fn set_schema(&mut self, schema: impl Into<String>) {
60 self.schema = Some(schema.into());
61 }
62
63 pub fn data_type(mut self, data_type: impl Into<String>) -> Self {
65 self.data_type = Some(data_type.into());
66 self
67 }
68
69 pub fn set_data_type(&mut self, data_type: impl Into<String>) {
71 self.data_type = Some(data_type.into());
72 }
73
74 pub fn start_value(mut self, start: i64) -> Self {
76 self.start_value = Some(start);
77 self
78 }
79
80 pub fn set_start_value(&mut self, start: i64) {
82 self.start_value = Some(start);
83 }
84
85 pub fn minimum_value(mut self, min: i64) -> Self {
87 self.minimum_value = Some(min);
88 self
89 }
90
91 pub fn set_minimum_value(&mut self, min: i64) {
93 self.minimum_value = Some(min);
94 }
95
96 pub fn maximum_value(mut self, max: i64) -> Self {
98 self.maximum_value = Some(max);
99 self
100 }
101
102 pub fn set_maximum_value(&mut self, max: i64) {
104 self.maximum_value = Some(max);
105 }
106
107 pub fn increment(mut self, increment: i64) -> Self {
109 self.increment = Some(increment);
110 self
111 }
112
113 pub fn set_increment(&mut self, increment: i64) {
115 self.increment = Some(increment);
116 }
117
118 pub fn cycle(mut self, cycle: bool) -> Self {
120 self.cycle = Some(cycle);
121 self
122 }
123
124 pub fn set_cycle(&mut self, cycle: bool) {
126 self.cycle = Some(cycle);
127 }
128
129 pub fn cache(mut self, cache: i64) -> Self {
131 self.cache = Some(cache);
132 self
133 }
134
135 pub fn set_cache(&mut self, cache: i64) {
137 self.cache = Some(cache);
138 }
139
140 pub fn owner(mut self, owner: impl Into<String>) -> Self {
142 self.owner = Some(owner.into());
143 self
144 }
145
146 pub fn set_owner(&mut self, owner: impl Into<String>) {
148 self.owner = Some(owner.into());
149 }
150
151 pub fn comment(mut self, comment: impl Into<String>) -> Self {
153 self.comment = Some(comment.into());
154 self
155 }
156
157 pub fn set_comment(&mut self, comment: impl Into<String>) {
159 self.comment = Some(comment.into());
160 }
161
162 pub fn simple() -> Self {
165 Self::new()
166 }
167
168 pub fn auto_increment() -> Self {
170 Self::new()
171 .data_type("BIGINT")
172 .start_value(1)
173 .increment(1)
174 .minimum_value(1)
175 .cycle(false)
176 }
177
178 pub fn small_auto_increment() -> Self {
180 Self::new()
181 .data_type("INTEGER")
182 .start_value(1)
183 .increment(1)
184 .minimum_value(1)
185 .cycle(false)
186 }
187
188 pub fn large_auto_increment() -> Self {
190 Self::new()
191 .data_type("BIGINT")
192 .start_value(1)
193 .increment(1)
194 .minimum_value(1)
195 .maximum_value(9223372036854775807)
196 .cycle(false)
197 }
198
199 pub fn timestamp() -> Self {
201 Self::new()
202 .data_type("BIGINT")
203 .start_value(0)
204 .increment(1)
205 .cycle(false)
206 }
207
208 pub fn counter() -> Self {
210 Self::new()
211 .data_type("INTEGER")
212 .start_value(0)
213 .increment(1)
214 .minimum_value(0)
215 .cycle(false)
216 }
217
218 pub fn cycling() -> Self {
220 Self::new()
221 .data_type("INTEGER")
222 .start_value(1)
223 .increment(1)
224 .minimum_value(1)
225 .maximum_value(1000)
226 .cycle(true)
227 }
228
229 pub fn cached() -> Self {
231 Self::new()
232 .data_type("BIGINT")
233 .start_value(1)
234 .increment(1)
235 .cache(10)
236 }
237
238 #[inline]
241 pub fn get_name(&self) -> Option<&str> {
242 self.name.as_deref()
243 }
244
245 #[inline]
247 pub fn get_schema(&self) -> Option<&str> {
248 self.schema.as_deref()
249 }
250
251 #[inline]
253 pub fn get_data_type(&self) -> Option<&str> {
254 self.data_type.as_deref()
255 }
256
257 pub fn get_start_value(&self) -> Option<i64> {
259 self.start_value
260 }
261
262 pub fn get_minimum_value(&self) -> Option<i64> {
264 self.minimum_value
265 }
266
267 pub fn get_maximum_value(&self) -> Option<i64> {
269 self.maximum_value
270 }
271
272 pub fn get_increment(&self) -> Option<i64> {
274 self.increment
275 }
276
277 pub fn get_cycle(&self) -> Option<bool> {
279 self.cycle
280 }
281
282 pub fn get_cache(&self) -> Option<i64> {
284 self.cache
285 }
286
287 pub fn get_owner(&self) -> Option<&str> {
289 self.owner.as_deref()
290 }
291
292 pub fn get_comment(&self) -> Option<&str> {
294 self.comment.as_deref()
295 }
296
297 pub fn has_name(&self) -> bool {
299 self.name.is_some()
300 }
301
302 pub fn has_schema(&self) -> bool {
304 self.schema.is_some()
305 }
306
307 pub fn has_data_type(&self) -> bool {
309 self.data_type.is_some()
310 }
311
312 pub fn has_start_value(&self) -> bool {
314 self.start_value.is_some()
315 }
316
317 pub fn has_minimum_value(&self) -> bool {
319 self.minimum_value.is_some()
320 }
321
322 pub fn has_maximum_value(&self) -> bool {
324 self.maximum_value.is_some()
325 }
326
327 pub fn has_increment(&self) -> bool {
329 self.increment.is_some()
330 }
331
332 pub fn has_cycle(&self) -> bool {
334 self.cycle.is_some()
335 }
336
337 pub fn has_cache(&self) -> bool {
339 self.cache.is_some()
340 }
341
342 pub fn has_owner(&self) -> bool {
344 self.owner.is_some()
345 }
346
347 pub fn has_comment(&self) -> bool {
349 self.comment.is_some()
350 }
351}
352
353impl SchemaBuilder for SequenceBuilder {
354 type Output = Sequence;
355 type Error = SequenceBuildError;
356
357 fn build(self) -> Result<Self::Output, Self::Error> {
358 if !self.is_valid() {
360 let errors = self.validation_errors();
361 return Err(SequenceBuildError::ValidationError(errors.join("; ")));
362 }
363
364 let sequence = Sequence {
366 name: self.name.unwrap_or_else(|| "sequence".to_string()),
367 schema: self.schema,
368 data_type: self.data_type.unwrap_or_else(|| "BIGINT".to_string()),
369 start_value: self.start_value,
370 minimum_value: self.minimum_value,
371 maximum_value: self.maximum_value,
372 increment: self.increment,
373 cycle: self.cycle,
374 cache: self.cache,
375 owner: self.owner,
376 comment: self.comment,
377 };
378
379 Ok(sequence)
380 }
381}
382
383impl ValidatableBuilder for SequenceBuilder {
384 fn is_valid(&self) -> bool {
385 self.validation_errors().is_empty()
386 }
387
388 fn validation_errors(&self) -> Vec<String> {
389 let mut errors = Vec::new();
390
391 if self.name.is_none() {
393 errors.push("Sequence must have a name".to_string());
394 }
395
396 if let Some(ref name) = self.name {
398 if name.trim().is_empty() {
399 errors.push("Sequence name cannot be empty".to_string());
400 }
401 }
402
403 if let Some(ref schema) = self.schema {
405 if schema.trim().is_empty() {
406 errors.push("Schema name cannot be empty".to_string());
407 }
408 }
409
410 if let Some(ref data_type) = self.data_type {
412 if data_type.trim().is_empty() {
413 errors.push("Data type cannot be empty".to_string());
414 }
415 }
416
417 if let Some(ref owner) = self.owner {
419 if owner.trim().is_empty() {
420 errors.push("Owner cannot be empty".to_string());
421 }
422 }
423
424 if let Some(ref comment) = self.comment {
426 if comment.trim().is_empty() {
427 errors.push("Comment cannot be empty".to_string());
428 }
429 }
430
431 if let (Some(min), Some(max)) = (self.minimum_value, self.maximum_value) {
433 if min >= max {
434 errors.push("Minimum value must be less than maximum value".to_string());
435 }
436 }
437
438 if let Some(increment) = self.increment {
439 if increment == 0 {
440 errors.push("Increment cannot be zero".to_string());
441 }
442 }
443
444 if let Some(cache) = self.cache {
445 if cache <= 0 {
446 errors.push("Cache size must be positive".to_string());
447 }
448 }
449
450 errors
451 }
452}
453
454impl ConditionalBuilder for SequenceBuilder {
455 fn when<F>(mut self, condition: bool, config_fn: F) -> Self
456 where
457 F: FnOnce(&mut Self),
458 Self: Sized,
459 {
460 if condition {
461 config_fn(&mut self);
462 }
463 self
464 }
465}
466
467impl InspectableBuilder for SequenceBuilder {
468 fn debug_info(&self) -> String {
469 format!(
470 "SequenceBuilder {{ name: {:?}, schema: {:?}, data_type: {:?}, start_value: {:?}, increment: {:?}, cycle: {:?} }}",
471 self.name, self.schema, self.data_type, self.start_value, self.increment, self.cycle
472 )
473 }
474
475 fn summary(&self) -> String {
476 let mut parts = Vec::new();
477
478 parts.push("Sequence".to_string());
479
480 if let Some(ref name) = self.name {
482 if let Some(ref schema) = self.schema {
483 parts.push(format!("{}.{}", schema, name));
484 } else {
485 parts.push(format!("'{}'", name));
486 }
487 }
488
489 if let Some(ref data_type) = self.data_type {
491 parts.push(format!("type: {}", data_type));
492 }
493
494 if let Some(start) = self.start_value {
496 parts.push(format!("starts at {}", start));
497 }
498
499 if let Some(increment) = self.increment {
501 parts.push(format!("increments by {}", increment));
502 }
503
504 let mut range_parts = Vec::new();
506 if let Some(min) = self.minimum_value {
507 range_parts.push(format!("min: {}", min));
508 }
509 if let Some(max) = self.maximum_value {
510 range_parts.push(format!("max: {}", max));
511 }
512 if !range_parts.is_empty() {
513 parts.push(format!("range: {}", range_parts.join(", ")));
514 }
515
516 if let Some(cycle) = self.cycle {
518 if cycle {
519 parts.push("cycles".to_string());
520 } else {
521 parts.push("no cycle".to_string());
522 }
523 }
524
525 if let Some(cache) = self.cache {
527 parts.push(format!("cache: {}", cache));
528 }
529
530 if let Some(ref owner) = self.owner {
532 parts.push(format!("owned by {}", owner));
533 }
534
535 if let Some(ref comment) = self.comment {
537 parts.push(format!("with comment: {}", comment));
538 }
539
540 parts.join(", ")
541 }
542}
543
544#[cfg(test)]
545mod tests {
546 use super::*;
547
548 #[test]
549 fn test_basic_sequence() {
550 let sequence = SequenceBuilder::new()
551 .name("user_id_seq")
552 .data_type("BIGINT")
553 .start_value(1)
554 .increment(1)
555 .build()
556 .unwrap();
557
558 assert_eq!(sequence.name, "user_id_seq");
559 assert_eq!(sequence.data_type, "BIGINT");
560 assert_eq!(sequence.start_value, Some(1));
561 assert_eq!(sequence.increment, Some(1));
562 }
563
564 #[test]
565 fn test_sequence_with_schema() {
566 let sequence = SequenceBuilder::new()
567 .name("order_id_seq")
568 .in_schema("public")
569 .data_type("INTEGER")
570 .start_value(1000)
571 .increment(10)
572 .build()
573 .unwrap();
574
575 assert_eq!(sequence.name, "order_id_seq");
576 assert_eq!(sequence.schema, Some("public".to_string()));
577 assert_eq!(sequence.data_type, "INTEGER");
578 assert_eq!(sequence.start_value, Some(1000));
579 assert_eq!(sequence.increment, Some(10));
580 }
581
582 #[test]
583 fn test_convenience_methods() {
584 let auto_seq = SequenceBuilder::auto_increment()
585 .name("auto_seq")
586 .build()
587 .unwrap();
588
589 let small_seq = SequenceBuilder::small_auto_increment()
590 .name("small_seq")
591 .build()
592 .unwrap();
593
594 let large_seq = SequenceBuilder::large_auto_increment()
595 .name("large_seq")
596 .build()
597 .unwrap();
598
599 let timestamp_seq = SequenceBuilder::timestamp()
600 .name("timestamp_seq")
601 .build()
602 .unwrap();
603
604 let counter_seq = SequenceBuilder::counter()
605 .name("counter_seq")
606 .build()
607 .unwrap();
608
609 let cycling_seq = SequenceBuilder::cycling()
610 .name("cycling_seq")
611 .build()
612 .unwrap();
613
614 let cached_seq = SequenceBuilder::cached()
615 .name("cached_seq")
616 .build()
617 .unwrap();
618
619 assert_eq!(auto_seq.data_type, "BIGINT");
620 assert_eq!(auto_seq.start_value, Some(1));
621 assert_eq!(auto_seq.increment, Some(1));
622 assert_eq!(auto_seq.minimum_value, Some(1));
623 assert_eq!(auto_seq.cycle, Some(false));
624
625 assert_eq!(small_seq.data_type, "INTEGER");
626 assert_eq!(small_seq.start_value, Some(1));
627
628 assert_eq!(large_seq.data_type, "BIGINT");
629 assert_eq!(large_seq.maximum_value, Some(9223372036854775807));
630
631 assert_eq!(timestamp_seq.data_type, "BIGINT");
632 assert_eq!(timestamp_seq.start_value, Some(0));
633
634 assert_eq!(counter_seq.data_type, "INTEGER");
635 assert_eq!(counter_seq.start_value, Some(0));
636 assert_eq!(counter_seq.minimum_value, Some(0));
637
638 assert_eq!(cycling_seq.data_type, "INTEGER");
639 assert_eq!(cycling_seq.maximum_value, Some(1000));
640 assert_eq!(cycling_seq.cycle, Some(true));
641
642 assert_eq!(cached_seq.data_type, "BIGINT");
643 assert_eq!(cached_seq.cache, Some(10));
644 }
645
646 #[test]
647 fn test_sequence_with_all_properties() {
648 let sequence = SequenceBuilder::new()
649 .name("comprehensive_seq")
650 .in_schema("public")
651 .data_type("BIGINT")
652 .start_value(100)
653 .minimum_value(1)
654 .maximum_value(10000)
655 .increment(5)
656 .cycle(true)
657 .cache(20)
658 .owner("postgres")
659 .comment("Comprehensive test sequence")
660 .build()
661 .unwrap();
662
663 assert_eq!(sequence.name, "comprehensive_seq");
664 assert_eq!(sequence.schema, Some("public".to_string()));
665 assert_eq!(sequence.data_type, "BIGINT");
666 assert_eq!(sequence.start_value, Some(100));
667 assert_eq!(sequence.minimum_value, Some(1));
668 assert_eq!(sequence.maximum_value, Some(10000));
669 assert_eq!(sequence.increment, Some(5));
670 assert_eq!(sequence.cycle, Some(true));
671 assert_eq!(sequence.cache, Some(20));
672 assert_eq!(sequence.owner, Some("postgres".to_string()));
673 assert_eq!(
674 sequence.comment,
675 Some("Comprehensive test sequence".to_string())
676 );
677 }
678
679 #[test]
680 fn test_validation_errors() {
681 let result = SequenceBuilder::new().data_type("BIGINT").build();
683 assert!(result.is_err());
684 assert!(matches!(
685 result.unwrap_err(),
686 SequenceBuildError::ValidationError(_)
687 ));
688
689 let result = SequenceBuilder::new().name("").data_type("BIGINT").build();
691 assert!(result.is_err());
692 assert!(matches!(
693 result.unwrap_err(),
694 SequenceBuildError::ValidationError(_)
695 ));
696
697 let result = SequenceBuilder::new()
699 .name("test_seq")
700 .data_type("INTEGER")
701 .minimum_value(100)
702 .maximum_value(50)
703 .build();
704 assert!(result.is_err());
705 assert!(matches!(
706 result.unwrap_err(),
707 SequenceBuildError::ValidationError(_)
708 ));
709
710 let result = SequenceBuilder::new()
712 .name("test_seq")
713 .data_type("INTEGER")
714 .increment(0)
715 .build();
716 assert!(result.is_err());
717 assert!(matches!(
718 result.unwrap_err(),
719 SequenceBuildError::ValidationError(_)
720 ));
721
722 let result = SequenceBuilder::new()
724 .name("test_seq")
725 .data_type("INTEGER")
726 .cache(-5)
727 .build();
728 assert!(result.is_err());
729 assert!(matches!(
730 result.unwrap_err(),
731 SequenceBuildError::ValidationError(_)
732 ));
733 }
734
735 #[test]
736 fn test_conditional_builder() {
737 let condition = true;
738 let sequence = SequenceBuilder::new()
739 .when(condition, |s| {
740 s.set_name("sequence_when_true");
741 s.set_data_type("INTEGER");
742 s.set_start_value(100);
743 s.set_increment(5);
744 })
745 .build()
746 .unwrap();
747
748 assert_eq!(sequence.name, "sequence_when_true");
749 assert_eq!(sequence.data_type, "INTEGER");
750 assert_eq!(sequence.start_value, Some(100));
751 assert_eq!(sequence.increment, Some(5));
752 }
753
754 #[test]
755 fn test_inspection_methods() {
756 let builder = SequenceBuilder::new()
757 .name("test_sequence")
758 .in_schema("public")
759 .data_type("BIGINT")
760 .start_value(1)
761 .minimum_value(1)
762 .maximum_value(1000)
763 .increment(1)
764 .cycle(false)
765 .cache(10)
766 .owner("postgres")
767 .comment("This is a test sequence");
768
769 assert_eq!(builder.get_name(), Some("test_sequence"));
770 assert_eq!(builder.get_schema(), Some("public"));
771 assert_eq!(builder.get_data_type(), Some("BIGINT"));
772 assert_eq!(builder.get_start_value(), Some(1));
773 assert_eq!(builder.get_minimum_value(), Some(1));
774 assert_eq!(builder.get_maximum_value(), Some(1000));
775 assert_eq!(builder.get_increment(), Some(1));
776 assert_eq!(builder.get_cycle(), Some(false));
777 assert_eq!(builder.get_cache(), Some(10));
778 assert_eq!(builder.get_owner(), Some("postgres"));
779 assert_eq!(builder.get_comment(), Some("This is a test sequence"));
780
781 assert!(builder.has_name());
782 assert!(builder.has_schema());
783 assert!(builder.has_data_type());
784 assert!(builder.has_start_value());
785 assert!(builder.has_minimum_value());
786 assert!(builder.has_maximum_value());
787 assert!(builder.has_increment());
788 assert!(builder.has_cycle());
789 assert!(builder.has_cache());
790 assert!(builder.has_owner());
791 assert!(builder.has_comment());
792 }
793
794 #[test]
795 fn test_debug_info_and_summary() {
796 let builder = SequenceBuilder::new()
797 .name("user_id_seq")
798 .in_schema("public")
799 .data_type("BIGINT")
800 .start_value(1)
801 .increment(1)
802 .minimum_value(1)
803 .maximum_value(1000000)
804 .cycle(false)
805 .cache(10)
806 .comment("User ID sequence");
807
808 let debug_info = builder.debug_info();
809 let summary = builder.summary();
810
811 assert!(debug_info.contains("SequenceBuilder"));
812 assert!(debug_info.contains("user_id_seq"));
813 assert!(debug_info.contains("public"));
814
815 assert!(summary.contains("Sequence"));
816 assert!(summary.contains("public.user_id_seq"));
817 assert!(summary.contains("type: BIGINT"));
818 assert!(summary.contains("starts at 1"));
819 assert!(summary.contains("increments by 1"));
820 assert!(summary.contains("range: min: 1, max: 1000000"));
821 assert!(summary.contains("no cycle"));
822 assert!(summary.contains("cache: 10"));
823 assert!(summary.contains("with comment: User ID sequence"));
824 }
825
826 #[test]
827 fn test_sequence_with_complex_constraints() {
828 let sequence = SequenceBuilder::new()
829 .name("complex_seq")
830 .data_type("INTEGER")
831 .start_value(-1000)
832 .minimum_value(-10000)
833 .maximum_value(10000)
834 .increment(100)
835 .cycle(true)
836 .cache(50)
837 .build()
838 .unwrap();
839
840 assert_eq!(sequence.name, "complex_seq");
841 assert_eq!(sequence.data_type, "INTEGER");
842 assert_eq!(sequence.start_value, Some(-1000));
843 assert_eq!(sequence.minimum_value, Some(-10000));
844 assert_eq!(sequence.maximum_value, Some(10000));
845 assert_eq!(sequence.increment, Some(100));
846 assert_eq!(sequence.cycle, Some(true));
847 assert_eq!(sequence.cache, Some(50));
848 }
849
850 #[test]
851 fn test_sequence_with_owner() {
852 let sequence = SequenceBuilder::new()
853 .name("owned_seq")
854 .data_type("BIGINT")
855 .owner("app_user")
856 .build()
857 .unwrap();
858
859 assert_eq!(sequence.name, "owned_seq");
860 assert_eq!(sequence.owner, Some("app_user".to_string()));
861 }
862
863 #[test]
864 fn test_sequence_with_comment() {
865 let sequence = SequenceBuilder::new()
866 .name("commented_seq")
867 .data_type("INTEGER")
868 .comment("This sequence is used for generating unique IDs")
869 .build()
870 .unwrap();
871
872 assert_eq!(sequence.name, "commented_seq");
873 assert_eq!(
874 sequence.comment,
875 Some("This sequence is used for generating unique IDs".to_string())
876 );
877 }
878}