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

/// Builder for constructing database indexes
#[derive(Debug, Clone)]
pub struct IndexBuilder {
    name: Option<String>,
    columns: Vec<String>,
    unique: bool,
    // Note: The actual Index struct only supports name, columns, and unique
    // Additional fields are stored in the builder for future schema expansion
    table_name: Option<String>,
    schema: Option<String>,
    index_type: IndexType,
    partial: Option<String>,
    include: Vec<String>,
    storage_parameters: Vec<(String, String)>,
    comment: Option<String>,
}

impl IndexBuilder {
    /// Create a new index builder
    pub fn new() -> Self {
        Self {
            name: None,
            columns: Vec::new(),
            unique: false,
            table_name: None,
            schema: None,
            index_type: IndexType::BTree,
            partial: None,
            include: Vec::new(),
            storage_parameters: Vec::new(),
            comment: None,
        }
    }

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

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

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

    /// Set the table name (mutable reference version for conditional building)
    pub fn set_table(&mut self, table_name: impl Into<String>) {
        self.table_name = Some(table_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 column to the index
    pub fn column(mut self, column: impl Into<String>) -> Self {
        self.columns.push(column.into());
        self
    }

    /// Add a column to the index (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 index
    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 index (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 index type
    pub fn index_type(mut self, index_type: IndexType) -> Self {
        self.index_type = index_type;
        self
    }

    /// Set the index type (mutable reference version for conditional building)
    pub fn set_index_type(&mut self, index_type: IndexType) {
        self.index_type = index_type;
    }

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

    /// Make the index unique (mutable reference version for conditional building)
    pub fn set_unique(&mut self) {
        self.unique = true;
    }

    /// Set a partial index condition
    pub fn partial(mut self, condition: impl Into<String>) -> Self {
        self.partial = Some(condition.into());
        self
    }

    /// Set a partial index condition (mutable reference version for conditional building)
    pub fn set_partial(&mut self, condition: impl Into<String>) {
        self.partial = Some(condition.into());
    }

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

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

    /// Add a storage parameter
    pub fn storage_parameter(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.storage_parameters.push((key.into(), value.into()));
        self
    }

    /// Add a storage parameter (mutable reference version for conditional building)
    pub fn add_storage_parameter(&mut self, key: impl Into<String>, value: impl Into<String>) {
        self.storage_parameters.push((key.into(), value.into()));
    }

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

    /// Set a comment on the index (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 index types
    /// Create a B-tree index
    pub fn btree() -> Self {
        Self::new().index_type(IndexType::BTree)
    }

    /// Create a hash index
    pub fn hash() -> Self {
        Self::new().index_type(IndexType::Hash)
    }

    /// Create a GiST index
    pub fn gist() -> Self {
        Self::new().index_type(IndexType::GIST)
    }

    /// Create a GIN index
    pub fn gin() -> Self {
        Self::new().index_type(IndexType::GIN)
    }

    /// Create a SP-GiST index
    pub fn spgist() -> Self {
        Self::new().index_type(IndexType::SPGIST)
    }

    /// Create a BRIN index
    pub fn brin() -> Self {
        Self::new().index_type(IndexType::BRIN)
    }

    /// Create a unique index
    pub fn unique_index() -> Self {
        Self::new().unique()
    }

    /// Create a partial index
    pub fn partial_index(condition: impl Into<String>) -> Self {
        Self::new().partial(condition)
    }

    /// Create a covering index with included columns
    pub fn covering(
        columns: impl IntoIterator<Item = impl Into<String>>,
        include: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        Self::new().columns(columns).include(include)
    }

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

    /// Get the table name
    pub fn get_table_name(&self) -> Option<&str> {
        self.table_name.as_deref()
    }

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

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

    /// Get the index type
    pub fn get_index_type(&self) -> &IndexType {
        &self.index_type
    }

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

    /// Get the partial condition
    pub fn get_partial(&self) -> Option<&str> {
        self.partial.as_deref()
    }

    /// Get the included columns
    pub fn get_include(&self) -> &[String] {
        &self.include
    }

    /// Get the storage parameters
    pub fn get_storage_parameters(&self) -> &[(String, String)] {
        &self.storage_parameters
    }

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

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

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

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

    /// Check if the index has a table name
    pub fn has_table(&self) -> bool {
        self.table_name.is_some()
    }

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

    /// Check if the index has a partial condition
    pub fn has_partial(&self) -> bool {
        self.partial.is_some()
    }

    /// Check if the index has included columns
    pub fn has_include(&self) -> bool {
        !self.include.is_empty()
    }

    /// Check if the index has storage parameters
    pub fn has_storage_parameters(&self) -> bool {
        !self.storage_parameters.is_empty()
    }

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

impl SchemaBuilder for IndexBuilder {
    type Output = Index;
    type Error = IndexBuildError;

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

        // Build the index
        let index = Index {
            name: self.name.unwrap_or_else(|| "index".to_string()),
            columns: self.columns,
            unique: self.unique,
        };

        Ok(index)
    }
}

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

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

        // Validate that columns are specified
        if self.columns.is_empty() {
            errors.push("Index must specify at least one column".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 index name if provided
        if let Some(ref name) = self.name {
            if name.trim().is_empty() {
                errors.push("Index name cannot be empty".to_string());
            }
        }

        // Validate table name if provided
        if let Some(ref table_name) = self.table_name {
            if table_name.trim().is_empty() {
                errors.push("Table 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());
            }
        }

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

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

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

        // Validate storage parameters
        for (key, value) in &self.storage_parameters {
            if key.trim().is_empty() {
                errors.push("Storage parameter key cannot be empty".to_string());
            }
            if value.trim().is_empty() {
                errors.push("Storage parameter value cannot be empty".to_string());
            }
        }

        errors
    }
}

impl ConditionalBuilder for IndexBuilder {
    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 IndexBuilder {
    fn debug_info(&self) -> String {
        format!(
            "IndexBuilder {{ name: {:?}, table: {:?}, schema: {:?}, columns: {:?}, type: {:?}, unique: {}, partial: {:?}, include: {:?} }}",
            self.name, self.table_name, self.schema, self.columns, self.index_type, self.unique, self.partial, self.include
        )
    }

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

        // Index type and uniqueness
        let type_desc = match self.index_type {
            IndexType::BTree => "B-tree",
            IndexType::Hash => "Hash",
            IndexType::GIST => "GiST",
            IndexType::GIN => "GIN",
            IndexType::SPGIST => "SP-GiST",
            IndexType::BRIN => "BRIN",
        };

        if self.unique {
            parts.push(format!("Unique {} index", type_desc));
        } else {
            parts.push(format!("{} index", type_desc));
        }

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

        // Table and schema
        if let Some(ref table) = self.table_name {
            if let Some(ref schema) = self.schema {
                parts.push(format!("on {}.{}", schema, table));
            } else {
                parts.push(format!("on {}", table));
            }
        }

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

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

        // Included columns
        if !self.include.is_empty() {
            parts.push(format!("including columns: {}", self.include.join(", ")));
        }

        // Storage parameters
        if !self.storage_parameters.is_empty() {
            let params: Vec<String> = self
                .storage_parameters
                .iter()
                .map(|(k, v)| format!("{}={}", k, v))
                .collect();
            parts.push(format!("with storage parameters: {}", params.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::IndexType;

    #[test]
    fn test_btree_index() {
        let index = IndexBuilder::btree()
            .name("idx_users_email")
            .on_table("users")
            .column("email")
            .build()
            .unwrap();

        assert_eq!(index.name, "idx_users_email");
        assert_eq!(index.columns, vec!["email"]);
        assert!(!index.unique);
    }

    #[test]
    fn test_unique_hash_index() {
        let index = IndexBuilder::hash()
            .name("idx_users_id")
            .on_table("users")
            .column("id")
            .unique()
            .build()
            .unwrap();

        assert_eq!(index.name, "idx_users_id");
        assert_eq!(index.columns, vec!["id"]);
        assert!(index.unique);
    }

    #[test]
    fn test_composite_gist_index() {
        let index = IndexBuilder::gist()
            .name("idx_users_location")
            .on_table("users")
            .columns(vec!["latitude", "longitude"])
            .build()
            .unwrap();

        assert_eq!(index.name, "idx_users_location");
        assert_eq!(index.columns, vec!["latitude", "longitude"]);
    }

    #[test]
    fn test_partial_index() {
        let index = IndexBuilder::partial_index("status = 'active'")
            .name("idx_active_users")
            .on_table("users")
            .column("email")
            .build()
            .unwrap();

        assert_eq!(index.name, "idx_active_users");
        assert_eq!(index.columns, vec!["email"]);
    }

    #[test]
    fn test_covering_index() {
        let index = IndexBuilder::covering(vec!["user_id"], vec!["email", "name"])
            .name("idx_posts_user_covering")
            .on_table("posts")
            .build()
            .unwrap();

        assert_eq!(index.name, "idx_posts_user_covering");
        assert_eq!(index.columns, vec!["user_id"]);
    }

    #[test]
    fn test_index_with_storage_parameters() {
        let index = IndexBuilder::btree()
            .name("idx_users_created")
            .on_table("users")
            .column("created_at")
            .storage_parameter("fillfactor", "90")
            .storage_parameter("gin_pending_list_limit", "64")
            .build()
            .unwrap();

        assert_eq!(index.name, "idx_users_created");
    }

    #[test]
    fn test_index_with_schema() {
        let index = IndexBuilder::btree()
            .name("idx_users_email")
            .in_schema("public")
            .on_table("users")
            .column("email")
            .build()
            .unwrap();

        assert_eq!(index.name, "idx_users_email");
    }

    #[test]
    fn test_convenience_methods() {
        let btree_index = IndexBuilder::btree()
            .name("idx_btree")
            .column("col1")
            .build()
            .unwrap();

        let gin_index = IndexBuilder::gin()
            .name("idx_gin")
            .column("col2")
            .build()
            .unwrap();

        let unique_index = IndexBuilder::unique_index()
            .name("idx_unique")
            .column("col3")
            .build()
            .unwrap();

        assert!(unique_index.unique);
    }

    #[test]
    fn test_validation_errors() {
        // No columns
        let result = IndexBuilder::new().build();
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            IndexBuildError::ValidationError(_)
        ));

        // Empty column name
        let result = IndexBuilder::new().column("").build();
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            IndexBuildError::ValidationError(_)
        ));
    }

    #[test]
    fn test_conditional_builder() {
        let condition = true;
        let index = IndexBuilder::btree()
            .when(condition, |i| {
                i.set_name("idx_when_true");
                i.add_column("id");
            })
            .on_table("users")
            .build()
            .unwrap();

        assert_eq!(index.name, "idx_when_true");
        assert_eq!(index.columns, vec!["id"]);
    }

    #[test]
    fn test_inspection_methods() {
        let builder = IndexBuilder::btree()
            .name("idx_test")
            .on_table("users")
            .columns(vec!["id", "email"]);

        assert_eq!(builder.get_name(), Some("idx_test"));
        assert_eq!(builder.get_table_name(), Some("users"));
        assert_eq!(builder.get_columns(), &["id", "email"]);
        assert_eq!(builder.column_count(), 2);
        assert!(builder.has_column("id"));
        assert!(!builder.has_column("nonexistent"));
        assert!(builder.has_name());
        assert!(builder.has_table());
        assert!(!builder.has_schema());
        assert!(!builder.has_partial());
        assert!(!builder.has_include());
        assert!(!builder.has_storage_parameters());
        assert!(!builder.has_comment());
    }

    #[test]
    fn test_debug_info_and_summary() {
        let builder = IndexBuilder::btree()
            .name("idx_email")
            .on_table("users")
            .column("email")
            .unique()
            .comment("Ensure fast email lookups");

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

        assert!(debug_info.contains("IndexBuilder"));
        assert!(debug_info.contains("idx_email"));
        assert!(debug_info.contains("users"));
        assert!(debug_info.contains("email"));

        assert!(summary.contains("Unique B-tree index"));
        assert!(summary.contains("on columns: email"));
        assert!(summary.contains("on users"));
        assert!(summary.contains("named 'idx_email'"));
        assert!(summary.contains("with comment: Ensure fast email lookups"));
    }
}