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
//! TableBuilder for Ignis-DB
//!
//! This module provides a fluent builder API for constructing database tables
//! with comprehensive validation and configuration options.

use crate::builders::column::ColumnBuilder;
use crate::builders::traits::{
    ConditionalBuilder, InspectableBuilder, SchemaBuilder, ValidatableBuilder,
};
use crate::builders::validation::TableBuildError;
use crate::schema::{Column, Table};
use std::collections::HashMap;

/// Builder for creating database tables
///
/// This builder provides a fluent, chainable API for constructing tables
/// with comprehensive validation and configuration options.
///
/// # Examples
///
/// ```rust
/// use ignis_db::builders::{TableBuilder, ColumnBuilder, table};
/// use ignis_db::schema::ColumnType;
///
/// // Basic table
/// let users_table = TableBuilder::new("users")
///     .column(ColumnBuilder::new("id", ColumnType::Int4).primary_key())
///     .column(ColumnBuilder::new("email", ColumnType::Varchar(Some(255))).unique())
///     .build()?;
///
/// // Advanced table with constraints and indexes
/// let posts_table = TableBuilder::new("posts")
///     .schema("blog")
///     .column(ColumnBuilder::new("id", ColumnType::Int4).primary_key())
///     .column(ColumnBuilder::new("user_id", ColumnType::Int4).not_null())
///     .column(ColumnBuilder::new("title", ColumnType::Varchar(Some(200))).not_null())
///     .column(ColumnBuilder::new("content", ColumnType::Text))
///     .column(ColumnBuilder::new("published", ColumnType::Bool).default("false"))
///     .column(ColumnBuilder::new("created_at", ColumnType::Timestamptz).default("NOW()"))
///     .comment("Blog posts table")
///     .build()?;
///
/// // Using convenience function
/// let simple_table = table("simple")
///     .column(ColumnBuilder::new("id", ColumnType::Int4).primary_key())
///     .build()?;
/// ```
#[derive(Debug, Clone)]
pub struct TableBuilder {
    name: String,
    schema: Option<String>,
    columns: Vec<ColumnBuilder>,
    comment: Option<String>,
    storage_parameters: HashMap<String, String>,
    inherits_from: Vec<String>,
    partition_by: Option<PartitionStrategy>,
    rls_enabled: bool,
    policies: Vec<crate::schema::Policy>,
}

/// Partitioning strategy for tables
#[derive(Debug, Clone)]
pub enum PartitionStrategy {
    Range(Vec<String>),
    List(Vec<String>),
    Hash(Vec<String>),
}

impl TableBuilder {
    /// Create a new table builder
    ///
    /// # Parameters
    ///
    /// - `name`: The name of the table (can be schema-qualified like "auth.users")
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ignis_db::builders::TableBuilder;
    ///
    /// let table = TableBuilder::new("users");           // Simple table name
    /// let table = TableBuilder::new("auth.users");     // Schema-qualified name
    /// ```
    pub fn new(name: impl Into<String>) -> Self {
        let full_name = name.into();

        // Check if the name is schema-qualified (contains a dot)
        if let Some(dot_pos) = full_name.find('.') {
            let schema_name = &full_name[..dot_pos];
            let table_name = &full_name[dot_pos + 1..];

            Self {
                name: table_name.to_string(),
                schema: Some(schema_name.to_string()),
                columns: Vec::new(),
                comment: None,
                storage_parameters: HashMap::new(),
                inherits_from: Vec::new(),
                partition_by: None,
                rls_enabled: false,
                policies: Vec::new(),
            }
        } else {
            Self {
                name: full_name,
                schema: None,
                columns: Vec::new(),
                comment: None,
                storage_parameters: HashMap::new(),
                inherits_from: Vec::new(),
                partition_by: None,
                rls_enabled: false,
                policies: Vec::new(),
            }
        }
    }

    /// Set the schema for the table
    ///
    /// # Parameters
    ///
    /// - `schema`: The schema name
    ///
    /// # Examples
    ///
    /// ```rust
    /// let table = TableBuilder::new("users")
    ///     .schema("public")
    ///     .build()?;
    /// ```
    pub fn schema(mut self, schema: impl Into<String>) -> Self {
        self.schema = Some(schema.into());
        self
    }

