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
use crate::builders::traits::{
    ConditionalBuilder, InspectableBuilder, SchemaBuilder, ValidatableBuilder,
};
use crate::builders::validation::ConstraintBuildError;
use crate::schema::{Constraint, ConstraintType};
use std::collections::HashSet;

/// Builder for constructing table-level constraints
#[derive(Debug, Clone)]
pub struct ConstraintBuilder {
    name: Option<String>,
    constraint_type: ConstraintType,
    columns: Vec<String>,
    expression: Option<String>,
    deferrable: bool,
    initially_deferred: bool,
    comment: Option<String>,
}

impl ConstraintBuilder {
    /// Create a new constraint builder
    pub fn new(constraint_type: ConstraintType) -> Self {
        Self {
            name: None,
            constraint_type,
            columns: Vec::new(),
            expression: None,
            deferrable: false,
            initially_deferred: false,
            comment: None,
        }
    }

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

    /// Set the constraint name (mutable reference version for conditional building)
    pub fn set_name(&mut self, name: impl Into<String>) {
        self.name = Some(name.into());
    }

    /// Add a column to the constraint
    pub fn column(mut self, column: impl Into<String>) -> Self {
        self.columns.push(column.into());
        self
    }

    /// Add a column to the constraint (mutable reference version for conditional building)
    pub fn add_column(&mut self, column: impl Into<String>) {
        self.columns.push(column.into());
    }

    /// Add multiple columns to the constraint
    pub fn columns(mut self, columns: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.columns.extend(columns.into_iter().map(|c| c.into()));
        self
    }

    /// Add multiple columns to the constraint (mutable reference version for conditional building)
    pub fn add_columns(&mut self, columns: impl IntoIterator<Item = impl Into<String>>) {
        self.columns.extend(columns.into_iter().map(|c| c.into()));
    }

    /// Set the constraint expression (for check constraints)
    pub fn expression(mut self, expression: impl Into<String>) -> Self {
        self.expression = Some(expression.into());
        self
    }

    /// Make the constraint deferrable
    pub fn deferrable(mut self) -> Self {
        self.deferrable = true;
        self
    }

    /// Make the constraint initially deferred
    pub fn initially_deferred(mut self) -> Self {
        self.initially_deferred = true;
        self
    }

    /// Set a comment on the constraint
    pub fn comment(mut self, comment: impl Into<String>) -> Self {
        self.comment = Some(comment.into());
        self
    }

    // Convenience methods for specific constraint types
    /// Create a primary key constraint
    pub fn primary_key() -> Self {
        Self::new(ConstraintType::Unique(vec![]))
    }

    /// Create a unique constraint
    pub fn unique() -> Self {
        Self::new(ConstraintType::Unique(vec![]))
    }

    /// Create a check constraint
    pub fn check(expression: impl Into<String>) -> Self {
        let expr = expression.into();
        Self::new(ConstraintType::Check(expr.clone())).expression(expr)
    }

    /// Create a foreign key constraint
    pub fn foreign_key(
        referenced_table: impl Into<String>,
        referenced_column: impl Into<String>,
    ) -> Self {
        let expr = format!(
            "REFERENCES {}({})",
            referenced_table.into(),
            referenced_column.into()
        );
        Self::new(ConstraintType::Check(expr.clone())).expression(expr)
    }

    /// Create a not null constraint
    pub fn not_null() -> Self {
        let expr = "NOT NULL".to_string();
        Self::new(ConstraintType::Check(expr.clone())).expression(expr)
    }

    /// Create a default constraint
    pub fn default(default_value: impl Into<String>) -> Self {
        let expr = format!("DEFAULT {}", default_value.into());
        Self::new(ConstraintType::Check(expr.clone())).expression(expr)
    }

    /// Create an exclusion constraint
    pub fn exclusion() -> Self {
        let expr = "EXCLUDE".to_string();
        Self::new(ConstraintType::Check(expr.clone())).expression(expr)
    }

    /// Create an exclusion constraint with a specific expression
    pub fn exclusion_with_expression(expression: impl Into<String>) -> Self {
        let expr = expression.into();
        Self::new(ConstraintType::Check(expr.clone())).expression(expr)
    }

