use crate::builders::traits::{
ConditionalBuilder, InspectableBuilder, SchemaBuilder, ValidatableBuilder,
};
use crate::builders::validation::ColumnBuildError;
use crate::schema::{Column, ColumnType, ForeignKey};
use std::collections::HashMap;
#[derive(Debug, Clone)]
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>,
storage_parameters: HashMap<String, String>,
}
#[derive(Debug, Clone)]
pub struct ForeignKeyBuilder {
table: String,
column: String,
on_delete: Option<String>,
on_update: Option<String>,
}
#[derive(Debug, Clone)]
pub struct GeneratedColumnSpec {
pub expression: String,
pub stored: bool,
}
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,
storage_parameters: HashMap::new(),
}
}
pub fn from_definition(name: impl Into<String>, definition: impl Into<String>) -> Self {
let name = name.into();
let definition = definition.into().to_uppercase();
let (column_type, primary_key, unique, nullable, default) = Self::parse_definition(&definition);
Self {
name,
column_type,
nullable,
default,
primary_key,
unique,
references: None,
check_constraint: None,
comment: None,
collation: None,
generated: None,
storage_parameters: HashMap::new(),
}
}
fn parse_definition(definition: &str) -> (ColumnType, bool, bool, bool, Option<String>) {
let mut primary_key = false;
let mut unique = false;
let mut nullable = true;
let mut default = None;
if definition.contains("PRIMARY KEY") {
primary_key = true;
nullable = false; }
if definition.contains("UNIQUE") {
unique = true;
}
if definition.contains("NOT NULL") {
nullable = false;
}
if let Some(start) = definition.find("DEFAULT ") {
let after_default = &definition[start + 8..];
if let Some(end) = after_default.find(' ') {
default = Some(after_default[..end].to_string());
} else {
default = Some(after_default.to_string());
}
}
let column_type = if definition.contains("UUID") {
ColumnType::Uuid
} else if definition.contains("VARCHAR") {
if let Some(start) = definition.find("VARCHAR(") {
let after_varchar = &definition[start + 8..];
if let Some(end) = after_varchar.find(')') {
if let Ok(length) = after_varchar[..end].parse::<u32>() {
ColumnType::Varchar(Some(length as usize))
} else {
ColumnType::Varchar(None)
}
} else {
ColumnType::Varchar(None)
}
} else {
ColumnType::Varchar(None)
}
} else if definition.contains("TEXT") {
ColumnType::Text
} else if definition.contains("INTEGER") || definition.contains("INT4") {
ColumnType::Int4
} else if definition.contains("BIGINT") || definition.contains("INT8") {
ColumnType::Int8
} else if definition.contains("SMALLINT") || definition.contains("INT2") {
ColumnType::Int2
} else if definition.contains("BOOLEAN") || definition.contains("BOOL") {
ColumnType::Bool
} else if definition.contains("TIMESTAMPTZ") {
ColumnType::Timestamptz
} else if definition.contains("TIMESTAMP") {
ColumnType::Timestamptz
} else if definition.contains("DATE") {
ColumnType::Date
} else if definition.contains("TIME") {
ColumnType::Time
} else if definition.contains("JSONB") {
ColumnType::Jsonb
} else if definition.contains("JSON") {
ColumnType::Json
} else if definition.contains("NUMERIC") {
ColumnType::Numeric(None, None)
} else if definition.contains("SERIAL") {
ColumnType::Serial
} else if definition.contains("BIGSERIAL") {
ColumnType::BigSerial
} else {
ColumnType::Text
};
(column_type, primary_key, unique, nullable, default)
}
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; self
}
pub fn unique(mut self) -> Self {
self.unique = true;
self
}
pub fn references(mut self, table: impl Into<String>, column: impl Into<String>) -> Self {
self.references = Some(ForeignKeyBuilder::new(table, column));
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 storage_parameter(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.storage_parameters.insert(key.into(), value.into());
self
}
pub fn on_delete(mut self, action: impl Into<String>) -> Self {
if let Some(ref mut fk) = self.references {
fk.on_delete = Some(action.into());
}
self
}
pub fn on_update(mut self, action: impl Into<String>) -> Self {
if let Some(ref mut fk) = self.references {
fk.on_update = Some(action.into());
}
self
}
pub fn name(&self) -> &str {
&self.name
}
pub fn column_type(&self) -> &ColumnType {
&self.column_type
}
pub fn is_nullable(&self) -> bool {
self.nullable
}
pub fn is_primary_key(&self) -> bool {
self.primary_key
}
pub fn is_unique(&self) -> bool {
self.unique
}
pub fn has_foreign_key(&self) -> bool {
self.references.is_some()
}
pub fn is_generated(&self) -> bool {
self.generated.is_some()
}
pub fn storage_parameter_count(&self) -> usize {
self.storage_parameters.len()
}
}
impl ForeignKeyBuilder {
pub fn new(table: impl Into<String>, column: impl Into<String>) -> Self {
Self {
table: table.into(),
column: column.into(),
on_delete: None,
on_update: None,
}
}
pub fn on_delete(mut self, action: impl Into<String>) -> Self {
self.on_delete = Some(action.into());
self
}
pub fn on_update(mut self, action: impl Into<String>) -> Self {
self.on_update = Some(action.into());
self
}
pub fn build(self) -> Result<ForeignKey, ColumnBuildError> {
if self.table.is_empty() {
return Err(ColumnBuildError::ForeignKeyError(
crate::builders::validation::ForeignKeyBuildError::InvalidReferencedTable(
"Empty table name".to_string(),
),
));
}
if self.column.is_empty() {
return Err(ColumnBuildError::ForeignKeyError(
crate::builders::validation::ForeignKeyBuildError::InvalidReferencedColumn(
"Empty column name".to_string(),
),
));
}
let fk = ForeignKey {
table: self.table,
column: self.column,
};
Ok(fk)
}
}
impl SchemaBuilder for ColumnBuilder {
type Output = Column;
type Error = ColumnBuildError;
fn build(self) -> Result<Self::Output, Self::Error> {
self.validate()?;
let mut column = Column::new(self.name, self.column_type);
if !self.nullable {
column = column.not_null();
}
if let Some(default) = self.default {
column = column.default(default);
}
if self.unique {
column = column.unique();
}
if let Some(fk) = self.references {
let foreign_key = fk.build()?;
column = column.references(foreign_key);
}
if let Some(check) = self.check_constraint {
column = column.check(check);
}
Ok(column)
}
}
impl ValidatableBuilder for ColumnBuilder {
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("Column name cannot be empty".to_string());
}
if self.name.len() > 63 {
errors.push("Column name cannot exceed 63 characters".to_string());
}
if let Some(_) = self.generated {
if self.default.is_some() {
errors.push("Generated columns cannot have default values".to_string());
}
if self.primary_key {
errors.push("Generated columns cannot be primary keys".to_string());
}
if self.references.is_some() {
errors.push("Generated columns cannot have foreign key references".to_string());
}
}
if let Some(check) = &self.check_constraint {
if check.is_empty() {
errors.push("Check constraint expression cannot be empty".to_string());
}
if check.len() > 1000 {
errors.push("Check constraint expression is too long".to_string());
}
}
if let Some(default) = &self.default {
if default.is_empty() {
errors.push("Default value cannot be empty".to_string());
}
}
errors
}
}
impl ConditionalBuilder for ColumnBuilder {}
impl InspectableBuilder for ColumnBuilder {
fn debug_info(&self) -> String {
format!(
"ColumnBuilder {{ name: {:?}, type: {:?}, nullable: {}, primary_key: {}, unique: {}, generated: {:?} }}",
self.name, self.column_type, self.nullable, self.primary_key, self.unique, self.generated
)
}
fn summary(&self) -> String {
let mut parts = vec![
format!("column '{}'", self.name),
format!("type {:?}", self.column_type),
];
if !self.nullable {
parts.push("NOT NULL".to_string());
}
if self.primary_key {
parts.push("PRIMARY KEY".to_string());
}
if self.unique {
parts.push("UNIQUE".to_string());
}
if self.default.is_some() {
parts.push("with default".to_string());
}
if self.references.is_some() {
parts.push("with foreign key".to_string());
}
if self.check_constraint.is_some() {
parts.push("with check constraint".to_string());
}
if self.generated.is_some() {
parts.push("generated".to_string());
}
parts.join(", ")
}
}
impl ColumnBuilder {
fn validate(&self) -> Result<(), ColumnBuildError> {
let errors = self.validation_errors();
if !errors.is_empty() {
return Err(ColumnBuildError::ValidationError(errors.join("; ")));
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::schema::ColumnType;
#[test]
fn test_column_builder_basic() {
let column = ColumnBuilder::new("id", ColumnType::Int4)
.primary_key()
.build()
.expect("Should build successfully");
assert_eq!(column.name, "id");
assert_eq!(column.column_type, ColumnType::Int4);
assert!(!column.nullable);
}
#[test]
fn test_column_builder_advanced() {
let column = ColumnBuilder::new("email", ColumnType::Varchar(Some(255)))
.not_null()
.unique()
.default("'unknown@example.com'")
.comment("User email address")
.build()
.expect("Should build successfully");
assert_eq!(column.name, "email");
assert_eq!(column.column_type, ColumnType::Varchar(Some(255)));
assert!(!column.nullable);
assert!(column.unique);
}
#[test]
fn test_column_builder_validation() {
let result = ColumnBuilder::new("", ColumnType::Int4).build();
assert!(result.is_err());
assert!(matches!(
result.unwrap_err(),
ColumnBuildError::ValidationError(_)
));
}
#[test]
fn test_column_builder_generated_constraints() {
let result = ColumnBuilder::new("full_name", ColumnType::Varchar(Some(200)))
.generated_as("first_name || ' ' || last_name", true)
.default("'Unknown'")
.build();
assert!(result.is_err());
assert!(matches!(
result.unwrap_err(),
ColumnBuildError::ValidationError(_)
));
}
#[test]
fn test_column_builder_foreign_key() {
let column = ColumnBuilder::new("user_id", ColumnType::Int4)
.references("users", "id")
.on_delete("CASCADE")
.on_update("CASCADE")
.build()
.expect("Should build successfully");
assert_eq!(column.name, "user_id");
assert!(column.references.is_some());
}
#[test]
fn test_column_builder_inspection() {
let builder = ColumnBuilder::new("id", ColumnType::Int4)
.primary_key()
.comment("Primary key");
assert!(builder.is_valid());
assert_eq!(builder.name(), "id");
assert!(builder.is_primary_key());
assert!(!builder.is_nullable());
let summary = builder.summary();
assert!(summary.contains("column 'id'"));
assert!(summary.contains("PRIMARY KEY"));
}
}