    /// Add a column to the table
    ///
    /// # Parameters
    ///
    /// - `column`: The column builder to add
    ///
    /// # Examples
    ///
    /// ```rust
    /// let table = TableBuilder::new("users")
    ///     .column(ColumnBuilder::new("id", ColumnType::Int4).primary_key())
    ///     .column(ColumnBuilder::new("email", ColumnType::Varchar(Some(255))))
    ///     .build()?;
    /// ```
    pub fn column(mut self, column: ColumnBuilder) -> Self {
        self.columns.push(column);
        self
    }

    /// Add a column with a simple string definition (convenience method)
    ///
    /// # Parameters
    ///
    /// - `name`: The column name
    /// - `definition`: The column definition (e.g., "UUID PRIMARY KEY DEFAULT gen_random_uuid()")
    ///
    /// # Examples
    ///
    /// ```rust
    /// let table = TableBuilder::new("users")
    ///     .add_column("id", "UUID PRIMARY KEY DEFAULT gen_random_uuid()")
    ///     .add_column("email", "VARCHAR(255) UNIQUE NOT NULL")
    ///     .add_column("created_at", "TIMESTAMPTZ DEFAULT NOW()")
    ///     .build()?;
    /// ```
    pub fn add_column(mut self, name: impl Into<String>, definition: impl Into<String>) -> Self {
        let column = ColumnBuilder::from_definition(name.into(), definition.into());
        self.columns.push(column);
        self
    }

    /// Add multiple columns to the table
    ///
    /// # Parameters
    ///
    /// - `columns`: Vector of column builders to add
    ///
    /// # Examples
    ///
    /// ```rust
    /// let columns = vec![
    ///     ColumnBuilder::new("id", ColumnType::Int4).primary_key(),
    ///     ColumnBuilder::new("email", ColumnType::Varchar(Some(255))),
    ///     ColumnBuilder::new("name", ColumnType::Varchar(Some(100))),
    /// ];
    ///
    /// let table = TableBuilder::new("users")
    ///     .columns(columns)
    ///     .build()?;
    /// ```
    pub fn columns(mut self, columns: Vec<ColumnBuilder>) -> Self {
        self.columns.extend(columns);
        self
    }

    /// Add a comment to the table
    ///
    /// # Parameters
    ///
    /// - `comment`: The comment text
    ///
    /// # Examples
    ///
    /// ```rust
    /// let table = TableBuilder::new("users")
    ///     .comment("User accounts table")
    ///     .build()?;
    /// ```
    pub fn comment(mut self, comment: impl Into<String>) -> Self {
        self.comment = Some(comment.into());
        self
    }

    /// Add a storage parameter to the table
    ///
    /// # Parameters
    ///
    /// - `key`: The storage parameter name
    /// - `value`: The storage parameter value
    ///
    /// # Examples
    ///
    /// ```rust
    /// let table = TableBuilder::new("large_table")
    ///     .storage_parameter("autovacuum_vacuum_scale_factor", "0.1")
    ///     .storage_parameter("fillfactor", "80")
    ///     .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
    }

    /// Make the table inherit from another table
    ///
    /// # Parameters
    ///
    /// - `parent_table`: The parent table name
    ///
    /// # Examples
    ///
    /// ```rust
    /// let table = TableBuilder::new("users_2024")
    ///     .inherits_from("users")
    ///     .build()?;
    /// ```
    pub fn inherits_from(mut self, parent_table: impl Into<String>) -> Self {
        self.inherits_from.push(parent_table.into());
        self
    }

    /// Set the partitioning strategy for the table
    ///
    /// # Parameters
    ///
    /// - `strategy`: The partitioning strategy
    ///
    /// # Examples
    ///
    /// ```rust
    /// let table = TableBuilder::new("events")
    ///     .partition_by(PartitionStrategy::Range(vec!["created_at".to_string()]))
    ///     .build()?;
    /// ```
    pub fn partition_by(mut self, strategy: PartitionStrategy) -> Self {
        self.partition_by = Some(strategy);
        self
    }

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

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

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

    /// Check if the table has a primary key
    pub fn has_primary_key(&self) -> bool {
        self.columns.iter().any(|col| col.is_primary_key())
    }

    /// Get the primary key column names
    pub fn primary_key_columns(&self) -> Vec<&str> {
        self.columns
            .iter()
            .filter(|col| col.is_primary_key())
            .map(|col| col.name())
            .collect()
    }

    /// Check if the table has any foreign key references
    pub fn has_foreign_keys(&self) -> bool {
        self.columns.iter().any(|col| col.has_foreign_key())
    }

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

    /// Check if the table inherits from other tables
    pub fn has_inheritance(&self) -> bool {
        !self.inherits_from.is_empty()
    }

    /// Check if the table is partitioned
    pub fn is_partitioned(&self) -> bool {
        self.partition_by.is_some()
    }
}

