ignis-db 0.2.0

A comprehensive PostgreSQL ORM with macro-driven schema management
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
//! ColumnBuilder for Ignis-DB
//!
//! This module provides a fluent builder API for constructing database columns
//! with comprehensive validation and configuration options.

use crate::builders::traits::{
    ConditionalBuilder, InspectableBuilder, SchemaBuilder, ValidatableBuilder,
};
use crate::builders::validation::ColumnBuildError;
use crate::schema::{Column, ColumnType, ForeignKey};
use std::collections::HashMap;

/// Builder for creating database columns
///
/// This builder provides a fluent, chainable API for constructing columns
/// with comprehensive validation and configuration options.
///
/// # Examples
///
/// ```rust
/// use ignis_db::builders::{ColumnBuilder, column};
/// use ignis_db::schema::ColumnType;
///
/// // Basic column
/// let id_column = ColumnBuilder::new("id", ColumnType::Int4)
///     .primary_key()
///     .build()?;
///
/// // Advanced column with constraints
/// let email_column = ColumnBuilder::new("email", ColumnType::Varchar(Some(255)))
///     .not_null()
///     .unique()
///     .default("'unknown@example.com'")
///     .check("email ~* '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$'")
///     .comment("User email address")
///     .build()?;
///
/// // Generated column
/// let full_name_column = ColumnBuilder::new("full_name", ColumnType::Varchar(Some(200)))
///     .generated_as("first_name || ' ' || last_name", true)
///     .comment("Automatically generated full name")
///     .build()?;
///
/// // Foreign key column
/// let user_id_column = ColumnBuilder::new("user_id", ColumnType::Int4)
///     .not_null()
///     .references("users", "id")
///     .on_delete("CASCADE")
///     .build()?;
/// ```
#[derive(Debug, Clone)]
pub struct ColumnBuilder {
    name: String,
    column_type: ColumnType,
    nullable: bool,
    default: Option<String>,
    primary_key: bool,
    unique: bool,
    references: Option<ForeignKeyBuilder>,
    check_constraint: Option<String>,
    comment: Option<String>,
    collation: Option<String>,
    generated: Option<GeneratedColumnSpec>,
    storage_parameters: HashMap<String, String>,
}

/// Builder for foreign key references
#[derive(Debug, Clone)]
pub struct ForeignKeyBuilder {
    table: String,
    column: String,
    on_delete: Option<String>,
    on_update: Option<String>,
}

/// Specification for generated columns
///
/// This struct is prepared for future enhancement when generated columns
/// are fully implemented in the Column schema.
#[derive(Debug, Clone)]
pub struct GeneratedColumnSpec {
    /// The expression that generates the column value
    pub expression: String,
    /// Whether the generated column is stored (true) or virtual (false)
    pub stored: bool,
}

impl ColumnBuilder {
    /// Create a new column builder
    ///
    /// # Parameters
    ///
    /// - `name`: The name of the column
    /// - `column_type`: The data type of the column
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ignis_db::builders::ColumnBuilder;
    /// use ignis_db::schema::ColumnType;
    ///
    /// let column = ColumnBuilder::new("id", ColumnType::Int4);
    /// ```
    pub fn new(name: impl Into<String>, column_type: ColumnType) -> Self {
        Self {
            name: name.into(),
            column_type,
            nullable: true,
            default: None,
            primary_key: false,
            unique: false,
            references: None,
            check_constraint: None,
            comment: None,
            collation: None,
            generated: None,
            storage_parameters: HashMap::new(),
        }
    }

    /// Create a column builder from a string definition
    ///
    /// This is a convenience method for creating columns from raw SQL definitions.
    /// It parses the definition to extract basic information.
    ///
    /// # Parameters
    ///
    /// - `name`: The name of the column
    /// - `definition`: The column definition (e.g., "UUID PRIMARY KEY DEFAULT gen_random_uuid()")
    ///
    /// # Examples
    ///
    /// ```rust
    /// let column = ColumnBuilder::from_definition("id", "UUID PRIMARY KEY DEFAULT gen_random_uuid()");
    /// let column = ColumnBuilder::from_definition("email", "VARCHAR(255) UNIQUE NOT NULL");
    /// ```
    pub fn from_definition(name: impl Into<String>, definition: impl Into<String>) -> Self {
        let name = name.into();
        let definition = definition.into().to_uppercase();
        
        // Parse the definition to determine column type and constraints
        let (column_type, primary_key, unique, nullable, default) = Self::parse_definition(&definition);
        
        Self {
            name,
            column_type,
            nullable,
            default,
            primary_key,
            unique,
            references: None,
            check_constraint: None,
            comment: None,
            collation: None,
            generated: None,
            storage_parameters: HashMap::new(),
        }
    }