    /// Create a unique constraint with specific columns
    pub fn unique_on(columns: impl IntoIterator<Item = impl Into<String>>) -> Self {
        let cols: Vec<String> = columns.into_iter().map(|c| c.into()).collect();
        Self::new(ConstraintType::Unique(cols.clone())).columns(cols)
    }

    /// Create a primary key constraint with specific columns
    pub fn primary_key_on(columns: impl IntoIterator<Item = impl Into<String>>) -> Self {
        let cols: Vec<String> = columns.into_iter().map(|c| c.into()).collect();
        Self::new(ConstraintType::Unique(cols.clone())).columns(cols)
    }

    /// Create a check constraint with a specific expression
    pub fn check_on(expression: impl Into<String>) -> Self {
        Self::check(expression)
    }

    /// Create a foreign key constraint with specific columns
    pub fn foreign_key_on(
        columns: impl IntoIterator<Item = impl Into<String>>,
        referenced_table: impl Into<String>,
        referenced_columns: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        let ref_cols: Vec<String> = referenced_columns.into_iter().map(|c| c.into()).collect();
        let ref_expr = format!(
            "REFERENCES {}({})",
            referenced_table.into(),
            ref_cols.join(", ")
        );

        Self::new(ConstraintType::Check(ref_expr.clone()))
            .expression(ref_expr)
            .columns(columns)
    }

    // Inspection methods
    /// Get the constraint name
    pub fn get_name(&self) -> Option<&str> {
        self.name.as_deref()
    }

    /// Get the constraint type
    pub fn get_constraint_type(&self) -> &ConstraintType {
        &self.constraint_type
    }

    /// Get the columns involved in the constraint
    pub fn get_columns(&self) -> &[String] {
        &self.columns
    }

    /// Get the constraint expression
    pub fn get_expression(&self) -> Option<&str> {
        self.expression.as_deref()
    }

    /// Check if the constraint is deferrable
    pub fn is_deferrable(&self) -> bool {
        self.deferrable
    }

    /// Check if the constraint is initially deferred
    pub fn is_initially_deferred(&self) -> bool {
        self.initially_deferred
    }

    /// Get the constraint comment
    pub fn get_comment(&self) -> Option<&str> {
        self.comment.as_deref()
    }

    /// Get the number of columns in the constraint
    pub fn column_count(&self) -> usize {
        self.columns.len()
    }

    /// Check if the constraint has a specific column
    pub fn has_column(&self, column_name: &str) -> bool {
        self.columns.iter().any(|c| c == column_name)
    }

    /// Check if the constraint has an expression
    pub fn has_expression(&self) -> bool {
        self.expression.is_some()
    }

    /// Check if the constraint has a name
    pub fn has_name(&self) -> bool {
        self.name.is_some()
    }

    /// Check if the constraint has a comment
    pub fn has_comment(&self) -> bool {
        self.comment.is_some()
    }
}

impl SchemaBuilder for ConstraintBuilder {
    type Output = Constraint;
    type Error = ConstraintBuildError;

    fn build(self) -> Result<Self::Output, Self::Error> {
        // Validate the constraint before building
        if !self.is_valid() {
            let errors = self.validation_errors();
            return Err(ConstraintBuildError::ValidationError(errors.join("; ")));
        }

        // Build the constraint based on type
        let constraint = match &self.constraint_type {
            ConstraintType::Unique(_) => {
                if self.columns.is_empty() {
                    return Err(ConstraintBuildError::ValidationError(
                        "Unique constraint must specify columns".to_string(),
                    ));
                }
                Constraint {
                    name: self.name.unwrap_or_else(|| "constraint".to_string()),
                    constraint_type: ConstraintType::Unique(self.columns),
                }
            }
            ConstraintType::Check(_) => {
                let expression = self.expression.ok_or_else(|| {
                    ConstraintBuildError::ValidationError(
                        "Check constraint must have an expression".to_string(),
                    )
                })?;
                Constraint {
                    name: self.name.unwrap_or_else(|| "constraint".to_string()),
                    constraint_type: ConstraintType::Check(expression),
                }
            }
        };

        Ok(constraint)
    }
}

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

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

        // Validate constraint type specific requirements
        match &self.constraint_type {
            ConstraintType::Unique(_) => {
                if self.columns.is_empty() {
                    errors.push("Constraint must specify at least one column".to_string());
                }
            }
            ConstraintType::Check(_) => {
                if self.expression.is_none() {
                    errors.push("Check constraint must have an expression".to_string());
                }
            }
        }

        // Validate column names are not empty
        for (i, column) in self.columns.iter().enumerate() {
            if column.trim().is_empty() {
                errors.push(format!("Column {} at index {} cannot be empty", i, i));
            }
        }

        // Check for duplicate column names
        let mut seen_columns = HashSet::new();
        for column in &self.columns {
            if !seen_columns.insert(column) {
                errors.push(format!("Duplicate column name: {}", column));
            }
        }

        // Validate constraint name if provided
        if let Some(ref name) = self.name {
            if name.trim().is_empty() {
                errors.push("Constraint name cannot be empty".to_string());
            }
        }

        // Validate expression if provided
        if let Some(ref expression) = self.expression {
            if expression.trim().is_empty() {
                errors.push("Constraint expression cannot be empty".to_string());
            }
        }

        errors
    }
}

