Skip to main content

ignis_db/builders/
table.rs

1//! TableBuilder for Ignis-DB
2//!
3//! This module provides a fluent builder API for constructing database tables
4//! with comprehensive validation and configuration options.
5
6use crate::builders::column::ColumnBuilder;
7use crate::builders::traits::{
8    ConditionalBuilder, InspectableBuilder, SchemaBuilder, ValidatableBuilder,
9};
10use crate::builders::validation::TableBuildError;
11use crate::schema::{Column, Table};
12use std::collections::HashMap;
13
14/// Builder for creating database tables
15///
16/// This builder provides a fluent, chainable API for constructing tables
17/// with comprehensive validation and configuration options.
18///
19/// # Examples
20///
21/// ```rust
22/// use ignis_db::builders::{TableBuilder, ColumnBuilder, table};
23/// use ignis_db::schema::ColumnType;
24///
25/// // Basic table
26/// let users_table = TableBuilder::new("users")
27///     .column(ColumnBuilder::new("id", ColumnType::Int4).primary_key())
28///     .column(ColumnBuilder::new("email", ColumnType::Varchar(Some(255))).unique())
29///     .build()?;
30///
31/// // Advanced table with constraints and indexes
32/// let posts_table = TableBuilder::new("posts")
33///     .schema("blog")
34///     .column(ColumnBuilder::new("id", ColumnType::Int4).primary_key())
35///     .column(ColumnBuilder::new("user_id", ColumnType::Int4).not_null())
36///     .column(ColumnBuilder::new("title", ColumnType::Varchar(Some(200))).not_null())
37///     .column(ColumnBuilder::new("content", ColumnType::Text))
38///     .column(ColumnBuilder::new("published", ColumnType::Bool).default("false"))
39///     .column(ColumnBuilder::new("created_at", ColumnType::Timestamptz).default("NOW()"))
40///     .comment("Blog posts table")
41///     .build()?;
42///
43/// // Using convenience function
44/// let simple_table = table("simple")
45///     .column(ColumnBuilder::new("id", ColumnType::Int4).primary_key())
46///     .build()?;
47/// ```
48#[derive(Debug, Clone)]
49pub struct TableBuilder {
50    name: String,
51    schema: Option<String>,
52    columns: Vec<ColumnBuilder>,
53    comment: Option<String>,
54    storage_parameters: HashMap<String, String>,
55    inherits_from: Vec<String>,
56    partition_by: Option<PartitionStrategy>,
57    rls_enabled: bool,
58    policies: Vec<crate::schema::Policy>,
59}
60
61/// Partitioning strategy for tables
62#[derive(Debug, Clone)]
63pub enum PartitionStrategy {
64    Range(Vec<String>),
65    List(Vec<String>),
66    Hash(Vec<String>),
67}
68
69impl TableBuilder {
70    /// Create a new table builder
71    ///
72    /// # Parameters
73    ///
74    /// - `name`: The name of the table (can be schema-qualified like "auth.users")
75    ///
76    /// # Examples
77    ///
78    /// ```rust
79    /// use ignis_db::builders::TableBuilder;
80    ///
81    /// let table = TableBuilder::new("users");           // Simple table name
82    /// let table = TableBuilder::new("auth.users");     // Schema-qualified name
83    /// ```
84    pub fn new(name: impl Into<String>) -> Self {
85        let full_name = name.into();
86
87        // Check if the name is schema-qualified (contains a dot)
88        if let Some(dot_pos) = full_name.find('.') {
89            let schema_name = &full_name[..dot_pos];
90            let table_name = &full_name[dot_pos + 1..];
91
92            Self {
93                name: table_name.to_string(),
94                schema: Some(schema_name.to_string()),
95                columns: Vec::new(),
96                comment: None,
97                storage_parameters: HashMap::new(),
98                inherits_from: Vec::new(),
99                partition_by: None,
100                rls_enabled: false,
101                policies: Vec::new(),
102            }
103        } else {
104            Self {
105                name: full_name,
106                schema: None,
107                columns: Vec::new(),
108                comment: None,
109                storage_parameters: HashMap::new(),
110                inherits_from: Vec::new(),
111                partition_by: None,
112                rls_enabled: false,
113                policies: Vec::new(),
114            }
115        }
116    }
117
118    /// Set the schema for the table
119    ///
120    /// # Parameters
121    ///
122    /// - `schema`: The schema name
123    ///
124    /// # Examples
125    ///
126    /// ```rust
127    /// let table = TableBuilder::new("users")
128    ///     .schema("public")
129    ///     .build()?;
130    /// ```
131    pub fn schema(mut self, schema: impl Into<String>) -> Self {
132        self.schema = Some(schema.into());
133        self
134    }
135
136    /// Add a column to the table
137    ///
138    /// # Parameters
139    ///
140    /// - `column`: The column builder to add
141    ///
142    /// # Examples
143    ///
144    /// ```rust
145    /// let table = TableBuilder::new("users")
146    ///     .column(ColumnBuilder::new("id", ColumnType::Int4).primary_key())
147    ///     .column(ColumnBuilder::new("email", ColumnType::Varchar(Some(255))))
148    ///     .build()?;
149    /// ```
150    pub fn column(mut self, column: ColumnBuilder) -> Self {
151        self.columns.push(column);
152        self
153    }
154
155    /// Add a column with a simple string definition (convenience method)
156    ///
157    /// # Parameters
158    ///
159    /// - `name`: The column name
160    /// - `definition`: The column definition (e.g., "UUID PRIMARY KEY DEFAULT gen_random_uuid()")
161    ///
162    /// # Examples
163    ///
164    /// ```rust
165    /// let table = TableBuilder::new("users")
166    ///     .add_column("id", "UUID PRIMARY KEY DEFAULT gen_random_uuid()")
167    ///     .add_column("email", "VARCHAR(255) UNIQUE NOT NULL")
168    ///     .add_column("created_at", "TIMESTAMPTZ DEFAULT NOW()")
169    ///     .build()?;
170    /// ```
171    pub fn add_column(mut self, name: impl Into<String>, definition: impl Into<String>) -> Self {
172        let column = ColumnBuilder::from_definition(name.into(), definition.into());
173        self.columns.push(column);
174        self
175    }
176
177    /// Add multiple columns to the table
178    ///
179    /// # Parameters
180    ///
181    /// - `columns`: Vector of column builders to add
182    ///
183    /// # Examples
184    ///
185    /// ```rust
186    /// let columns = vec![
187    ///     ColumnBuilder::new("id", ColumnType::Int4).primary_key(),
188    ///     ColumnBuilder::new("email", ColumnType::Varchar(Some(255))),
189    ///     ColumnBuilder::new("name", ColumnType::Varchar(Some(100))),
190    /// ];
191    ///
192    /// let table = TableBuilder::new("users")
193    ///     .columns(columns)
194    ///     .build()?;
195    /// ```
196    pub fn columns(mut self, columns: Vec<ColumnBuilder>) -> Self {
197        self.columns.extend(columns);
198        self
199    }
200
201    /// Add a comment to the table
202    ///
203    /// # Parameters
204    ///
205    /// - `comment`: The comment text
206    ///
207    /// # Examples
208    ///
209    /// ```rust
210    /// let table = TableBuilder::new("users")
211    ///     .comment("User accounts table")
212    ///     .build()?;
213    /// ```
214    pub fn comment(mut self, comment: impl Into<String>) -> Self {
215        self.comment = Some(comment.into());
216        self
217    }
218
219    /// Add a storage parameter to the table
220    ///
221    /// # Parameters
222    ///
223    /// - `key`: The storage parameter name
224    /// - `value`: The storage parameter value
225    ///
226    /// # Examples
227    ///
228    /// ```rust
229    /// let table = TableBuilder::new("large_table")
230    ///     .storage_parameter("autovacuum_vacuum_scale_factor", "0.1")
231    ///     .storage_parameter("fillfactor", "80")
232    ///     .build()?;
233    /// ```
234    pub fn storage_parameter(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
235        self.storage_parameters.insert(key.into(), value.into());
236        self
237    }
238
239    /// Make the table inherit from another table
240    ///
241    /// # Parameters
242    ///
243    /// - `parent_table`: The parent table name
244    ///
245    /// # Examples
246    ///
247    /// ```rust
248    /// let table = TableBuilder::new("users_2024")
249    ///     .inherits_from("users")
250    ///     .build()?;
251    /// ```
252    pub fn inherits_from(mut self, parent_table: impl Into<String>) -> Self {
253        self.inherits_from.push(parent_table.into());
254        self
255    }
256
257    /// Set the partitioning strategy for the table
258    ///
259    /// # Parameters
260    ///
261    /// - `strategy`: The partitioning strategy
262    ///
263    /// # Examples
264    ///
265    /// ```rust
266    /// let table = TableBuilder::new("events")
267    ///     .partition_by(PartitionStrategy::Range(vec!["created_at".to_string()]))
268    ///     .build()?;
269    /// ```
270    pub fn partition_by(mut self, strategy: PartitionStrategy) -> Self {
271        self.partition_by = Some(strategy);
272        self
273    }
274
275    /// Get the table name
276    pub fn name(&self) -> &str {
277        &self.name
278    }
279
280    /// Get the schema name
281    pub fn get_schema(&self) -> Option<&str> {
282        self.schema.as_deref()
283    }
284
285    /// Get the number of columns
286    pub fn column_count(&self) -> usize {
287        self.columns.len()
288    }
289
290    /// Check if the table has a primary key
291    pub fn has_primary_key(&self) -> bool {
292        self.columns.iter().any(|col| col.is_primary_key())
293    }
294
295    /// Get the primary key column names
296    pub fn primary_key_columns(&self) -> Vec<&str> {
297        self.columns
298            .iter()
299            .filter(|col| col.is_primary_key())
300            .map(|col| col.name())
301            .collect()
302    }
303
304    /// Check if the table has any foreign key references
305    pub fn has_foreign_keys(&self) -> bool {
306        self.columns.iter().any(|col| col.has_foreign_key())
307    }
308
309    /// Get the number of storage parameters
310    pub fn storage_parameter_count(&self) -> usize {
311        self.storage_parameters.len()
312    }
313
314    /// Check if the table inherits from other tables
315    pub fn has_inheritance(&self) -> bool {
316        !self.inherits_from.is_empty()
317    }
318
319    /// Check if the table is partitioned
320    pub fn is_partitioned(&self) -> bool {
321        self.partition_by.is_some()
322    }
323}
324
325impl SchemaBuilder for TableBuilder {
326    type Output = Table;
327    type Error = TableBuildError;
328
329    fn build(self) -> Result<Self::Output, Self::Error> {
330        // Validate the configuration
331        self.validate()?;
332
333        // Build all columns
334        let columns: Vec<Column> = self
335            .columns
336            .into_iter()
337            .map(|cb| cb.build())
338            .collect::<Result<Vec<_>, _>>()?;
339
340        // Create the table
341        let mut table = if let Some(schema) = &self.schema {
342            Table::with_schema(schema.clone(), self.name)
343        } else {
344            Table::new(self.name)
345        };
346
347        // Add all columns
348        for column in columns {
349            table = table.add_column(column);
350        }
351
352        // Set RLS configuration
353        if self.rls_enabled {
354            table = table.enable_rls();
355        }
356
357        // Add policies
358        for policy in self.policies {
359            table = table.add_policy(policy);
360        }
361
362        // Note: Comment, storage parameters, inheritance, and partitioning
363        // are not yet supported in the Table struct. These will be added
364        // in future enhancements.
365
366        Ok(table)
367    }
368}
369
370impl ValidatableBuilder for TableBuilder {
371    fn is_valid(&self) -> bool {
372        self.validation_errors().is_empty()
373    }
374
375    fn validation_errors(&self) -> Vec<String> {
376        let mut errors = Vec::new();
377
378        // Validate table name
379        if self.name.is_empty() {
380            errors.push("Table name cannot be empty".to_string());
381        }
382
383        if self.name.len() > 63 {
384            errors.push("Table name cannot exceed 63 characters".to_string());
385        }
386
387        // Validate schema name if specified
388        if let Some(ref schema) = self.schema {
389            if schema.is_empty() {
390                errors.push("Schema name cannot be empty".to_string());
391            }
392
393            if schema.len() > 63 {
394                errors.push("Schema name cannot exceed 63 characters".to_string());
395            }
396        }
397
398        // Validate columns
399        if self.columns.is_empty() {
400            errors.push("Table must have at least one column".to_string());
401        }
402
403        // Check for duplicate column names
404        let mut column_names = std::collections::HashSet::new();
405        for column in &self.columns {
406            if !column_names.insert(column.name()) {
407                errors.push(format!("Duplicate column name: {}", column.name()));
408            }
409        }
410
411        // Validate primary key
412        let primary_key_count = self
413            .columns
414            .iter()
415            .filter(|col| col.is_primary_key())
416            .count();
417
418        if primary_key_count == 0 {
419            errors.push("Table must have exactly one primary key".to_string());
420        }
421
422        if primary_key_count > 1 {
423            errors.push(format!(
424                "Table cannot have multiple primary keys, found {}",
425                primary_key_count
426            ));
427        }
428
429        // Validate inheritance
430        for parent in &self.inherits_from {
431            if parent.is_empty() {
432                errors.push("Parent table name cannot be empty".to_string());
433            }
434
435            if parent.len() > 63 {
436                errors.push(format!(
437                    "Parent table name '{}' cannot exceed 63 characters",
438                    parent
439                ));
440            }
441        }
442
443        // Validate storage parameters
444        for (key, value) in &self.storage_parameters {
445            if key.is_empty() {
446                errors.push("Storage parameter key cannot be empty".to_string());
447            }
448
449            if value.is_empty() {
450                errors.push(format!("Storage parameter '{}' value cannot be empty", key));
451            }
452        }
453
454        errors
455    }
456}
457
458impl ConditionalBuilder for TableBuilder {}
459
460impl InspectableBuilder for TableBuilder {
461    fn debug_info(&self) -> String {
462        format!(
463            "TableBuilder {{ name: {:?}, schema: {:?}, columns: {}, comment: {:?}, storage_parameters: {}, inherits_from: {:?}, partition_by: {:?} }}",
464            self.name, self.schema, self.columns.len(), self.comment, self.storage_parameters.len(), self.inherits_from, self.partition_by
465        )
466    }
467
468    fn summary(&self) -> String {
469        let mut parts = vec![format!("table '{}'", self.name)];
470
471        if let Some(ref schema) = self.schema {
472            parts.push(format!("in schema '{}'", schema));
473        }
474
475        parts.push(format!("with {} columns", self.columns.len()));
476
477        if self.has_primary_key() {
478            let pk_cols = self.primary_key_columns();
479            parts.push(format!("primary key: {}", pk_cols.join(", ")));
480        }
481
482        if self.has_foreign_keys() {
483            parts.push("with foreign keys".to_string());
484        }
485
486        if self.has_inheritance() {
487            parts.push(format!("inherits from: {}", self.inherits_from.join(", ")));
488        }
489
490        if self.is_partitioned() {
491            parts.push("partitioned".to_string());
492        }
493
494        if self.comment.is_some() {
495            parts.push("with comment".to_string());
496        }
497
498        if !self.storage_parameters.is_empty() {
499            parts.push(format!(
500                "with {} storage parameters",
501                self.storage_parameters.len()
502            ));
503        }
504
505        parts.join(", ")
506    }
507}
508
509impl TableBuilder {
510    /// Enable Row-Level Security on this table
511    ///
512    /// # Examples
513    ///
514    /// ```rust
515    /// use ignis_db::builders::TableBuilder;
516    ///
517    /// let table = TableBuilder::new("users")
518    ///     .enable_rls()
519    ///     .build()?;
520    /// ```
521    pub fn enable_rls(mut self) -> Self {
522        self.rls_enabled = true;
523        self
524    }
525
526    /// Disable Row-Level Security on this table
527    pub fn disable_rls(mut self) -> Self {
528        self.rls_enabled = false;
529        self
530    }
531
532    /// Add a policy to this table
533    ///
534    /// # Examples
535    ///
536    /// ```rust
537    /// use ignis_db::builders::{TableBuilder, PolicyBuilder};
538    /// use ignis_db::schema::PolicyCommand;
539    ///
540    /// let policy = PolicyBuilder::for_table("users")
541    ///     .name("user_access_policy")
542    ///     .allow_all()
543    ///     .for_role("authenticated_user")
544    ///     .using_expression("id = current_setting('jwt.claims.user_id')::UUID")
545    ///     .build()?;
546    ///
547    /// let table = TableBuilder::new("users")
548    ///     .enable_rls()
549    ///     .add_policy(policy)
550    ///     .build()?;
551    /// ```
552    pub fn add_policy(mut self, policy: crate::schema::Policy) -> Self {
553        self.policies.push(policy);
554        self
555    }
556
557    /// Add multiple policies to this table
558    pub fn add_policies(mut self, policies: Vec<crate::schema::Policy>) -> Self {
559        self.policies.extend(policies);
560        self
561    }
562
563    /// Check if RLS is enabled
564    pub fn is_rls_enabled(&self) -> bool {
565        self.rls_enabled
566    }
567
568    /// Get all policies for this table
569    pub fn policies(&self) -> &[crate::schema::Policy] {
570        &self.policies
571    }
572}
573
574impl TableBuilder {
575    /// Validate the table configuration
576    fn validate(&self) -> Result<(), TableBuildError> {
577        // Check for validation errors
578        let errors = self.validation_errors();
579        if !errors.is_empty() {
580            return Err(TableBuildError::ValidationError(errors.join("; ")));
581        }
582
583        Ok(())
584    }
585}
586
587#[cfg(test)]
588mod tests {
589    use super::*;
590    use crate::schema::ColumnType;
591
592    #[test]
593    fn test_table_builder_basic() {
594        let table = TableBuilder::new("users")
595            .column(ColumnBuilder::new("id", ColumnType::Int4).primary_key())
596            .column(ColumnBuilder::new("email", ColumnType::Varchar(Some(255))))
597            .build()
598            .expect("Should build successfully");
599
600        assert_eq!(table.name, "users");
601        assert_eq!(table.columns.len(), 2);
602    }
603
604    #[test]
605    fn test_table_builder_with_schema() {
606        let table = TableBuilder::new("users")
607            .schema("public")
608            .column(ColumnBuilder::new("id", ColumnType::Int4).primary_key())
609            .build()
610            .expect("Should build successfully");
611
612        assert_eq!(table.name, "users");
613        assert_eq!(table.schema, Some("public".to_string()));
614    }
615
616    #[test]
617    fn test_table_builder_validation() {
618        let result = TableBuilder::new("").build();
619
620        assert!(result.is_err());
621        assert!(matches!(
622            result.unwrap_err(),
623            TableBuildError::ValidationError(_)
624        ));
625    }
626
627    #[test]
628    fn test_table_builder_no_columns() {
629        let result = TableBuilder::new("users").build();
630
631        assert!(result.is_err());
632        assert!(matches!(
633            result.unwrap_err(),
634            TableBuildError::ValidationError(_)
635        ));
636    }
637
638    #[test]
639    fn test_table_builder_no_primary_key() {
640        let result = TableBuilder::new("users")
641            .column(ColumnBuilder::new("email", ColumnType::Varchar(Some(255))))
642            .build();
643
644        assert!(result.is_err());
645        assert!(matches!(
646            result.unwrap_err(),
647            TableBuildError::ValidationError(_)
648        ));
649    }
650
651    #[test]
652    fn test_table_builder_multiple_primary_keys() {
653        let result = TableBuilder::new("users")
654            .column(ColumnBuilder::new("id", ColumnType::Int4).primary_key())
655            .column(ColumnBuilder::new("email", ColumnType::Varchar(Some(255))).primary_key())
656            .build();
657
658        assert!(result.is_err());
659        assert!(matches!(
660            result.unwrap_err(),
661            TableBuildError::ValidationError(_)
662        ));
663    }
664
665    #[test]
666    fn test_table_builder_duplicate_columns() {
667        let result = TableBuilder::new("users")
668            .column(ColumnBuilder::new("id", ColumnType::Int4).primary_key())
669            .column(ColumnBuilder::new("id", ColumnType::Int4))
670            .build();
671
672        assert!(result.is_err());
673        assert!(matches!(
674            result.unwrap_err(),
675            TableBuildError::ValidationError(_)
676        ));
677    }
678
679    #[test]
680    fn test_table_builder_inspection() {
681        let builder = TableBuilder::new("users")
682            .schema("public")
683            .column(ColumnBuilder::new("id", ColumnType::Int4).primary_key())
684            .comment("User accounts table");
685
686        assert!(builder.is_valid());
687        assert_eq!(builder.name(), "users");
688        assert_eq!(builder.get_schema(), Some("public"));
689        assert_eq!(builder.column_count(), 1);
690        assert!(builder.has_primary_key());
691        assert_eq!(builder.primary_key_columns(), vec!["id"]);
692
693        let summary = builder.summary();
694        assert!(summary.contains("table 'users'"));
695        assert!(summary.contains("in schema 'public'"));
696        assert!(summary.contains("with 1 columns"));
697        assert!(summary.contains("primary key: id"));
698        assert!(summary.contains("with comment"));
699    }
700
701    #[test]
702    fn test_table_builder_storage_parameters() {
703        let builder = TableBuilder::new("large_table")
704            .column(ColumnBuilder::new("id", ColumnType::Int4).primary_key())
705            .storage_parameter("autovacuum_vacuum_scale_factor", "0.1")
706            .storage_parameter("fillfactor", "80");
707
708        assert!(builder.is_valid());
709        assert_eq!(builder.storage_parameter_count(), 2);
710    }
711
712    #[test]
713    fn test_table_builder_inheritance() {
714        let builder = TableBuilder::new("users_2024")
715            .column(ColumnBuilder::new("id", ColumnType::Int4).primary_key())
716            .inherits_from("users");
717
718        assert!(builder.is_valid());
719        assert!(builder.has_inheritance());
720        assert_eq!(builder.inherits_from.len(), 1);
721    }
722
723    #[test]
724    fn test_table_builder_partitioning() {
725        let builder = TableBuilder::new("events")
726            .column(ColumnBuilder::new("id", ColumnType::Int4).primary_key())
727            .partition_by(PartitionStrategy::Range(vec!["created_at".to_string()]));
728
729        assert!(builder.is_valid());
730        assert!(builder.is_partitioned());
731    }
732}