Skip to main content

ignis_db/builders/
column.rs

1//! ColumnBuilder for Ignis-DB
2//!
3//! This module provides a fluent builder API for constructing database columns
4//! with comprehensive validation and configuration options.
5
6use 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/// Builder for creating database columns
14///
15/// This builder provides a fluent, chainable API for constructing columns
16/// with comprehensive validation and configuration options.
17///
18/// # Examples
19///
20/// ```rust
21/// use ignis_db::builders::{ColumnBuilder, column};
22/// use ignis_db::schema::ColumnType;
23///
24/// // Basic column
25/// let id_column = ColumnBuilder::new("id", ColumnType::Int4)
26///     .primary_key()
27///     .build()?;
28///
29/// // Advanced column with constraints
30/// let email_column = ColumnBuilder::new("email", ColumnType::Varchar(Some(255)))
31///     .not_null()
32///     .unique()
33///     .default("'unknown@example.com'")
34///     .check("email ~* '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$'")
35///     .comment("User email address")
36///     .build()?;
37///
38/// // Generated column
39/// let full_name_column = ColumnBuilder::new("full_name", ColumnType::Varchar(Some(200)))
40///     .generated_as("first_name || ' ' || last_name", true)
41///     .comment("Automatically generated full name")
42///     .build()?;
43///
44/// // Foreign key column
45/// let user_id_column = ColumnBuilder::new("user_id", ColumnType::Int4)
46///     .not_null()
47///     .references("users", "id")
48///     .on_delete("CASCADE")
49///     .build()?;
50/// ```
51#[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/// Builder for foreign key references
68#[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/// Specification for generated columns
77///
78/// This struct is prepared for future enhancement when generated columns
79/// are fully implemented in the Column schema.
80#[derive(Debug, Clone)]
81pub struct GeneratedColumnSpec {
82    /// The expression that generates the column value
83    pub expression: String,
84    /// Whether the generated column is stored (true) or virtual (false)
85    pub stored: bool,
86}
87
88impl ColumnBuilder {
89    /// Create a new column builder
90    ///
91    /// # Parameters
92    ///
93    /// - `name`: The name of the column
94    /// - `column_type`: The data type of the column
95    ///
96    /// # Examples
97    ///
98    /// ```rust
99    /// use ignis_db::builders::ColumnBuilder;
100    /// use ignis_db::schema::ColumnType;
101    ///
102    /// let column = ColumnBuilder::new("id", ColumnType::Int4);
103    /// ```
104    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    /// Create a column builder from a string definition
122    ///
123    /// This is a convenience method for creating columns from raw SQL definitions.
124    /// It parses the definition to extract basic information.
125    ///
126    /// # Parameters
127    ///
128    /// - `name`: The name of the column
129    /// - `definition`: The column definition (e.g., "UUID PRIMARY KEY DEFAULT gen_random_uuid()")
130    ///
131    /// # Examples
132    ///
133    /// ```rust
134    /// let column = ColumnBuilder::from_definition("id", "UUID PRIMARY KEY DEFAULT gen_random_uuid()");
135    /// let column = ColumnBuilder::from_definition("email", "VARCHAR(255) UNIQUE NOT NULL");
136    /// ```
137    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        // Parse the definition to determine column type and constraints
142        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    /// Parse a column definition string to extract type and constraints
161    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        // Check for PRIMARY KEY
168        if definition.contains("PRIMARY KEY") {
169            primary_key = true;
170            nullable = false; // Primary keys are always NOT NULL
171        }
172        
173        // Check for UNIQUE
174        if definition.contains("UNIQUE") {
175            unique = true;
176        }
177        
178        // Check for NOT NULL
179        if definition.contains("NOT NULL") {
180            nullable = false;
181        }
182        
183        // Extract DEFAULT value
184        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        // Determine column type
194        let column_type = if definition.contains("UUID") {
195            ColumnType::Uuid
196        } else if definition.contains("VARCHAR") {
197            // Extract length if present
198            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            // Default to Text for unknown types
242            ColumnType::Text
243        };
244        
245        (column_type, primary_key, unique, nullable, default)
246    }
247
248    /// Make the column nullable (default behavior)
249    ///
250    /// # Examples
251    ///
252    /// ```rust
253    /// let column = ColumnBuilder::new("description", ColumnType::Text)
254    ///     .nullable()
255    ///     .build()?;
256    /// ```
257    pub fn nullable(mut self) -> Self {
258        self.nullable = true;
259        self
260    }
261
262    /// Make the column NOT NULL
263    ///
264    /// # Examples
265    ///
266    /// ```rust
267    /// let column = ColumnBuilder::new("email", ColumnType::Varchar(Some(255)))
268    ///     .not_null()
269    ///     .build()?;
270    /// ```
271    pub fn not_null(mut self) -> Self {
272        self.nullable = false;
273        self
274    }
275
276    /// Set a default value for the column
277    ///
278    /// # Parameters
279    ///
280    /// - `default`: The default value expression
281    ///
282    /// # Examples
283    ///
284    /// ```rust
285    /// let column = ColumnBuilder::new("created_at", ColumnType::Timestamptz)
286    ///     .default("NOW()")
287    ///     .build()?;
288    ///
289    /// let column = ColumnBuilder::new("status", ColumnType::Varchar(Some(20)))
290    ///     .default("'active'")
291    ///     .build()?;
292    /// ```
293    pub fn default(mut self, default: impl Into<String>) -> Self {
294        self.default = Some(default.into());
295        self
296    }
297
298    /// Make the column a primary key
299    ///
300    /// This automatically sets the column to NOT NULL.
301    ///
302    /// # Examples
303    ///
304    /// ```rust
305    /// let column = ColumnBuilder::new("id", ColumnType::Int4)
306    ///     .primary_key()
307    ///     .build()?;
308    /// ```
309    pub fn primary_key(mut self) -> Self {
310        self.primary_key = true;
311        self.nullable = false; // Primary keys are always NOT NULL
312        self
313    }
314
315    /// Make the column unique
316    ///
317    /// # Examples
318    ///
319    /// ```rust
320    /// let column = ColumnBuilder::new("email", ColumnType::Varchar(Some(255)))
321    ///     .unique()
322    ///     .build()?;
323    /// ```
324    pub fn unique(mut self) -> Self {
325        self.unique = true;
326        self
327    }
328
329    /// Add a foreign key reference
330    ///
331    /// # Parameters
332    ///
333    /// - `table`: The referenced table name
334    /// - `column`: The referenced column name
335    ///
336    /// # Examples
337    ///
338    /// ```rust
339    /// let column = ColumnBuilder::new("user_id", ColumnType::Int4)
340    ///     .references("users", "id")
341    ///     .build()?;
342    /// ```
343    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    /// Add a check constraint
349    ///
350    /// # Parameters
351    ///
352    /// - `constraint`: The check constraint expression
353    ///
354    /// # Examples
355    ///
356    /// ```rust
357    /// let column = ColumnBuilder::new("age", ColumnType::Int4)
358    ///     .check("age >= 0")
359    ///     .build()?;
360    ///
361    /// let column = ColumnBuilder::new("email", ColumnType::Varchar(Some(255)))
362    ///     .check("email ~* '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$'")
363    ///     .build()?;
364    /// ```
365    pub fn check(mut self, constraint: impl Into<String>) -> Self {
366        self.check_constraint = Some(constraint.into());
367        self
368    }
369
370    /// Add a comment to the column
371    ///
372    /// # Parameters
373    ///
374    /// - `comment`: The comment text
375    ///
376    /// # Examples
377    ///
378    /// ```rust
379    /// let column = ColumnBuilder::new("email", ColumnType::Varchar(Some(255)))
380    ///     .comment("User email address")
381    ///     .build()?;
382    /// ```
383    pub fn comment(mut self, comment: impl Into<String>) -> Self {
384        self.comment = Some(comment.into());
385        self
386    }
387
388    /// Set the collation for the column
389    ///
390    /// # Parameters
391    ///
392    /// - `collation`: The collation name
393    ///
394    /// # Examples
395    ///
396    /// ```rust
397    /// let column = ColumnBuilder::new("name", ColumnType::Varchar(Some(100)))
398    ///     .collation("en_US.utf8")
399    ///     .build()?;
400    /// ```
401    pub fn collation(mut self, collation: impl Into<String>) -> Self {
402        self.collation = Some(collation.into());
403        self
404    }
405
406    /// Make the column a generated column
407    ///
408    /// # Parameters
409    ///
410    /// - `expression`: The generation expression
411    /// - `stored`: Whether the column is stored or virtual
412    ///
413    /// # Examples
414    ///
415    /// ```rust
416    /// let column = ColumnBuilder::new("full_name", ColumnType::Varchar(Some(200)))
417    ///     .generated_as("first_name || ' ' || last_name", true)
418    ///     .build()?;
419    ///
420    /// let column = ColumnBuilder::new("area", ColumnType::Numeric(10, 2))
421    ///     .generated_as("width * height", false)
422    ///     .build()?;
423    /// ```
424    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    /// Add a storage parameter
433    ///
434    /// # Parameters
435    ///
436    /// - `key`: The storage parameter name
437    /// - `value`: The storage parameter value
438    ///
439    /// # Examples
440    ///
441    /// ```rust
442    /// let column = ColumnBuilder::new("data", ColumnType::Text)
443    ///     .storage_parameter("compression", "gzip")
444    ///     .build()?;
445    /// ```
446    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    /// Configure foreign key behavior
452    ///
453    /// This method allows you to configure the ON DELETE and ON UPDATE
454    /// behavior for foreign key references.
455    ///
456    /// # Examples
457    ///
458    /// ```rust
459    /// let column = ColumnBuilder::new("user_id", ColumnType::Int4)
460    ///     .references("users", "id")
461    ///     .on_delete("CASCADE")
462    ///     .on_update("CASCADE")
463    ///     .build()?;
464    /// ```
465    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    /// Configure foreign key update behavior
473    ///
474    /// This method allows you to configure the ON UPDATE behavior
475    /// for foreign key references.
476    ///
477    /// # Examples
478    ///
479    /// ```rust
480    /// let column = ColumnBuilder::new("user_id", ColumnType::Int4)
481    ///     .references("users", "id")
482    ///     .on_update("CASCADE")
483    ///     .build()?;
484    /// ```
485    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    /// Get the column name
493    pub fn name(&self) -> &str {
494        &self.name
495    }
496
497    /// Get the column type
498    pub fn column_type(&self) -> &ColumnType {
499        &self.column_type
500    }
501
502    /// Check if the column is nullable
503    pub fn is_nullable(&self) -> bool {
504        self.nullable
505    }
506
507    /// Check if the column is a primary key
508    pub fn is_primary_key(&self) -> bool {
509        self.primary_key
510    }
511
512    /// Check if the column is unique
513    pub fn is_unique(&self) -> bool {
514        self.unique
515    }
516
517    /// Check if the column has a foreign key reference
518    pub fn has_foreign_key(&self) -> bool {
519        self.references.is_some()
520    }
521
522    /// Check if the column is generated
523    pub fn is_generated(&self) -> bool {
524        self.generated.is_some()
525    }
526
527    /// Get the number of storage parameters
528    pub fn storage_parameter_count(&self) -> usize {
529        self.storage_parameters.len()
530    }
531}
532
533impl ForeignKeyBuilder {
534    /// Create a new foreign key builder
535    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    /// Set the ON DELETE action
545    pub fn on_delete(mut self, action: impl Into<String>) -> Self {
546        self.on_delete = Some(action.into());
547        self
548    }
549
550    /// Set the ON UPDATE action
551    pub fn on_update(mut self, action: impl Into<String>) -> Self {
552        self.on_update = Some(action.into());
553        self
554    }
555
556    /// Build the foreign key
557    pub fn build(self) -> Result<ForeignKey, ColumnBuildError> {
558        // Basic validation
559        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        // Create foreign key - note that on_delete and on_update are not yet
576        // supported in the ForeignKey struct, so we'll create a basic one
577        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        // Validate the configuration
592        self.validate()?;
593
594        // Create the column
595        let mut column = Column::new(self.name, self.column_type);
596
597        // Apply nullable setting
598        if !self.nullable {
599            column = column.not_null();
600        }
601
602        // Apply default value
603        if let Some(default) = self.default {
604            column = column.default(default);
605        }
606
607        // Apply unique setting
608        if self.unique {
609            column = column.unique();
610        }
611
612        // Apply foreign key reference
613        if let Some(fk) = self.references {
614            let foreign_key = fk.build()?;
615            column = column.references(foreign_key);
616        }
617
618        // Apply check constraint
619        if let Some(check) = self.check_constraint {
620            column = column.check(check);
621        }
622
623        // Note: Comment, collation, generated columns, and storage parameters
624        // are not yet supported in the Column struct. These will be added
625        // in future enhancements.
626
627        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        // Validate column name
640        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        // Validate generated column constraints
649        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        // Validate check constraint
664        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        // Validate default value
675        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    /// Validate the column configuration
735    fn validate(&self) -> Result<(), ColumnBuildError> {
736        // Check for validation errors
737        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        // Note: primary_key is not yet implemented in Column struct
762    }
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}