# Builder Implementation Details - Technical Specification
## ๐ฏ **Overview**
This document provides detailed technical specifications for implementing each builder type in the Ignis-DB Builder Pattern Enhancement.
## ๐๏ธ **1. TableBuilder Implementation**
### **1.1 Core Structure**
```rust
pub struct TableBuilder {
name: String,
schema: Option<String>,
columns: Vec<ColumnBuilder>,
constraints: Vec<ConstraintBuilder>,
indexes: Vec<IndexBuilder>,
comment: Option<String>,
storage_parameters: HashMap<String, String>,
inherits_from: Vec<String>,
partition_by: Option<PartitionStrategy>,
}
impl TableBuilder {
pub fn new(name: impl Into<String>) -> Self {
Self {
name: name.into(),
schema: None,
columns: Vec::new(),
constraints: Vec::new(),
indexes: Vec::new(),
comment: None,
storage_parameters: HashMap::new(),
inherits_from: Vec::new(),
partition_by: None,
}
}
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 constraint(mut self, constraint: ConstraintBuilder) -> Self {
self.constraints.push(constraint);
self
}
pub fn index(mut self, index: IndexBuilder) -> Self {
self.indexes.push(index);
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 build(self) -> Result<Table, TableBuildError> {
// Validation
self.validate()?;
// Build columns
let columns: Vec<Column> = self.columns
.into_iter()
.map(|cb| cb.build())
.collect::<Result<Vec<_>, _>>()?;
// Build constraints
let constraints: Vec<Constraint> = self.constraints
.into_iter()
.map(|cb| cb.build())
.collect::<Result<Vec<_>, _>>()?;
// Build indexes
let indexes: Vec<IndexMeta> = self.indexes
.into_iter()
.map(|ib| ib.build())
.collect::<Result<Vec<_>, _>>()?;
// Create table
let mut table = Table::new(self.name);
if let Some(schema) = self.schema {
table = table.with_schema(schema);
}
for column in columns {
table = table.with_column(column);
}
for constraint in constraints {
table = table.with_constraint(constraint);
}
for index in indexes {
table = table.with_index(index);
}
if let Some(comment) = self.comment {
table = table.with_comment(comment);
}
// Add storage parameters
for (key, value) in self.storage_parameters {
table = table.with_storage_parameter(key, value);
}
// Add inheritance
for parent in self.inherits_from {
table = table.inherits_from(parent);
}
// Add partitioning
if let Some(partition_strategy) = self.partition_by {
table = table.with_partition_strategy(partition_strategy);
}
Ok(table)
}
fn validate(&self) -> Result<(), TableBuildError> {
// Must have at least one column
if self.columns.is_empty() {
return Err(TableBuildError::NoColumns);
}
// Must have exactly one primary key
let primary_key_count = self.columns.iter()
.filter(|cb| cb.is_primary_key())
.count();
if primary_key_count == 0 {
return Err(TableBuildError::NoPrimaryKey);
}
if primary_key_count > 1 {
return Err(TableBuildError::MultiplePrimaryKeys);
}
// Column names must be unique
let mut column_names = HashSet::new();
for column in &self.columns {
if !column_names.insert(column.name.clone()) {
return Err(TableBuildError::DuplicateColumnName(column.name.clone()));
}
}
Ok(())
}
}
```
### **1.2 Usage Examples**
```rust
// Basic table
let users_table = TableBuilder::new("users")
.schema("public")
.column(ColumnBuilder::new("id", ColumnType::Int4).primary_key())
.column(ColumnBuilder::new("email", ColumnType::Varchar(Some(255))).unique().not_null())
.column(ColumnBuilder::new("name", ColumnType::Varchar(Some(100))).not_null())
.column(ColumnBuilder::new("created_at", ColumnType::Timestamptz).default("NOW()"))
.comment("User accounts table")
.build()?;
// Advanced table with constraints and indexes
let posts_table = TableBuilder::new("posts")
.schema("public")
.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()"))
.constraint(ConstraintBuilder::foreign_key("posts_user_id_fkey", "user_id", "users", "id"))
.index(IndexBuilder::new("posts_user_id_idx", ["user_id"]))
.index(IndexBuilder::new("posts_published_idx", ["published"]).where_clause("published = true"))
.storage_parameter("autovacuum_vacuum_scale_factor", "0.1")
.build()?;
```
## ๐๏ธ **2. ColumnBuilder Implementation**
### **2.1 Core Structure**
```rust
pub struct ColumnBuilder {
name: String,
column_type: ColumnType,
nullable: bool,
default: Option<String>,
primary_key: bool,
unique: bool,
references: Option<ForeignKeyBuilder>,
check_constraint: Option<String>,
comment: Option<String>,
collation: Option<String>,
generated: Option<GeneratedColumnSpec>,
}
impl ColumnBuilder {
pub fn new(name: impl Into<String>, column_type: ColumnType) -> Self {
Self {
name: name.into(),
column_type,
nullable: true,
default: None,
primary_key: false,
unique: false,
references: None,
check_constraint: None,
comment: None,
collation: None,
generated: None,
}
}
pub fn nullable(mut self) -> Self {
self.nullable = true;
self
}
pub fn not_null(mut self) -> Self {
self.nullable = false;
self
}
pub fn default(mut self, default: impl Into<String>) -> Self {
self.default = Some(default.into());
self
}
pub fn primary_key(mut self) -> Self {
self.primary_key = true;
self.nullable = false; // Primary keys are always NOT NULL
self
}
pub fn unique(mut self) -> Self {
self.unique = true;
self
}
pub fn references(mut self, fk: ForeignKeyBuilder) -> Self {
self.references = Some(fk);
self
}
pub fn check(mut self, constraint: impl Into<String>) -> Self {
self.check_constraint = Some(constraint.into());
self
}
pub fn comment(mut self, comment: impl Into<String>) -> Self {
self.comment = Some(comment.into());
self
}
pub fn collation(mut self, collation: impl Into<String>) -> Self {
self.collation = Some(collation.into());
self
}
pub fn generated_as(mut self, expression: impl Into<String>, stored: bool) -> Self {
self.generated = Some(GeneratedColumnSpec {
expression: expression.into(),
stored,
});
self
}
pub fn build(self) -> Result<Column, ColumnBuildError> {
// Validation
self.validate()?;
// Create column
let mut column = Column::new(self.name, self.column_type);
if !self.nullable {
column = column.set_not_null();
}
if let Some(default) = self.default {
column = column.set_default(default);
}
if self.primary_key {
column = column.set_primary_key();
}
if self.unique {
column = column.set_unique();
}
if let Some(fk) = self.references {
column = column.set_foreign_key(fk.build()?);
}
if let Some(check) = self.check_constraint {
column = column.set_check_constraint(check);
}
if let Some(comment) = self.comment {
column = column.set_comment(comment);
}
if let Some(collation) = self.collation {
column = column.set_collation(collation);
}
if let Some(generated) = self.generated {
column = column.set_generated(generated);
}
Ok(column)
}
fn validate(&self) -> Result<(), ColumnBuildError> {
// Generated columns cannot have defaults
if self.generated.is_some() && self.default.is_some() {
return Err(ColumnBuildError::GeneratedColumnWithDefault);
}
// Generated columns cannot be primary keys
if self.generated.is_some() && self.primary_key {
return Err(ColumnBuildError::GeneratedColumnAsPrimaryKey);
}
// Generated columns cannot have foreign keys
if self.generated.is_some() && self.references.is_some() {
return Err(ColumnBuildError::GeneratedColumnWithForeignKey);
}
// Check constraint validation
if let Some(check) = &self.check_constraint {
if !self.validate_check_constraint(check) {
return Err(ColumnBuildError::InvalidCheckConstraint(check.clone()));
}
}
Ok(())
}
fn validate_check_constraint(&self, constraint: &str) -> bool {
// Basic validation - could be enhanced with SQL parsing
!constraint.is_empty() && constraint.len() < 1000
}
}
```
### **2.2 Usage Examples**
```rust
// Basic column
let id_column = ColumnBuilder::new("id", ColumnType::Int4)
.primary_key()
.build()?;
// Advanced column with constraints
let email_column = ColumnBuilder::new("email", ColumnType::Varchar(Some(255)))
.not_null()
.unique()
.check("email ~* '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$'")
.comment("User email address")
.build()?;
// Generated column
let full_name_column = ColumnBuilder::new("full_name", ColumnType::Varchar(Some(200)))
.generated_as("first_name || ' ' || last_name", true)
.comment("Automatically generated full name")
.build()?;
// Foreign key column
let user_id_column = ColumnBuilder::new("user_id", ColumnType::Int4)
.not_null()
.references(ForeignKeyBuilder::new("users", "id")
.on_delete(ReferentialAction::Cascade))
.build()?;
```
## ๐๏ธ **3. ConstraintBuilder Implementation**
### **3.1 Core Structure**
```rust
pub struct ConstraintBuilder {
name: Option<String>,
constraint_type: ConstraintType,
columns: Vec<String>,
expression: Option<String>,
deferrable: bool,
initially_deferred: bool,
}
pub enum ConstraintType {
PrimaryKey,
Unique,
Check,
ForeignKey(ForeignKeyBuilder),
Exclusion,
}
impl ConstraintBuilder {
pub fn primary_key(columns: Vec<impl Into<String>>) -> Self {
Self {
name: None,
constraint_type: ConstraintType::PrimaryKey,
columns: columns.into_iter().map(|c| c.into()).collect(),
expression: None,
deferrable: false,
initially_deferred: false,
}
}
pub fn unique(columns: Vec<impl Into<String>>) -> Self {
Self {
name: None,
constraint_type: ConstraintType::Unique,
columns: columns.into_iter().map(|c| c.into()).collect(),
expression: None,
deferrable: false,
initially_deferred: false,
}
}
pub fn check(expression: impl Into<String>) -> Self {
Self {
name: None,
constraint_type: ConstraintType::Check,
columns: Vec::new(),
expression: Some(expression.into()),
deferrable: false,
initially_deferred: false,
}
}
pub fn foreign_key(columns: Vec<impl Into<String>>, fk: ForeignKeyBuilder) -> Self {
Self {
name: None,
constraint_type: ConstraintType::ForeignKey(fk),
columns: columns.into_iter().map(|c| c.into()).collect(),
expression: None,
deferrable: false,
initially_deferred: false,
}
}
pub fn named(mut self, name: impl Into<String>) -> Self {
self.name = Some(name.into());
self
}
pub fn deferrable(mut self) -> Self {
self.deferrable = true;
self
}
pub fn initially_deferred(mut self) -> Self {
self.initially_deferred = true;
self
}
pub fn build(self) -> Result<Constraint, ConstraintBuildError> {
// Validation
self.validate()?;
// Create constraint based on type
match self.constraint_type {
ConstraintType::PrimaryKey => {
Constraint::primary_key(self.columns, self.name)
}
ConstraintType::Unique => {
Constraint::unique(self.columns, self.name)
}
ConstraintType::Check => {
let expression = self.expression.ok_or(ConstraintBuildError::MissingExpression)?;
Constraint::check(expression, self.name)
}
ConstraintType::ForeignKey(fk) => {
let fk_constraint = fk.build()?;
Constraint::foreign_key(self.columns, fk_constraint, self.name)
}
ConstraintType::Exclusion => {
// Implementation for exclusion constraints
unimplemented!("Exclusion constraints not yet implemented");
}
}
}
fn validate(&self) -> Result<(), ConstraintBuildError> {
match self.constraint_type {
ConstraintType::PrimaryKey | ConstraintType::Unique => {
if self.columns.is_empty() {
return Err(ConstraintBuildError::NoColumns);
}
}
ConstraintType::Check => {
if self.expression.is_none() {
return Err(ConstraintBuildError::MissingExpression);
}
}
ConstraintType::ForeignKey(_) => {
if self.columns.is_empty() {
return Err(ConstraintBuildError::NoColumns);
}
}
ConstraintType::Exclusion => {
// Validation for exclusion constraints
}
}
Ok(())
}
}
```
### **3.2 Usage Examples**
```rust
// Primary key constraint
let pk_constraint = ConstraintBuilder::primary_key(vec!["id"])
.named("users_pkey")
.build()?;
// Unique constraint
let unique_constraint = ConstraintBuilder::unique(vec!["email"])
.named("users_email_key")
.build()?;
// Check constraint
let check_constraint = ConstraintBuilder::check("age >= 0")
.named("users_age_check")
.build()?;
// Foreign key constraint
let fk_constraint = ConstraintBuilder::foreign_key(
vec!["user_id"],
ForeignKeyBuilder::new("users", "id")
.on_delete(ReferentialAction::Cascade)
)
.named("posts_user_id_fkey")
.build()?;
```
## ๐๏ธ **4. IndexBuilder Implementation**
### **4.1 Core Structure**
```rust
pub struct IndexBuilder {
name: Option<String>,
columns: Vec<IndexColumnSpec>,
unique: bool,
concurrent: bool,
index_type: IndexType,
where_clause: Option<String>,
storage_parameters: HashMap<String, String>,
comment: Option<String>,
}
pub struct IndexColumnSpec {
name: String,
collation: Option<String>,
opclass: Option<String>,
sort_order: Option<SortOrder>,
nulls_order: Option<NullsOrder>,
}
pub enum SortOrder {
Asc,
Desc,
}
pub enum NullsOrder {
First,
Last,
}
impl IndexBuilder {
pub fn new(columns: Vec<impl Into<String>>) -> Self {
Self {
name: None,
columns: columns.into_iter()
.map(|c| IndexColumnSpec::new(c))
.collect(),
unique: false,
concurrent: false,
index_type: IndexType::BTree,
where_clause: None,
storage_parameters: HashMap::new(),
comment: None,
}
}
pub fn named(mut self, name: impl Into<String>) -> Self {
self.name = Some(name.into());
self
}
pub fn unique(mut self) -> Self {
self.unique = true;
self
}
pub fn concurrent(mut self) -> Self {
self.concurrent = true;
self
}
pub fn index_type(mut self, index_type: IndexType) -> Self {
self.index_type = index_type;
self
}
pub fn where_clause(mut self, where_clause: impl Into<String>) -> Self {
self.where_clause = Some(where_clause.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 comment(mut self, comment: impl Into<String>) -> Self {
self.comment = Some(comment.into());
self
}
pub fn build(self) -> Result<IndexMeta, IndexBuildError> {
// Validation
self.validate()?;
// Create index
let mut index = IndexMeta::new(
self.name.unwrap_or_else(|| self.generate_name()),
self.columns.iter().map(|c| c.name.clone()).collect()
);
index = index.with_unique(self.unique);
index = index.with_concurrent(self.concurrent);
index = index.with_index_type(self.index_type);
if let Some(where_clause) = self.where_clause {
index = index.with_where_clause(where_clause);
}
if let Some(comment) = self.comment {
index = index.with_comment(comment);
}
// Add storage parameters
for (key, value) in self.storage_parameters {
index = index.with_storage_parameter(key, value);
}
Ok(index)
}
fn validate(&self) -> Result<(), IndexBuildError> {
if self.columns.is_empty() {
return Err(IndexBuildError::NoColumns);
}
// Validate where clause syntax (basic validation)
if let Some(where_clause) = &self.where_clause {
if where_clause.is_empty() {
return Err(IndexBuildError::EmptyWhereClause);
}
}
Ok(())
}
fn generate_name(&self) -> String {
// Generate index name based on columns
let column_names = self.columns.iter()
.map(|c| c.name.as_str())
.collect::<Vec<_>>()
.join("_");
format!("idx_{}_{}",
self.table_name.as_deref().unwrap_or("table"),
column_names
)
}
}
```
### **4.2 Usage Examples**
```rust
// Basic index
let basic_index = IndexBuilder::new(vec!["user_id"])
.named("posts_user_id_idx")
.build()?;
// Unique index
let unique_index = IndexBuilder::new(vec!["email"])
.unique()
.named("users_email_unique_idx")
.build()?;
// Partial index
let partial_index = IndexBuilder::new(vec!["status", "created_at"])
.where_clause("status = 'published'")
.named("posts_published_status_idx")
.build()?;
// GIN index for full-text search
let gin_index = IndexBuilder::new(vec!["content"])
.index_type(IndexType::GIN)
.named("posts_content_gin_idx")
.comment("Full-text search index")
.build()?;
// Concurrent index
let concurrent_index = IndexBuilder::new(vec!["user_id", "created_at"])
.concurrent()
.named("posts_user_created_concurrent_idx")
.build()?;
```
## ๐ง **5. Integration Points**
### **5.1 With Existing Schema System**
```rust
// Both approaches generate the same final objects
let table_from_macro = table! { users (id) { ... } };
let table_from_builder = TableBuilder::new("users")
.column(ColumnBuilder::new("id", ColumnType::Int4).primary_key())
.build()?;
// Both register in the same inventory system
assert_eq!(table_from_macro.name(), table_from_builder.name());
assert_eq!(table_from_macro.columns().len(), table_from_builder.columns().len());
```
### **5.2 With Migration System**
```rust
// Builders can be used in migrations
let migration = MigrationBuilder::new()
.set_old_schema(vec![old_table])
.set_new_schema(vec![new_table])
.add_table(TableBuilder::new("new_table")
.column(ColumnBuilder::new("id", ColumnType::Int4).primary_key())
.build()?)
.build()?;
```
### **5.3 With DDL Generation**
```rust
// Builders generate the same DDL as macros
let table = TableBuilder::new("users")
.column(ColumnBuilder::new("id", ColumnType::Int4).primary_key())
.column(ColumnBuilder::new("email", ColumnType::Varchar(Some(255))).unique())
.build()?;
let ddl = table.to_sql();
// Generates: CREATE TABLE "users" ("id" INTEGER PRIMARY KEY, "email" VARCHAR(255) UNIQUE);
```
## ๐งช **6. Testing Strategy**
### **6.1 Unit Tests**
```rust
#[test]
fn test_table_builder_basic() {
let table = TableBuilder::new("users")
.column(ColumnBuilder::new("id", ColumnType::Int4).primary_key())
.build()
.expect("Should build successfully");
assert_eq!(table.name(), "users");
assert_eq!(table.columns().len(), 1);
assert!(table.primary_key_columns().contains("id"));
}
#[test]
fn test_table_builder_validation() {
let result = TableBuilder::new("users")
.build(); // No columns
assert!(result.is_err());
assert_matches!(result.unwrap_err(), TableBuildError::NoColumns);
}
```
### **6.2 Integration Tests**
```rust
#[test]
fn test_builder_vs_macro_equivalence() {
let table_from_macro = table! { users (id) { id -> Int4 } };
let table_from_builder = TableBuilder::new("users")
.column(ColumnBuilder::new("id", ColumnType::Int4).primary_key())
.build()
.expect("Should build successfully");
// Both should generate identical objects
assert_eq!(table_from_macro.name(), table_from_builder.name());
assert_eq!(table_from_macro.columns().len(), table_from_builder.columns().len());
// Both should generate identical DDL
assert_eq!(table_from_macro.to_sql(), table_from_builder.to_sql());
}
```
### **6.3 Performance Tests**
```rust
#[test]
fn test_builder_performance() {
let start = Instant::now();
for _ in 0..1000 {
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");
}
let duration = start.elapsed();
assert!(duration.as_millis() < 100, "Builder should be fast");
}
```
## ๐ **7. Documentation Examples**
### **7.1 API Documentation**
```rust
/// Builder for creating database tables with a fluent, chainable API.
///
/// This builder provides an alternative to the macro-based approach for
/// programmatically constructing table definitions.
///
/// # Examples
///
/// Basic table creation:
/// ```rust
/// use ignis_db::builders::TableBuilder;
///
/// let 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:
/// ```rust
/// let table = TableBuilder::new("posts")
/// .schema("blog")
/// .column(ColumnBuilder::new("id", ColumnType::Int4).primary_key())
/// .column(ColumnBuilder::new("user_id", ColumnType::Int4).not_null())
/// .constraint(ConstraintBuilder::foreign_key(
/// vec!["user_id"],
/// ForeignKeyBuilder::new("users", "id")
/// ))
/// .index(IndexBuilder::new(vec!["user_id"]).named("posts_user_id_idx"))
/// .comment("Blog posts table")
/// .build()?;
/// ```
pub struct TableBuilder { ... }
```
### **7.2 Migration Guide**
```rust
// Before (macro approach)
let table = table! {
users (id) {
id -> Int4,
email -> Varchar,
name -> Varchar
}
};
// After (builder approach)
let table = TableBuilder::new("users")
.column(ColumnBuilder::new("id", ColumnType::Int4).primary_key())
.column(ColumnBuilder::new("email", ColumnType::Varchar(Some(255))))
.column(ColumnBuilder::new("name", ColumnType::Varchar(Some(100))))
.build()?;
```
This detailed technical specification provides the foundation for implementing the Builder Pattern Enhancement while maintaining full compatibility with the existing macro-based approach.