    /// Parse a column definition string to extract type and constraints
    fn parse_definition(definition: &str) -> (ColumnType, bool, bool, bool, Option<String>) {
        let mut primary_key = false;
        let mut unique = false;
        let mut nullable = true;
        let mut default = None;
        
        // Check for PRIMARY KEY
        if definition.contains("PRIMARY KEY") {
            primary_key = true;
            nullable = false; // Primary keys are always NOT NULL
        }
        
        // Check for UNIQUE
        if definition.contains("UNIQUE") {
            unique = true;
        }
        
        // Check for NOT NULL
        if definition.contains("NOT NULL") {
            nullable = false;
        }
        
        // Extract DEFAULT value
        if let Some(start) = definition.find("DEFAULT ") {
            let after_default = &definition[start + 8..];
            if let Some(end) = after_default.find(' ') {
                default = Some(after_default[..end].to_string());
            } else {
                default = Some(after_default.to_string());
            }
        }
        
        // Determine column type
        let column_type = if definition.contains("UUID") {
            ColumnType::Uuid
        } else if definition.contains("VARCHAR") {
            // Extract length if present
            if let Some(start) = definition.find("VARCHAR(") {
                let after_varchar = &definition[start + 8..];
                if let Some(end) = after_varchar.find(')') {
                    if let Ok(length) = after_varchar[..end].parse::<u32>() {
                        ColumnType::Varchar(Some(length as usize))
                    } else {
                        ColumnType::Varchar(None)
                    }
                } else {
                    ColumnType::Varchar(None)
                }
            } else {
                ColumnType::Varchar(None)
            }
        } else if definition.contains("TEXT") {
            ColumnType::Text
        } else if definition.contains("INTEGER") || definition.contains("INT4") {
            ColumnType::Int4
        } else if definition.contains("BIGINT") || definition.contains("INT8") {
            ColumnType::Int8
        } else if definition.contains("SMALLINT") || definition.contains("INT2") {
            ColumnType::Int2
        } else if definition.contains("BOOLEAN") || definition.contains("BOOL") {
            ColumnType::Bool
        } else if definition.contains("TIMESTAMPTZ") {
            ColumnType::Timestamptz
        } else if definition.contains("TIMESTAMP") {
            ColumnType::Timestamptz
        } else if definition.contains("DATE") {
            ColumnType::Date
        } else if definition.contains("TIME") {
            ColumnType::Time
        } else if definition.contains("JSONB") {
            ColumnType::Jsonb
        } else if definition.contains("JSON") {
            ColumnType::Json
        } else if definition.contains("NUMERIC") {
            ColumnType::Numeric(None, None)
        } else if definition.contains("SERIAL") {
            ColumnType::Serial
        } else if definition.contains("BIGSERIAL") {
            ColumnType::BigSerial
        } else {
            // Default to Text for unknown types
            ColumnType::Text
        };
        
        (column_type, primary_key, unique, nullable, default)
    }

    /// Make the column nullable (default behavior)
    ///
    /// # Examples
    ///
    /// ```rust
    /// let column = ColumnBuilder::new("description", ColumnType::Text)
    ///     .nullable()
    ///     .build()?;
    /// ```
    pub fn nullable(mut self) -> Self {
        self.nullable = true;
        self
    }

    /// Make the column NOT NULL
    ///
    /// # Examples
    ///
    /// ```rust
    /// let column = ColumnBuilder::new("email", ColumnType::Varchar(Some(255)))
    ///     .not_null()
    ///     .build()?;
    /// ```
    pub fn not_null(mut self) -> Self {
        self.nullable = false;
        self
    }

    /// Set a default value for the column
    ///
    /// # Parameters
    ///
    /// - `default`: The default value expression
    ///
    /// # Examples
    ///
    /// ```rust
    /// let column = ColumnBuilder::new("created_at", ColumnType::Timestamptz)
    ///     .default("NOW()")
    ///     .build()?;
    ///
    /// let column = ColumnBuilder::new("status", ColumnType::Varchar(Some(20)))
    ///     .default("'active'")
    ///     .build()?;
    /// ```
    pub fn default(mut self, default: impl Into<String>) -> Self {
        self.default = Some(default.into());
        self
    }

