1use 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#[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#[derive(Debug, Clone)]
63pub enum PartitionStrategy {
64 Range(Vec<String>),
65 List(Vec<String>),
66 Hash(Vec<String>),
67}
68
69impl TableBuilder {
70 pub fn new(name: impl Into<String>) -> Self {
85 let full_name = name.into();
86
87 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 pub fn schema(mut self, schema: impl Into<String>) -> Self {
132 self.schema = Some(schema.into());
133 self
134 }
135
136 pub fn column(mut self, column: ColumnBuilder) -> Self {
151 self.columns.push(column);
152 self
153 }
154
155 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 pub fn columns(mut self, columns: Vec<ColumnBuilder>) -> Self {
197 self.columns.extend(columns);
198 self
199 }
200
201 pub fn comment(mut self, comment: impl Into<String>) -> Self {
215 self.comment = Some(comment.into());
216 self
217 }
218
219 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 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 pub fn partition_by(mut self, strategy: PartitionStrategy) -> Self {
271 self.partition_by = Some(strategy);
272 self
273 }
274
275 pub fn name(&self) -> &str {
277 &self.name
278 }
279
280 pub fn get_schema(&self) -> Option<&str> {
282 self.schema.as_deref()
283 }
284
285 pub fn column_count(&self) -> usize {
287 self.columns.len()
288 }
289
290 pub fn has_primary_key(&self) -> bool {
292 self.columns.iter().any(|col| col.is_primary_key())
293 }
294
295 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 pub fn has_foreign_keys(&self) -> bool {
306 self.columns.iter().any(|col| col.has_foreign_key())
307 }
308
309 pub fn storage_parameter_count(&self) -> usize {
311 self.storage_parameters.len()
312 }
313
314 pub fn has_inheritance(&self) -> bool {
316 !self.inherits_from.is_empty()
317 }
318
319 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 self.validate()?;
332
333 let columns: Vec<Column> = self
335 .columns
336 .into_iter()
337 .map(|cb| cb.build())
338 .collect::<Result<Vec<_>, _>>()?;
339
340 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 for column in columns {
349 table = table.add_column(column);
350 }
351
352 if self.rls_enabled {
354 table = table.enable_rls();
355 }
356
357 for policy in self.policies {
359 table = table.add_policy(policy);
360 }
361
362 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 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 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 if self.columns.is_empty() {
400 errors.push("Table must have at least one column".to_string());
401 }
402
403 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 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 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 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 pub fn enable_rls(mut self) -> Self {
522 self.rls_enabled = true;
523 self
524 }
525
526 pub fn disable_rls(mut self) -> Self {
528 self.rls_enabled = false;
529 self
530 }
531
532 pub fn add_policy(mut self, policy: crate::schema::Policy) -> Self {
553 self.policies.push(policy);
554 self
555 }
556
557 pub fn add_policies(mut self, policies: Vec<crate::schema::Policy>) -> Self {
559 self.policies.extend(policies);
560 self
561 }
562
563 pub fn is_rls_enabled(&self) -> bool {
565 self.rls_enabled
566 }
567
568 pub fn policies(&self) -> &[crate::schema::Policy] {
570 &self.policies
571 }
572}
573
574impl TableBuilder {
575 fn validate(&self) -> Result<(), TableBuildError> {
577 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}