impl SchemaBuilder for TableBuilder {
    type Output = Table;
    type Error = TableBuildError;

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

        // Build all columns
        let columns: Vec<Column> = self
            .columns
            .into_iter()
            .map(|cb| cb.build())
            .collect::<Result<Vec<_>, _>>()?;

        // Create the table
        let mut table = if let Some(schema) = &self.schema {
            Table::with_schema(schema.clone(), self.name)
        } else {
            Table::new(self.name)
        };

        // Add all columns
        for column in columns {
            table = table.add_column(column);
        }

        // Set RLS configuration
        if self.rls_enabled {
            table = table.enable_rls();
        }

        // Add policies
        for policy in self.policies {
            table = table.add_policy(policy);
        }

        // Note: Comment, storage parameters, inheritance, and partitioning
        // are not yet supported in the Table struct. These will be added
        // in future enhancements.

        Ok(table)
    }
}

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

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

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

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

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

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

        // Validate columns
        if self.columns.is_empty() {
            errors.push("Table must have at least one column".to_string());
        }

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

        // Validate primary key
        let primary_key_count = self
            .columns
            .iter()
            .filter(|col| col.is_primary_key())
            .count();

        if primary_key_count == 0 {
            errors.push("Table must have exactly one primary key".to_string());
        }

        if primary_key_count > 1 {
            errors.push(format!(
                "Table cannot have multiple primary keys, found {}",
                primary_key_count
            ));
        }

        // Validate inheritance
        for parent in &self.inherits_from {
            if parent.is_empty() {
                errors.push("Parent table name cannot be empty".to_string());
            }

            if parent.len() > 63 {
                errors.push(format!(
                    "Parent table name '{}' cannot exceed 63 characters",
                    parent
                ));
            }
        }

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

            if value.is_empty() {
                errors.push(format!("Storage parameter '{}' value cannot be empty", key));
            }
        }

        errors
    }
}

impl ConditionalBuilder for TableBuilder {}

impl InspectableBuilder for TableBuilder {
    fn debug_info(&self) -> String {
        format!(
            "TableBuilder {{ name: {:?}, schema: {:?}, columns: {}, comment: {:?}, storage_parameters: {}, inherits_from: {:?}, partition_by: {:?} }}",
            self.name, self.schema, self.columns.len(), self.comment, self.storage_parameters.len(), self.inherits_from, self.partition_by
        )
    }

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

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

        parts.push(format!("with {} columns", self.columns.len()));

        if self.has_primary_key() {
            let pk_cols = self.primary_key_columns();
            parts.push(format!("primary key: {}", pk_cols.join(", ")));
        }

        if self.has_foreign_keys() {
            parts.push("with foreign keys".to_string());
        }

        if self.has_inheritance() {
            parts.push(format!("inherits from: {}", self.inherits_from.join(", ")));
        }

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

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

        if !self.storage_parameters.is_empty() {
            parts.push(format!(
                "with {} storage parameters",
                self.storage_parameters.len()
            ));
        }

        parts.join(", ")
    }
}

impl TableBuilder {
    /// Enable Row-Level Security on this table
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ignis_db::builders::TableBuilder;
    ///
    /// let table = TableBuilder::new("users")
    ///     .enable_rls()
    ///     .build()?;
    /// ```
    pub fn enable_rls(mut self) -> Self {
        self.rls_enabled = true;
        self
    }

    /// Disable Row-Level Security on this table
    pub fn disable_rls(mut self) -> Self {
        self.rls_enabled = false;
        self
    }

    /// Add a policy to this table
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ignis_db::builders::{TableBuilder, PolicyBuilder};
    /// use ignis_db::schema::PolicyCommand;
    ///
    /// let policy = PolicyBuilder::for_table("users")
    ///     .name("user_access_policy")
    ///     .allow_all()
    ///     .for_role("authenticated_user")
    ///     .using_expression("id = current_setting('jwt.claims.user_id')::UUID")
    ///     .build()?;
    ///
    /// let table = TableBuilder::new("users")
    ///     .enable_rls()
    ///     .add_policy(policy)
    ///     .build()?;
    /// ```
    pub fn add_policy(mut self, policy: crate::schema::Policy) -> Self {
        self.policies.push(policy);
        self
    }