    /// Make the column a primary key
    ///
    /// This automatically sets the column to NOT NULL.
    ///
    /// # Examples
    ///
    /// ```rust
    /// let column = ColumnBuilder::new("id", ColumnType::Int4)
    ///     .primary_key()
    ///     .build()?;
    /// ```
    pub fn primary_key(mut self) -> Self {
        self.primary_key = true;
        self.nullable = false; // Primary keys are always NOT NULL
        self
    }

    /// Make the column unique
    ///
    /// # Examples
    ///
    /// ```rust
    /// let column = ColumnBuilder::new("email", ColumnType::Varchar(Some(255)))
    ///     .unique()
    ///     .build()?;
    /// ```
    pub fn unique(mut self) -> Self {
        self.unique = true;
        self
    }

    /// Add a foreign key reference
    ///
    /// # Parameters
    ///
    /// - `table`: The referenced table name
    /// - `column`: The referenced column name
    ///
    /// # Examples
    ///
    /// ```rust
    /// let column = ColumnBuilder::new("user_id", ColumnType::Int4)
    ///     .references("users", "id")
    ///     .build()?;
    /// ```
    pub fn references(mut self, table: impl Into<String>, column: impl Into<String>) -> Self {
        self.references = Some(ForeignKeyBuilder::new(table, column));
        self
    }

    /// Add a check constraint
    ///
    /// # Parameters
    ///
    /// - `constraint`: The check constraint expression
    ///
    /// # Examples
    ///
    /// ```rust
    /// let column = ColumnBuilder::new("age", ColumnType::Int4)
    ///     .check("age >= 0")
    ///     .build()?;
    ///
    /// let column = ColumnBuilder::new("email", ColumnType::Varchar(Some(255)))
    ///     .check("email ~* '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$'")
    ///     .build()?;
    /// ```
    pub fn check(mut self, constraint: impl Into<String>) -> Self {
        self.check_constraint = Some(constraint.into());
        self
    }

    /// Add a comment to the column
    ///
    /// # Parameters
    ///
    /// - `comment`: The comment text
    ///
    /// # Examples
    ///
    /// ```rust
    /// let column = ColumnBuilder::new("email", ColumnType::Varchar(Some(255)))
    ///     .comment("User email address")
    ///     .build()?;
    /// ```
    pub fn comment(mut self, comment: impl Into<String>) -> Self {
        self.comment = Some(comment.into());
        self
    }

    /// Set the collation for the column
    ///
    /// # Parameters
    ///
    /// - `collation`: The collation name
    ///
    /// # Examples
    ///
    /// ```rust
    /// let column = ColumnBuilder::new("name", ColumnType::Varchar(Some(100)))
    ///     .collation("en_US.utf8")
    ///     .build()?;
    /// ```
    pub fn collation(mut self, collation: impl Into<String>) -> Self {
        self.collation = Some(collation.into());
        self
    }

    /// Make the column a generated column
    ///
    /// # Parameters
    ///
    /// - `expression`: The generation expression
    /// - `stored`: Whether the column is stored or virtual
    ///
    /// # Examples
    ///
    /// ```rust
    /// let column = ColumnBuilder::new("full_name", ColumnType::Varchar(Some(200)))
    ///     .generated_as("first_name || ' ' || last_name", true)
    ///     .build()?;
    ///
    /// let column = ColumnBuilder::new("area", ColumnType::Numeric(10, 2))
    ///     .generated_as("width * height", false)
    ///     .build()?;
    /// ```
    pub fn generated_as(mut self, expression: impl Into<String>, stored: bool) -> Self {
        self.generated = Some(GeneratedColumnSpec {
            expression: expression.into(),
            stored,
        });
        self
    }

    /// Add a storage parameter
    ///
    /// # Parameters
    ///
    /// - `key`: The storage parameter name
    /// - `value`: The storage parameter value
    ///
    /// # Examples
    ///
    /// ```rust
    /// let column = ColumnBuilder::new("data", ColumnType::Text)
    ///     .storage_parameter("compression", "gzip")
    ///     .build()?;
    /// ```
    pub fn storage_parameter(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.storage_parameters.insert(key.into(), value.into());
        self
    }

    /// Configure foreign key behavior
    ///
    /// This method allows you to configure the ON DELETE and ON UPDATE
    /// behavior for foreign key references.
    ///
    /// # Examples
    ///
    /// ```rust
    /// let column = ColumnBuilder::new("user_id", ColumnType::Int4)
    ///     .references("users", "id")
    ///     .on_delete("CASCADE")
    ///     .on_update("CASCADE")
    ///     .build()?;
    /// ```
    pub fn on_delete(mut self, action: impl Into<String>) -> Self {
        if let Some(ref mut fk) = self.references {
            fk.on_delete = Some(action.into());
        }
        self
    }

