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;
#[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>,
}
#[derive(Debug, Clone)]
pub enum PartitionStrategy {
Range(Vec<String>),
List(Vec<String>),
Hash(Vec<String>),
}
impl TableBuilder {
pub fn new(name: impl Into<String>) -> Self {
let full_name = name.into();
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(),
}
}
}
pub fn schema(mut self, schema: impl Into<String>) -> Self {
self.schema = Some(schema.into());
self
}
pub fn column(mut self, column: ColumnBuilder) -> Self {
self.columns.push(column);
self
}
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
}
pub fn columns(mut self, columns: Vec<ColumnBuilder>) -> Self {
self.columns.extend(columns);
self
}
pub fn comment(mut self, comment: impl Into<String>) -> Self {
self.comment = Some(comment.into());
self
}
pub fn storage_parameter(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.storage_parameters.insert(key.into(), value.into());
self
}
pub fn inherits_from(mut self, parent_table: impl Into<String>) -> Self {
self.inherits_from.push(parent_table.into());
self
}
pub fn partition_by(mut self, strategy: PartitionStrategy) -> Self {
self.partition_by = Some(strategy);
self
}
pub fn name(&self) -> &str {
&self.name
}
pub fn get_schema(&self) -> Option<&str> {
self.schema.as_deref()
}
pub fn column_count(&self) -> usize {
self.columns.len()
}
pub fn has_primary_key(&self) -> bool {
self.columns.iter().any(|col| col.is_primary_key())
}
pub fn primary_key_columns(&self) -> Vec<&str> {
self.columns
.iter()
.filter(|col| col.is_primary_key())
.map(|col| col.name())
.collect()
}
pub fn has_foreign_keys(&self) -> bool {
self.columns.iter().any(|col| col.has_foreign_key())
}
pub fn storage_parameter_count(&self) -> usize {
self.storage_parameters.len()
}
pub fn has_inheritance(&self) -> bool {
!self.inherits_from.is_empty()
}
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> {
self.validate()?;
let columns: Vec<Column> = self
.columns
.into_iter()
.map(|cb| cb.build())
.collect::<Result<Vec<_>, _>>()?;
let mut table = if let Some(schema) = &self.schema {
Table::with_schema(schema.clone(), self.name)
} else {
Table::new(self.name)
};
for column in columns {
table = table.add_column(column);
}
if self.rls_enabled {
table = table.enable_rls();
}
for policy in self.policies {
table = table.add_policy(policy);
}
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();
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());
}
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());
}
}
if self.columns.is_empty() {
errors.push("Table must have at least one column".to_string());
}
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()));
}
}
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
));
}
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
));
}
}
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 {
pub fn enable_rls(mut self) -> Self {
self.rls_enabled = true;
self
}
pub fn disable_rls(mut self) -> Self {
self.rls_enabled = false;
self
}
pub fn add_policy(mut self, policy: crate::schema::Policy) -> Self {
self.policies.push(policy);
self
}
pub fn add_policies(mut self, policies: Vec<crate::schema::Policy>) -> Self {
self.policies.extend(policies);
self
}
pub fn is_rls_enabled(&self) -> bool {
self.rls_enabled
}
pub fn policies(&self) -> &[crate::schema::Policy] {
&self.policies
}
}
impl TableBuilder {
fn validate(&self) -> Result<(), TableBuildError> {
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());
}
}