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

/// Builder for constructing database composite types
#[derive(Debug, Clone)]
pub struct CompositeTypeBuilder {
    name: Option<String>,
    schema: Option<String>,
    fields: Vec<CompositeField>,
    comment: Option<String>,
}

impl CompositeTypeBuilder {
    /// Create a new composite type builder
    pub fn new() -> Self {
        Self {
            name: None,
            schema: None,
            fields: Vec::new(),
            comment: None,
        }
    }

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

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

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

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

    /// Add a field to the composite type
    pub fn field(mut self, name: impl Into<String>, field_type: impl Into<String>) -> Self {
        let field = CompositeField {
            name: name.into(),
            field_type: field_type.into(),
            nullable: true, // Default to nullable
        };
        self.fields.push(field);
        self
    }

    /// Add a field to the composite type (mutable reference version for conditional building)
    pub fn add_field(&mut self, name: impl Into<String>, field_type: impl Into<String>) {
        let field = CompositeField {
            name: name.into(),
            field_type: field_type.into(),
            nullable: true, // Default to nullable
        };
        self.fields.push(field);
    }

    /// Add multiple fields to the composite type
    pub fn fields(
        mut self,
        fields: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>,
    ) -> Self {
        for (name, field_type) in fields {
            let field = CompositeField {
                name: name.into(),
                field_type: field_type.into(),
                nullable: true, // Default to nullable
            };
            self.fields.push(field);
        }
        self
    }

    /// Add multiple fields to the composite type (mutable reference version for conditional building)
    pub fn add_fields(
        &mut self,
        fields: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>,
    ) {
        for (name, field_type) in fields {
            let field = CompositeField {
                name: name.into(),
                field_type: field_type.into(),
                nullable: true, // Default to nullable
            };
            self.fields.push(field);
        }
    }

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

    /// Set a comment on the composite type (mutable reference version for conditional building)
    pub fn set_comment(&mut self, comment: impl Into<String>) {
        self.comment = Some(comment.into());
    }

    // Convenience methods for specific composite type patterns
    /// Create a point type (x, y coordinates)
    pub fn point() -> Self {
        Self::new()
            .field("x", "DOUBLE PRECISION")
            .field("y", "DOUBLE PRECISION")
    }

    /// Create a rectangle type (x1, y1, x2, y2 coordinates)
    pub fn rectangle() -> Self {
        Self::new()
            .field("x1", "DOUBLE PRECISION")
            .field("y1", "DOUBLE PRECISION")
            .field("x2", "DOUBLE PRECISION")
            .field("y2", "DOUBLE PRECISION")
    }

    /// Create a circle type (center_x, center_y, radius)
    pub fn circle() -> Self {
        Self::new()
            .field("center_x", "DOUBLE PRECISION")
            .field("center_y", "DOUBLE PRECISION")
            .field("radius", "DOUBLE PRECISION")
    }

    /// Create a line type (point1_x, point1_y, point2_x, point2_y)
    pub fn line() -> Self {
        Self::new()
            .field("point1_x", "DOUBLE PRECISION")
            .field("point1_y", "DOUBLE PRECISION")
            .field("point2_x", "DOUBLE PRECISION")
            .field("point2_y", "DOUBLE PRECISION")
    }

    /// Create a polygon type (points array)
    pub fn polygon() -> Self {
        Self::new().field("points", "JSONB")
    }

    /// Create an address type
    pub fn address() -> Self {
        Self::new()
            .field("street", "VARCHAR(255)")
            .field("city", "VARCHAR(100)")
            .field("state", "VARCHAR(50)")
            .field("postal_code", "VARCHAR(20)")
            .field("country", "VARCHAR(100)")
    }

    /// Create a contact info type
    pub fn contact_info() -> Self {
        Self::new()
            .field("email", "VARCHAR(255)")
            .field("phone", "VARCHAR(20)")
            .field("website", "VARCHAR(255)")
    }

    /// Create a money type (amount, currency)
    pub fn money() -> Self {
        Self::new()
            .field("amount", "NUMERIC(19,4)")
            .field("currency", "VARCHAR(3)")
    }

    /// Create a date range type (start_date, end_date)
    pub fn date_range() -> Self {
        Self::new()
            .field("start_date", "DATE")
            .field("end_date", "DATE")
    }

    /// Create a time range type (start_time, end_time)
    pub fn time_range() -> Self {
        Self::new()
            .field("start_time", "TIME")
            .field("end_time", "TIME")
    }

    /// Create a timestamp range type (start_timestamp, end_timestamp)
    pub fn timestamp_range() -> Self {
        Self::new()
            .field("start_timestamp", "TIMESTAMPTZ")
            .field("end_timestamp", "TIMESTAMPTZ")
    }

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