    /// Add multiple policies to this table
    pub fn add_policies(mut self, policies: Vec<crate::schema::Policy>) -> Self {
        self.policies.extend(policies);
        self
    }

    /// Check if RLS is enabled
    pub fn is_rls_enabled(&self) -> bool {
        self.rls_enabled
    }

    /// Get all policies for this table
    pub fn policies(&self) -> &[crate::schema::Policy] {
        &self.policies
    }
}

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

        Ok(())
    }
}

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

    #[test]
    fn test_table_builder_basic() {
        let table = TableBuilder::new("users")
            .column(ColumnBuilder::new("id", ColumnType::Int4).primary_key())
            .column(ColumnBuilder::new("email", ColumnType::Varchar(Some(255))))
            .build()
            .expect("Should build successfully");

        assert_eq!(table.name, "users");
        assert_eq!(table.columns.len(), 2);
    }

    #[test]
    fn test_table_builder_with_schema() {
        let table = TableBuilder::new("users")
            .schema("public")
            .column(ColumnBuilder::new("id", ColumnType::Int4).primary_key())
            .build()
            .expect("Should build successfully");

        assert_eq!(table.name, "users");
        assert_eq!(table.schema, Some("public".to_string()));
    }

    #[test]
    fn test_table_builder_validation() {
        let result = TableBuilder::new("").build();

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

    #[test]
    fn test_table_builder_no_columns() {
        let result = TableBuilder::new("users").build();

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

    #[test]
    fn test_table_builder_no_primary_key() {
        let result = TableBuilder::new("users")
            .column(ColumnBuilder::new("email", ColumnType::Varchar(Some(255))))
            .build();

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

    #[test]
    fn test_table_builder_multiple_primary_keys() {
        let result = TableBuilder::new("users")
            .column(ColumnBuilder::new("id", ColumnType::Int4).primary_key())
            .column(ColumnBuilder::new("email", ColumnType::Varchar(Some(255))).primary_key())
            .build();

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

    #[test]
    fn test_table_builder_duplicate_columns() {
        let result = TableBuilder::new("users")
            .column(ColumnBuilder::new("id", ColumnType::Int4).primary_key())
            .column(ColumnBuilder::new("id", ColumnType::Int4))
            .build();

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

    #[test]
    fn test_table_builder_inspection() {
        let builder = TableBuilder::new("users")
            .schema("public")
            .column(ColumnBuilder::new("id", ColumnType::Int4).primary_key())
            .comment("User accounts table");

        assert!(builder.is_valid());
        assert_eq!(builder.name(), "users");
        assert_eq!(builder.get_schema(), Some("public"));
        assert_eq!(builder.column_count(), 1);
        assert!(builder.has_primary_key());
        assert_eq!(builder.primary_key_columns(), vec!["id"]);

        let summary = builder.summary();
        assert!(summary.contains("table 'users'"));
        assert!(summary.contains("in schema 'public'"));
        assert!(summary.contains("with 1 columns"));
        assert!(summary.contains("primary key: id"));
        assert!(summary.contains("with comment"));
    }

    #[test]
    fn test_table_builder_storage_parameters() {
        let builder = TableBuilder::new("large_table")
            .column(ColumnBuilder::new("id", ColumnType::Int4).primary_key())
            .storage_parameter("autovacuum_vacuum_scale_factor", "0.1")
            .storage_parameter("fillfactor", "80");

        assert!(builder.is_valid());
        assert_eq!(builder.storage_parameter_count(), 2);
    }

    #[test]
    fn test_table_builder_inheritance() {
        let builder = TableBuilder::new("users_2024")
            .column(ColumnBuilder::new("id", ColumnType::Int4).primary_key())
            .inherits_from("users");

        assert!(builder.is_valid());
        assert!(builder.has_inheritance());
        assert_eq!(builder.inherits_from.len(), 1);
    }

    #[test]
    fn test_table_builder_partitioning() {
        let builder = TableBuilder::new("events")
            .column(ColumnBuilder::new("id", ColumnType::Int4).primary_key())
            .partition_by(PartitionStrategy::Range(vec!["created_at".to_string()]));

        assert!(builder.is_valid());
        assert!(builder.is_partitioned());
    }
}