    /// Configure foreign key update behavior
    ///
    /// This method allows you to configure the ON UPDATE behavior
    /// for foreign key references.
    ///
    /// # Examples
    ///
    /// ```rust
    /// let column = ColumnBuilder::new("user_id", ColumnType::Int4)
    ///     .references("users", "id")
    ///     .on_update("CASCADE")
    ///     .build()?;
    /// ```
    pub fn on_update(mut self, action: impl Into<String>) -> Self {
        if let Some(ref mut fk) = self.references {
            fk.on_update = Some(action.into());
        }
        self
    }

    /// Get the column name
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Get the column type
    pub fn column_type(&self) -> &ColumnType {
        &self.column_type
    }

    /// Check if the column is nullable
    pub fn is_nullable(&self) -> bool {
        self.nullable
    }

    /// Check if the column is a primary key
    pub fn is_primary_key(&self) -> bool {
        self.primary_key
    }

    /// Check if the column is unique
    pub fn is_unique(&self) -> bool {
        self.unique
    }

    /// Check if the column has a foreign key reference
    pub fn has_foreign_key(&self) -> bool {
        self.references.is_some()
    }

    /// Check if the column is generated
    pub fn is_generated(&self) -> bool {
        self.generated.is_some()
    }

    /// Get the number of storage parameters
    pub fn storage_parameter_count(&self) -> usize {
        self.storage_parameters.len()
    }
}

impl ForeignKeyBuilder {
    /// Create a new foreign key builder
    pub fn new(table: impl Into<String>, column: impl Into<String>) -> Self {
        Self {
            table: table.into(),
            column: column.into(),
            on_delete: None,
            on_update: None,
        }
    }

    /// Set the ON DELETE action
    pub fn on_delete(mut self, action: impl Into<String>) -> Self {
        self.on_delete = Some(action.into());
        self
    }

    /// Set the ON UPDATE action
    pub fn on_update(mut self, action: impl Into<String>) -> Self {
        self.on_update = Some(action.into());
        self
    }

    /// Build the foreign key
    pub fn build(self) -> Result<ForeignKey, ColumnBuildError> {
        // Basic validation
        if self.table.is_empty() {
            return Err(ColumnBuildError::ForeignKeyError(
                crate::builders::validation::ForeignKeyBuildError::InvalidReferencedTable(
                    "Empty table name".to_string(),
                ),
            ));
        }

        if self.column.is_empty() {
            return Err(ColumnBuildError::ForeignKeyError(
                crate::builders::validation::ForeignKeyBuildError::InvalidReferencedColumn(
                    "Empty column name".to_string(),
                ),
            ));
        }

        // Create foreign key - note that on_delete and on_update are not yet
        // supported in the ForeignKey struct, so we'll create a basic one
        let fk = ForeignKey {
            table: self.table,
            column: self.column,
        };

        Ok(fk)
    }
}

impl SchemaBuilder for ColumnBuilder {
    type Output = Column;
    type Error = ColumnBuildError;

    fn build(self) -> Result<Self::Output, Self::Error> {
        // Validate the configuration
        self.validate()?;

        // Create the column
        let mut column = Column::new(self.name, self.column_type);

        // Apply nullable setting
        if !self.nullable {
            column = column.not_null();
        }

        // Apply default value
        if let Some(default) = self.default {
            column = column.default(default);
        }

        // Apply unique setting
        if self.unique {
            column = column.unique();
        }

        // Apply foreign key reference
        if let Some(fk) = self.references {
            let foreign_key = fk.build()?;
            column = column.references(foreign_key);
        }

        // Apply check constraint
        if let Some(check) = self.check_constraint {
            column = column.check(check);
        }

        // Note: Comment, collation, generated columns, and storage parameters
        // are not yet supported in the Column struct. These will be added
        // in future enhancements.

        Ok(column)
    }
}

impl ValidatableBuilder for ColumnBuilder {
    fn is_valid(&self) -> bool {
        self.validation_errors().is_empty()
    }