impl ConditionalBuilder for ConstraintBuilder {
    fn when<F>(mut self, condition: bool, config_fn: F) -> Self
    where
        F: FnOnce(&mut Self),
        Self: Sized,
    {
        if condition {
            config_fn(&mut self);
        }
        self
    }
}

impl InspectableBuilder for ConstraintBuilder {
    fn debug_info(&self) -> String {
        format!(
            "ConstraintBuilder {{ type: {:?}, columns: {:?}, expression: {:?}, name: {:?} }}",
            self.constraint_type, self.columns, self.expression, self.name
        )
    }

    fn summary(&self) -> String {
        let mut parts = Vec::new();

        // Determine the constraint type description
        let constraint_desc = match &self.constraint_type {
            ConstraintType::Unique(_) => "Unique constraint",
            ConstraintType::Check(_) => "Check constraint",
        };
        parts.push(constraint_desc.to_string());

        if !self.columns.is_empty() {
            parts.push(format!("on columns: {}", self.columns.join(", ")));
        }

        if let Some(ref name) = self.name {
            parts.push(format!("named '{}'", name));
        }

        if let Some(ref expr) = self.expression {
            parts.push(format!("with expression: {}", expr));
        }

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

        if self.initially_deferred {
            parts.push("initially deferred".to_string());
        }

        if let Some(ref comment) = self.comment {
            parts.push(format!("with comment: {}", comment));
        }

        parts.join(", ")
    }
}

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

    #[test]
    fn test_primary_key_constraint() {
        let constraint = ConstraintBuilder::primary_key()
            .name("pk_users")
            .columns(vec!["id"])
            .build()
            .unwrap();

        assert_eq!(
            constraint.constraint_type,
            ConstraintType::Unique(vec!["id".to_string()])
        );
        assert_eq!(constraint.name, "pk_users");
    }

    #[test]
    fn test_unique_constraint() {
        let constraint = ConstraintBuilder::unique()
            .name("uq_users_email")
            .columns(vec!["email"])
            .build()
            .unwrap();

        assert_eq!(
            constraint.constraint_type,
            ConstraintType::Unique(vec!["email".to_string()])
        );
        assert_eq!(constraint.name, "uq_users_email");
    }

    #[test]
    fn test_check_constraint() {
        let constraint = ConstraintBuilder::check("age > 0")
            .name("chk_users_age")
            .build()
            .unwrap();

        assert_eq!(
            constraint.constraint_type,
            ConstraintType::Check("age > 0".to_string())
        );
        assert_eq!(constraint.name, "chk_users_age");
    }

    #[test]
    fn test_foreign_key_constraint() {
        let constraint = ConstraintBuilder::foreign_key("users", "id")
            .name("fk_posts_user_id")
            .columns(vec!["user_id"])
            .build()
            .unwrap();

        assert!(format!("{:?}", constraint.constraint_type).contains("REFERENCES users(id)"));
        assert_eq!(constraint.name, "fk_posts_user_id");
    }

    #[test]
    fn test_not_null_constraint() {
        let constraint = ConstraintBuilder::not_null()
            .column("email")
            .build()
            .unwrap();

        assert_eq!(
            constraint.constraint_type,
            ConstraintType::Check("NOT NULL".to_string())
        );
        assert_eq!(constraint.name, "constraint");
    }

    #[test]
    fn test_default_constraint() {
        let constraint = ConstraintBuilder::default("'unknown'")
            .column("status")
            .build()
            .unwrap();

        assert_eq!(
            constraint.constraint_type,
            ConstraintType::Check("DEFAULT 'unknown'".to_string())
        );
        assert_eq!(constraint.name, "constraint");
    }

    #[test]
    fn test_exclusion_constraint() {
        let constraint =
            ConstraintBuilder::exclusion_with_expression("email WITH =, username WITH =")
                .name("excl_users_email_username")
                .columns(vec!["email", "username"])
                .build()
                .unwrap();

        assert_eq!(
            constraint.constraint_type,
            ConstraintType::Check("email WITH =, username WITH =".to_string())
        );
        assert_eq!(constraint.name, "excl_users_email_username");
    }

    #[test]
    fn test_convenience_methods() {
        let pk_constraint = ConstraintBuilder::primary_key_on(vec!["id", "tenant_id"])
            .name("pk_composite")
            .build()
            .unwrap();

        let unique_constraint = ConstraintBuilder::unique_on(vec!["email", "tenant_id"])
            .name("uq_email_tenant")
            .build()
            .unwrap();

        let fk_constraint = ConstraintBuilder::foreign_key_on(
            vec!["user_id", "tenant_id"],
            "users",
            vec!["id", "tenant_id"],
        )
        .name("fk_composite")
        .build()
        .unwrap();

        assert_eq!(
            pk_constraint.constraint_type,
            ConstraintType::Unique(vec!["id".to_string(), "tenant_id".to_string()])
        );
        assert_eq!(pk_constraint.name, "pk_composite");

        assert_eq!(
            unique_constraint.constraint_type,
            ConstraintType::Unique(vec!["email".to_string(), "tenant_id".to_string()])
        );
        assert_eq!(unique_constraint.name, "uq_email_tenant");

        assert!(format!("{:?}", fk_constraint.constraint_type)
            .contains("REFERENCES users(id, tenant_id)"));
        assert_eq!(fk_constraint.name, "fk_composite");
    }

    #[test]
    fn test_validation_errors() {
        // No columns for unique constraint
        let result = ConstraintBuilder::unique().build();
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            ConstraintBuildError::ValidationError(_)
        ));

        // No expression for check constraint
        let result = ConstraintBuilder::check("").build();
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            ConstraintBuildError::ValidationError(_)
        ));
    }

    #[test]
    fn test_conditional_builder() {
        let condition = true;
        let constraint = ConstraintBuilder::primary_key()
            .when(condition, |c| {
                c.set_name("pk_when_true");
            })
            .column("id")
            .build()
            .unwrap();

        assert_eq!(constraint.name, "pk_when_true");
    }

    #[test]
    fn test_inspection_methods() {
        let builder = ConstraintBuilder::primary_key()
            .name("pk_test")
            .columns(vec!["id", "tenant_id"]);

        assert_eq!(builder.get_name(), Some("pk_test"));
        assert_eq!(
            builder.get_constraint_type(),
            &ConstraintType::Unique(vec![])
        );
        assert_eq!(builder.get_columns(), &["id", "tenant_id"]);
        assert_eq!(builder.column_count(), 2);
        assert!(builder.has_column("id"));
        assert!(!builder.has_column("nonexistent"));
        assert!(builder.has_name());
        assert!(!builder.has_expression());
        assert!(!builder.has_comment());
    }

    #[test]
    fn test_debug_info_and_summary() {
        let builder = ConstraintBuilder::unique()
            .name("uq_email")
            .column("email")
            .comment("Ensure unique emails");

        let debug_info = builder.debug_info();
        let summary = builder.summary();

        assert!(debug_info.contains("ConstraintBuilder"));
        assert!(debug_info.contains("Unique"));
        assert!(debug_info.contains("email"));

        assert!(summary.contains("Unique constraint"));
        assert!(summary.contains("on columns: email"));
        assert!(summary.contains("named 'uq_email'"));
        assert!(summary.contains("with comment: Ensure unique emails"));
    }
}