    /// Get the schema name
    pub fn get_schema(&self) -> Option<&str> {
        self.schema.as_deref()
    }

    /// Get the fields in the composite type
    pub fn get_fields(&self) -> &[CompositeField] {
        &self.fields
    }

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

    /// Get the number of fields in the composite type
    pub fn field_count(&self) -> usize {
        self.fields.len()
    }

    /// Check if the composite type has a specific field
    pub fn has_field(&self, field_name: &str) -> bool {
        self.fields.iter().any(|f| f.name == field_name)
    }

    /// Get a specific field by name
    pub fn get_field(&self, field_name: &str) -> Option<&CompositeField> {
        self.fields.iter().find(|f| f.name == field_name)
    }

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

    /// Check if the composite type has a schema
    pub fn has_schema(&self) -> bool {
        self.schema.is_some()
    }

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

    /// Check if the composite type has fields
    pub fn has_fields(&self) -> bool {
        !self.fields.is_empty()
    }
}

impl SchemaBuilder for CompositeTypeBuilder {
    type Output = CompositeType;
    type Error = CompositeTypeBuildError;

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

        // Build the composite type
        let composite_type = CompositeType {
            name: self.name.unwrap_or_else(|| "composite_type".to_string()),
            fields: self.fields,
            schema: self.schema,
        };

        Ok(composite_type)
    }
}

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

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

        // Validate that fields are specified
        if self.fields.is_empty() {
            errors.push("Composite type must specify at least one field".to_string());
        }

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

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

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

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

        errors
    }
}