    fn validation_errors(&self) -> Vec<String> {
        let mut errors = Vec::new();

        // Validate column name
        if self.name.is_empty() {
            errors.push("Column name cannot be empty".to_string());
        }

        if self.name.len() > 63 {
            errors.push("Column name cannot exceed 63 characters".to_string());
        }

        // Validate generated column constraints
        if let Some(_) = self.generated {
            if self.default.is_some() {
                errors.push("Generated columns cannot have default values".to_string());
            }

            if self.primary_key {
                errors.push("Generated columns cannot be primary keys".to_string());
            }

            if self.references.is_some() {
                errors.push("Generated columns cannot have foreign key references".to_string());
            }
        }

        // Validate check constraint
        if let Some(check) = &self.check_constraint {
            if check.is_empty() {
                errors.push("Check constraint expression cannot be empty".to_string());
            }

            if check.len() > 1000 {
                errors.push("Check constraint expression is too long".to_string());
            }
        }

        // Validate default value
        if let Some(default) = &self.default {
            if default.is_empty() {
                errors.push("Default value cannot be empty".to_string());
            }
        }

        errors
    }
}

impl ConditionalBuilder for ColumnBuilder {}

impl InspectableBuilder for ColumnBuilder {
    fn debug_info(&self) -> String {
        format!(
            "ColumnBuilder {{ name: {:?}, type: {:?}, nullable: {}, primary_key: {}, unique: {}, generated: {:?} }}",
            self.name, self.column_type, self.nullable, self.primary_key, self.unique, self.generated
        )
    }

    fn summary(&self) -> String {
        let mut parts = vec![
            format!("column '{}'", self.name),
            format!("type {:?}", self.column_type),
        ];

        if !self.nullable {
            parts.push("NOT NULL".to_string());
        }

        if self.primary_key {
            parts.push("PRIMARY KEY".to_string());
        }

        if self.unique {
            parts.push("UNIQUE".to_string());
        }

        if self.default.is_some() {
            parts.push("with default".to_string());
        }

        if self.references.is_some() {
            parts.push("with foreign key".to_string());
        }

        if self.check_constraint.is_some() {
            parts.push("with check constraint".to_string());
        }

        if self.generated.is_some() {
            parts.push("generated".to_string());
        }

        parts.join(", ")
    }
}

impl ColumnBuilder {
    /// Validate the column configuration
    fn validate(&self) -> Result<(), ColumnBuildError> {
        // Check for validation errors
        let errors = self.validation_errors();
        if !errors.is_empty() {
            return Err(ColumnBuildError::ValidationError(errors.join("; ")));
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::schema::ColumnType;

    #[test]
    fn test_column_builder_basic() {
        let column = ColumnBuilder::new("id", ColumnType::Int4)
            .primary_key()
            .build()
            .expect("Should build successfully");

        assert_eq!(column.name, "id");
        assert_eq!(column.column_type, ColumnType::Int4);
        assert!(!column.nullable);
        // Note: primary_key is not yet implemented in Column struct
    }

    #[test]
    fn test_column_builder_advanced() {
        let column = ColumnBuilder::new("email", ColumnType::Varchar(Some(255)))
            .not_null()
            .unique()
            .default("'unknown@example.com'")
            .comment("User email address")
            .build()
            .expect("Should build successfully");

        assert_eq!(column.name, "email");
        assert_eq!(column.column_type, ColumnType::Varchar(Some(255)));
        assert!(!column.nullable);
        assert!(column.unique);
    }

    #[test]
    fn test_column_builder_validation() {
        let result = ColumnBuilder::new("", ColumnType::Int4).build();

        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            ColumnBuildError::ValidationError(_)
        ));
    }

    #[test]
    fn test_column_builder_generated_constraints() {
        let result = ColumnBuilder::new("full_name", ColumnType::Varchar(Some(200)))
            .generated_as("first_name || ' ' || last_name", true)
            .default("'Unknown'")
            .build();

        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            ColumnBuildError::ValidationError(_)
        ));
    }

    #[test]
    fn test_column_builder_foreign_key() {
        let column = ColumnBuilder::new("user_id", ColumnType::Int4)
            .references("users", "id")
            .on_delete("CASCADE")
            .on_update("CASCADE")
            .build()
            .expect("Should build successfully");

        assert_eq!(column.name, "user_id");
        assert!(column.references.is_some());
    }

    #[test]
    fn test_column_builder_inspection() {
        let builder = ColumnBuilder::new("id", ColumnType::Int4)
            .primary_key()
            .comment("Primary key");

        assert!(builder.is_valid());
        assert_eq!(builder.name(), "id");
        assert!(builder.is_primary_key());
        assert!(!builder.is_nullable());

        let summary = builder.summary();
        assert!(summary.contains("column 'id'"));
        assert!(summary.contains("PRIMARY KEY"));
    }
}