1use crate::builders::traits::{
7 ConditionalBuilder, InspectableBuilder, SchemaBuilder, ValidatableBuilder,
8};
9use crate::builders::validation::ColumnBuildError;
10use crate::schema::{Column, ColumnType, ForeignKey};
11use std::collections::HashMap;
12
13#[derive(Debug, Clone)]
52pub struct ColumnBuilder {
53 name: String,
54 column_type: ColumnType,
55 nullable: bool,
56 default: Option<String>,
57 primary_key: bool,
58 unique: bool,
59 references: Option<ForeignKeyBuilder>,
60 check_constraint: Option<String>,
61 comment: Option<String>,
62 collation: Option<String>,
63 generated: Option<GeneratedColumnSpec>,
64 storage_parameters: HashMap<String, String>,
65}
66
67#[derive(Debug, Clone)]
69pub struct ForeignKeyBuilder {
70 table: String,
71 column: String,
72 on_delete: Option<String>,
73 on_update: Option<String>,
74}
75
76#[derive(Debug, Clone)]
81pub struct GeneratedColumnSpec {
82 pub expression: String,
84 pub stored: bool,
86}
87
88impl ColumnBuilder {
89 pub fn new(name: impl Into<String>, column_type: ColumnType) -> Self {
105 Self {
106 name: name.into(),
107 column_type,
108 nullable: true,
109 default: None,
110 primary_key: false,
111 unique: false,
112 references: None,
113 check_constraint: None,
114 comment: None,
115 collation: None,
116 generated: None,
117 storage_parameters: HashMap::new(),
118 }
119 }
120
121 pub fn from_definition(name: impl Into<String>, definition: impl Into<String>) -> Self {
138 let name = name.into();
139 let definition = definition.into().to_uppercase();
140
141 let (column_type, primary_key, unique, nullable, default) = Self::parse_definition(&definition);
143
144 Self {
145 name,
146 column_type,
147 nullable,
148 default,
149 primary_key,
150 unique,
151 references: None,
152 check_constraint: None,
153 comment: None,
154 collation: None,
155 generated: None,
156 storage_parameters: HashMap::new(),
157 }
158 }
159
160 fn parse_definition(definition: &str) -> (ColumnType, bool, bool, bool, Option<String>) {
162 let mut primary_key = false;
163 let mut unique = false;
164 let mut nullable = true;
165 let mut default = None;
166
167 if definition.contains("PRIMARY KEY") {
169 primary_key = true;
170 nullable = false; }
172
173 if definition.contains("UNIQUE") {
175 unique = true;
176 }
177
178 if definition.contains("NOT NULL") {
180 nullable = false;
181 }
182
183 if let Some(start) = definition.find("DEFAULT ") {
185 let after_default = &definition[start + 8..];
186 if let Some(end) = after_default.find(' ') {
187 default = Some(after_default[..end].to_string());
188 } else {
189 default = Some(after_default.to_string());
190 }
191 }
192
193 let column_type = if definition.contains("UUID") {
195 ColumnType::Uuid
196 } else if definition.contains("VARCHAR") {
197 if let Some(start) = definition.find("VARCHAR(") {
199 let after_varchar = &definition[start + 8..];
200 if let Some(end) = after_varchar.find(')') {
201 if let Ok(length) = after_varchar[..end].parse::<u32>() {
202 ColumnType::Varchar(Some(length as usize))
203 } else {
204 ColumnType::Varchar(None)
205 }
206 } else {
207 ColumnType::Varchar(None)
208 }
209 } else {
210 ColumnType::Varchar(None)
211 }
212 } else if definition.contains("TEXT") {
213 ColumnType::Text
214 } else if definition.contains("INTEGER") || definition.contains("INT4") {
215 ColumnType::Int4
216 } else if definition.contains("BIGINT") || definition.contains("INT8") {
217 ColumnType::Int8
218 } else if definition.contains("SMALLINT") || definition.contains("INT2") {
219 ColumnType::Int2
220 } else if definition.contains("BOOLEAN") || definition.contains("BOOL") {
221 ColumnType::Bool
222 } else if definition.contains("TIMESTAMPTZ") {
223 ColumnType::Timestamptz
224 } else if definition.contains("TIMESTAMP") {
225 ColumnType::Timestamptz
226 } else if definition.contains("DATE") {
227 ColumnType::Date
228 } else if definition.contains("TIME") {
229 ColumnType::Time
230 } else if definition.contains("JSONB") {
231 ColumnType::Jsonb
232 } else if definition.contains("JSON") {
233 ColumnType::Json
234 } else if definition.contains("NUMERIC") {
235 ColumnType::Numeric(None, None)
236 } else if definition.contains("SERIAL") {
237 ColumnType::Serial
238 } else if definition.contains("BIGSERIAL") {
239 ColumnType::BigSerial
240 } else {
241 ColumnType::Text
243 };
244
245 (column_type, primary_key, unique, nullable, default)
246 }
247
248 pub fn nullable(mut self) -> Self {
258 self.nullable = true;
259 self
260 }
261
262 pub fn not_null(mut self) -> Self {
272 self.nullable = false;
273 self
274 }
275
276 pub fn default(mut self, default: impl Into<String>) -> Self {
294 self.default = Some(default.into());
295 self
296 }
297
298 pub fn primary_key(mut self) -> Self {
310 self.primary_key = true;
311 self.nullable = false; self
313 }
314
315 pub fn unique(mut self) -> Self {
325 self.unique = true;
326 self
327 }
328
329 pub fn references(mut self, table: impl Into<String>, column: impl Into<String>) -> Self {
344 self.references = Some(ForeignKeyBuilder::new(table, column));
345 self
346 }
347
348 pub fn check(mut self, constraint: impl Into<String>) -> Self {
366 self.check_constraint = Some(constraint.into());
367 self
368 }
369
370 pub fn comment(mut self, comment: impl Into<String>) -> Self {
384 self.comment = Some(comment.into());
385 self
386 }
387
388 pub fn collation(mut self, collation: impl Into<String>) -> Self {
402 self.collation = Some(collation.into());
403 self
404 }
405
406 pub fn generated_as(mut self, expression: impl Into<String>, stored: bool) -> Self {
425 self.generated = Some(GeneratedColumnSpec {
426 expression: expression.into(),
427 stored,
428 });
429 self
430 }
431
432 pub fn storage_parameter(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
447 self.storage_parameters.insert(key.into(), value.into());
448 self
449 }
450
451 pub fn on_delete(mut self, action: impl Into<String>) -> Self {
466 if let Some(ref mut fk) = self.references {
467 fk.on_delete = Some(action.into());
468 }
469 self
470 }
471
472 pub fn on_update(mut self, action: impl Into<String>) -> Self {
486 if let Some(ref mut fk) = self.references {
487 fk.on_update = Some(action.into());
488 }
489 self
490 }
491
492 pub fn name(&self) -> &str {
494 &self.name
495 }
496
497 pub fn column_type(&self) -> &ColumnType {
499 &self.column_type
500 }
501
502 pub fn is_nullable(&self) -> bool {
504 self.nullable
505 }
506
507 pub fn is_primary_key(&self) -> bool {
509 self.primary_key
510 }
511
512 pub fn is_unique(&self) -> bool {
514 self.unique
515 }
516
517 pub fn has_foreign_key(&self) -> bool {
519 self.references.is_some()
520 }
521
522 pub fn is_generated(&self) -> bool {
524 self.generated.is_some()
525 }
526
527 pub fn storage_parameter_count(&self) -> usize {
529 self.storage_parameters.len()
530 }
531}
532
533impl ForeignKeyBuilder {
534 pub fn new(table: impl Into<String>, column: impl Into<String>) -> Self {
536 Self {
537 table: table.into(),
538 column: column.into(),
539 on_delete: None,
540 on_update: None,
541 }
542 }
543
544 pub fn on_delete(mut self, action: impl Into<String>) -> Self {
546 self.on_delete = Some(action.into());
547 self
548 }
549
550 pub fn on_update(mut self, action: impl Into<String>) -> Self {
552 self.on_update = Some(action.into());
553 self
554 }
555
556 pub fn build(self) -> Result<ForeignKey, ColumnBuildError> {
558 if self.table.is_empty() {
560 return Err(ColumnBuildError::ForeignKeyError(
561 crate::builders::validation::ForeignKeyBuildError::InvalidReferencedTable(
562 "Empty table name".to_string(),
563 ),
564 ));
565 }
566
567 if self.column.is_empty() {
568 return Err(ColumnBuildError::ForeignKeyError(
569 crate::builders::validation::ForeignKeyBuildError::InvalidReferencedColumn(
570 "Empty column name".to_string(),
571 ),
572 ));
573 }
574
575 let fk = ForeignKey {
578 table: self.table,
579 column: self.column,
580 };
581
582 Ok(fk)
583 }
584}
585
586impl SchemaBuilder for ColumnBuilder {
587 type Output = Column;
588 type Error = ColumnBuildError;
589
590 fn build(self) -> Result<Self::Output, Self::Error> {
591 self.validate()?;
593
594 let mut column = Column::new(self.name, self.column_type);
596
597 if !self.nullable {
599 column = column.not_null();
600 }
601
602 if let Some(default) = self.default {
604 column = column.default(default);
605 }
606
607 if self.unique {
609 column = column.unique();
610 }
611
612 if let Some(fk) = self.references {
614 let foreign_key = fk.build()?;
615 column = column.references(foreign_key);
616 }
617
618 if let Some(check) = self.check_constraint {
620 column = column.check(check);
621 }
622
623 Ok(column)
628 }
629}
630
631impl ValidatableBuilder for ColumnBuilder {
632 fn is_valid(&self) -> bool {
633 self.validation_errors().is_empty()
634 }
635
636 fn validation_errors(&self) -> Vec<String> {
637 let mut errors = Vec::new();
638
639 if self.name.is_empty() {
641 errors.push("Column name cannot be empty".to_string());
642 }
643
644 if self.name.len() > 63 {
645 errors.push("Column name cannot exceed 63 characters".to_string());
646 }
647
648 if let Some(_) = self.generated {
650 if self.default.is_some() {
651 errors.push("Generated columns cannot have default values".to_string());
652 }
653
654 if self.primary_key {
655 errors.push("Generated columns cannot be primary keys".to_string());
656 }
657
658 if self.references.is_some() {
659 errors.push("Generated columns cannot have foreign key references".to_string());
660 }
661 }
662
663 if let Some(check) = &self.check_constraint {
665 if check.is_empty() {
666 errors.push("Check constraint expression cannot be empty".to_string());
667 }
668
669 if check.len() > 1000 {
670 errors.push("Check constraint expression is too long".to_string());
671 }
672 }
673
674 if let Some(default) = &self.default {
676 if default.is_empty() {
677 errors.push("Default value cannot be empty".to_string());
678 }
679 }
680
681 errors
682 }
683}
684
685impl ConditionalBuilder for ColumnBuilder {}
686
687impl InspectableBuilder for ColumnBuilder {
688 fn debug_info(&self) -> String {
689 format!(
690 "ColumnBuilder {{ name: {:?}, type: {:?}, nullable: {}, primary_key: {}, unique: {}, generated: {:?} }}",
691 self.name, self.column_type, self.nullable, self.primary_key, self.unique, self.generated
692 )
693 }
694
695 fn summary(&self) -> String {
696 let mut parts = vec![
697 format!("column '{}'", self.name),
698 format!("type {:?}", self.column_type),
699 ];
700
701 if !self.nullable {
702 parts.push("NOT NULL".to_string());
703 }
704
705 if self.primary_key {
706 parts.push("PRIMARY KEY".to_string());
707 }
708
709 if self.unique {
710 parts.push("UNIQUE".to_string());
711 }
712
713 if self.default.is_some() {
714 parts.push("with default".to_string());
715 }
716
717 if self.references.is_some() {
718 parts.push("with foreign key".to_string());
719 }
720
721 if self.check_constraint.is_some() {
722 parts.push("with check constraint".to_string());
723 }
724
725 if self.generated.is_some() {
726 parts.push("generated".to_string());
727 }
728
729 parts.join(", ")
730 }
731}
732
733impl ColumnBuilder {
734 fn validate(&self) -> Result<(), ColumnBuildError> {
736 let errors = self.validation_errors();
738 if !errors.is_empty() {
739 return Err(ColumnBuildError::ValidationError(errors.join("; ")));
740 }
741
742 Ok(())
743 }
744}
745
746#[cfg(test)]
747mod tests {
748 use super::*;
749 use crate::schema::ColumnType;
750
751 #[test]
752 fn test_column_builder_basic() {
753 let column = ColumnBuilder::new("id", ColumnType::Int4)
754 .primary_key()
755 .build()
756 .expect("Should build successfully");
757
758 assert_eq!(column.name, "id");
759 assert_eq!(column.column_type, ColumnType::Int4);
760 assert!(!column.nullable);
761 }
763
764 #[test]
765 fn test_column_builder_advanced() {
766 let column = ColumnBuilder::new("email", ColumnType::Varchar(Some(255)))
767 .not_null()
768 .unique()
769 .default("'unknown@example.com'")
770 .comment("User email address")
771 .build()
772 .expect("Should build successfully");
773
774 assert_eq!(column.name, "email");
775 assert_eq!(column.column_type, ColumnType::Varchar(Some(255)));
776 assert!(!column.nullable);
777 assert!(column.unique);
778 }
779
780 #[test]
781 fn test_column_builder_validation() {
782 let result = ColumnBuilder::new("", ColumnType::Int4).build();
783
784 assert!(result.is_err());
785 assert!(matches!(
786 result.unwrap_err(),
787 ColumnBuildError::ValidationError(_)
788 ));
789 }
790
791 #[test]
792 fn test_column_builder_generated_constraints() {
793 let result = ColumnBuilder::new("full_name", ColumnType::Varchar(Some(200)))
794 .generated_as("first_name || ' ' || last_name", true)
795 .default("'Unknown'")
796 .build();
797
798 assert!(result.is_err());
799 assert!(matches!(
800 result.unwrap_err(),
801 ColumnBuildError::ValidationError(_)
802 ));
803 }
804
805 #[test]
806 fn test_column_builder_foreign_key() {
807 let column = ColumnBuilder::new("user_id", ColumnType::Int4)
808 .references("users", "id")
809 .on_delete("CASCADE")
810 .on_update("CASCADE")
811 .build()
812 .expect("Should build successfully");
813
814 assert_eq!(column.name, "user_id");
815 assert!(column.references.is_some());
816 }
817
818 #[test]
819 fn test_column_builder_inspection() {
820 let builder = ColumnBuilder::new("id", ColumnType::Int4)
821 .primary_key()
822 .comment("Primary key");
823
824 assert!(builder.is_valid());
825 assert_eq!(builder.name(), "id");
826 assert!(builder.is_primary_key());
827 assert!(!builder.is_nullable());
828
829 let summary = builder.summary();
830 assert!(summary.contains("column 'id'"));
831 assert!(summary.contains("PRIMARY KEY"));
832 }
833}