impl ConditionalBuilder for CompositeTypeBuilder {
    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 CompositeTypeBuilder {
    fn debug_info(&self) -> String {
        format!(
            "CompositeTypeBuilder {{ name: {:?}, schema: {:?}, fields: {:?} }}",
            self.name, self.schema, self.fields
        )
    }

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

        parts.push("Composite type".to_string());

        // Name and schema
        if let Some(ref name) = self.name {
            if let Some(ref schema) = self.schema {
                parts.push(format!("{}.{}", schema, name));
            } else {
                parts.push(format!("'{}'", name));
            }
        }

        // Fields
        if !self.fields.is_empty() {
            let field_descriptions: Vec<String> = self
                .fields
                .iter()
                .map(|f| format!("{}: {:?}", f.name, f.field_type))
                .collect();
            parts.push(format!("with fields: {}", field_descriptions.join(", ")));
        }

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

        parts.join(", ")
    }
}

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

    #[test]
    fn test_basic_composite_type() {
        let composite_type = CompositeTypeBuilder::new()
            .name("point_2d")
            .field("x", "DOUBLE PRECISION")
            .field("y", "DOUBLE PRECISION")
            .build()
            .unwrap();

        assert_eq!(composite_type.name, "point_2d");
        assert_eq!(composite_type.fields.len(), 2);
        assert_eq!(composite_type.fields[0].name, "x");
        assert_eq!(composite_type.fields[0].field_type, "DOUBLE PRECISION");
        assert_eq!(composite_type.fields[1].name, "y");
        assert_eq!(composite_type.fields[1].field_type, "DOUBLE PRECISION");
    }

    #[test]
    fn test_composite_type_with_schema() {
        let composite_type = CompositeTypeBuilder::new()
            .name("address")
            .in_schema("public")
            .field("street", "TEXT")
            .field("city", "TEXT")
            .build()
            .unwrap();

        assert_eq!(composite_type.name, "address");
        assert_eq!(composite_type.schema, Some("public".to_string()));
        assert_eq!(composite_type.fields.len(), 2);
    }

    #[test]
    fn test_convenience_methods() {
        let point_type = CompositeTypeBuilder::point()
            .name("point_2d")
            .build()
            .unwrap();

        let rectangle_type = CompositeTypeBuilder::rectangle()
            .name("rectangle_2d")
            .build()
            .unwrap();

        let address_type = CompositeTypeBuilder::address()
            .name("address_info")
            .build()
            .unwrap();

        assert_eq!(point_type.name, "point_2d");
        assert_eq!(point_type.fields.len(), 2);
        assert_eq!(rectangle_type.name, "rectangle_2d");
        assert_eq!(rectangle_type.fields.len(), 4);
        assert_eq!(address_type.name, "address_info");
        assert_eq!(address_type.fields.len(), 5);
    }

    #[test]
    fn test_composite_type_with_multiple_fields() {
        let composite_type = CompositeTypeBuilder::new()
            .name("user_profile")
            .fields(vec![
                ("id", "INTEGER"),
                ("name", "TEXT"),
                ("email", "VARCHAR(255)"),
                ("age", "INTEGER"),
                ("is_active", "BOOLEAN"),
            ])
            .build()
            .unwrap();

        assert_eq!(composite_type.name, "user_profile");
        assert_eq!(composite_type.fields.len(), 5);
        assert_eq!(composite_type.fields[0].name, "id");
        assert_eq!(composite_type.fields[0].field_type, "INTEGER");
        assert_eq!(composite_type.fields[4].name, "is_active");
        assert_eq!(composite_type.fields[4].field_type, "BOOLEAN");
    }

    #[test]
    fn test_composite_type_with_comment() {
        let composite_type = CompositeTypeBuilder::new()
            .name("coordinates")
            .field("latitude", "DOUBLE PRECISION")
            .field("longitude", "DOUBLE PRECISION")
            .comment("Geographic coordinates in decimal degrees")
            .build()
            .unwrap();

        assert_eq!(composite_type.name, "coordinates");
        // Note: comment is not stored in the actual CompositeType struct
    }

    #[test]
    fn test_validation_errors() {
        // No fields
        let result = CompositeTypeBuilder::new().name("test").build();
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            CompositeTypeBuildError::ValidationError(_)
        ));

        // Empty field name
        let result = CompositeTypeBuilder::new()
            .name("test")
            .field("", "TEXT")
            .build();
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            CompositeTypeBuildError::ValidationError(_)
        ));
    }

    #[test]
    fn test_conditional_builder() {
        let condition = true;
        let composite_type = CompositeTypeBuilder::new()
            .when(condition, |c| {
                c.set_name("point_when_true");
                c.add_field("x", "DOUBLE PRECISION");
                c.add_field("y", "DOUBLE PRECISION");
            })
            .build()
            .unwrap();

        assert_eq!(composite_type.name, "point_when_true");
        assert_eq!(composite_type.fields.len(), 2);
    }

    #[test]
    fn test_inspection_methods() {
        let builder = CompositeTypeBuilder::new()
            .name("test_type")
            .in_schema("public")
            .fields(vec![("field1", "TEXT"), ("field2", "INTEGER")]);

        assert_eq!(builder.get_name(), Some("test_type"));
        assert_eq!(builder.get_schema(), Some("public"));
        assert_eq!(builder.get_fields().len(), 2);
        assert_eq!(builder.field_count(), 2);
        assert!(builder.has_field("field1"));
        assert!(!builder.has_field("nonexistent"));
        assert!(builder.has_name());
        assert!(builder.has_schema());
        assert!(builder.has_fields());
        assert!(!builder.has_comment());

        let field = builder.get_field("field1");
        assert!(field.is_some());
        assert_eq!(field.unwrap().name, "field1");
        assert_eq!(field.unwrap().field_type, "TEXT");
    }

    #[test]
    fn test_debug_info_and_summary() {
        let builder = CompositeTypeBuilder::new()
            .name("point_3d")
            .in_schema("geometry")
            .fields(vec![
                ("x", "DOUBLE PRECISION"),
                ("y", "DOUBLE PRECISION"),
                ("z", "DOUBLE PRECISION"),
            ])
            .comment("3D point coordinates");

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

        assert!(debug_info.contains("CompositeTypeBuilder"));
        assert!(debug_info.contains("point_3d"));
        assert!(debug_info.contains("geometry"));

        assert!(summary.contains("Composite type"));
        assert!(summary.contains("geometry.point_3d"));
        assert!(summary.contains("with fields: x: \"DOUBLE PRECISION\", y: \"DOUBLE PRECISION\", z: \"DOUBLE PRECISION\""));
        assert!(summary.contains("with comment: 3D point coordinates"));
    }

    #[test]
    fn test_geometric_types() {
        let point = CompositeTypeBuilder::point()
            .name("point_2d")
            .build()
            .unwrap();

        let circle = CompositeTypeBuilder::circle()
            .name("circle_2d")
            .build()
            .unwrap();

        let line = CompositeTypeBuilder::line()
            .name("line_2d")
            .build()
            .unwrap();

        assert_eq!(point.fields.len(), 2);
        assert_eq!(circle.fields.len(), 3);
        assert_eq!(line.fields.len(), 4);
    }

    #[test]
    fn test_business_types() {
        let money = CompositeTypeBuilder::money()
            .name("currency_amount")
            .build()
            .unwrap();

        let date_range = CompositeTypeBuilder::date_range()
            .name("period")
            .build()
            .unwrap();

        let contact = CompositeTypeBuilder::contact_info()
            .name("contact_details")
            .build()
            .unwrap();

        assert_eq!(money.fields.len(), 2);
        assert_eq!(date_range.fields.len(), 2);
        assert_eq!(contact.fields.len(), 3);
    }
}