use crate::builders::traits::{
ConditionalBuilder, InspectableBuilder, SchemaBuilder, ValidatableBuilder,
};
use crate::builders::validation::ConstraintBuildError;
use crate::schema::{Constraint, ConstraintType};
use std::collections::HashSet;
#[derive(Debug, Clone)]
pub struct ConstraintBuilder {
name: Option<String>,
constraint_type: ConstraintType,
columns: Vec<String>,
expression: Option<String>,
deferrable: bool,
initially_deferred: bool,
comment: Option<String>,
}
impl ConstraintBuilder {
pub fn new(constraint_type: ConstraintType) -> Self {
Self {
name: None,
constraint_type,
columns: Vec::new(),
expression: None,
deferrable: false,
initially_deferred: false,
comment: None,
}
}
pub fn name(mut self, name: impl Into<String>) -> Self {
self.name = Some(name.into());
self
}
pub fn set_name(&mut self, name: impl Into<String>) {
self.name = Some(name.into());
}
pub fn column(mut self, column: impl Into<String>) -> Self {
self.columns.push(column.into());
self
}
pub fn add_column(&mut self, column: impl Into<String>) {
self.columns.push(column.into());
}
pub fn columns(mut self, columns: impl IntoIterator<Item = impl Into<String>>) -> Self {
self.columns.extend(columns.into_iter().map(|c| c.into()));
self
}
pub fn add_columns(&mut self, columns: impl IntoIterator<Item = impl Into<String>>) {
self.columns.extend(columns.into_iter().map(|c| c.into()));
}
pub fn expression(mut self, expression: impl Into<String>) -> Self {
self.expression = Some(expression.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 comment(mut self, comment: impl Into<String>) -> Self {
self.comment = Some(comment.into());
self
}
pub fn primary_key() -> Self {
Self::new(ConstraintType::Unique(vec![]))
}
pub fn unique() -> Self {
Self::new(ConstraintType::Unique(vec![]))
}
pub fn check(expression: impl Into<String>) -> Self {
let expr = expression.into();
Self::new(ConstraintType::Check(expr.clone())).expression(expr)
}
pub fn foreign_key(
referenced_table: impl Into<String>,
referenced_column: impl Into<String>,
) -> Self {
let expr = format!(
"REFERENCES {}({})",
referenced_table.into(),
referenced_column.into()
);
Self::new(ConstraintType::Check(expr.clone())).expression(expr)
}
pub fn not_null() -> Self {
let expr = "NOT NULL".to_string();
Self::new(ConstraintType::Check(expr.clone())).expression(expr)
}
pub fn default(default_value: impl Into<String>) -> Self {
let expr = format!("DEFAULT {}", default_value.into());
Self::new(ConstraintType::Check(expr.clone())).expression(expr)
}
pub fn exclusion() -> Self {
let expr = "EXCLUDE".to_string();
Self::new(ConstraintType::Check(expr.clone())).expression(expr)
}
pub fn exclusion_with_expression(expression: impl Into<String>) -> Self {
let expr = expression.into();
Self::new(ConstraintType::Check(expr.clone())).expression(expr)
}
pub fn unique_on(columns: impl IntoIterator<Item = impl Into<String>>) -> Self {
let cols: Vec<String> = columns.into_iter().map(|c| c.into()).collect();
Self::new(ConstraintType::Unique(cols.clone())).columns(cols)
}
pub fn primary_key_on(columns: impl IntoIterator<Item = impl Into<String>>) -> Self {
let cols: Vec<String> = columns.into_iter().map(|c| c.into()).collect();
Self::new(ConstraintType::Unique(cols.clone())).columns(cols)
}
pub fn check_on(expression: impl Into<String>) -> Self {
Self::check(expression)
}
pub fn foreign_key_on(
columns: impl IntoIterator<Item = impl Into<String>>,
referenced_table: impl Into<String>,
referenced_columns: impl IntoIterator<Item = impl Into<String>>,
) -> Self {
let ref_cols: Vec<String> = referenced_columns.into_iter().map(|c| c.into()).collect();
let ref_expr = format!(
"REFERENCES {}({})",
referenced_table.into(),
ref_cols.join(", ")
);
Self::new(ConstraintType::Check(ref_expr.clone()))
.expression(ref_expr)
.columns(columns)
}
pub fn get_name(&self) -> Option<&str> {
self.name.as_deref()
}
pub fn get_constraint_type(&self) -> &ConstraintType {
&self.constraint_type
}
pub fn get_columns(&self) -> &[String] {
&self.columns
}
pub fn get_expression(&self) -> Option<&str> {
self.expression.as_deref()
}
pub fn is_deferrable(&self) -> bool {
self.deferrable
}
pub fn is_initially_deferred(&self) -> bool {
self.initially_deferred
}
pub fn get_comment(&self) -> Option<&str> {
self.comment.as_deref()
}
pub fn column_count(&self) -> usize {
self.columns.len()
}
pub fn has_column(&self, column_name: &str) -> bool {
self.columns.iter().any(|c| c == column_name)
}
pub fn has_expression(&self) -> bool {
self.expression.is_some()
}
pub fn has_name(&self) -> bool {
self.name.is_some()
}
pub fn has_comment(&self) -> bool {
self.comment.is_some()
}
}
impl SchemaBuilder for ConstraintBuilder {
type Output = Constraint;
type Error = ConstraintBuildError;
fn build(self) -> Result<Self::Output, Self::Error> {
if !self.is_valid() {
let errors = self.validation_errors();
return Err(ConstraintBuildError::ValidationError(errors.join("; ")));
}
let constraint = match &self.constraint_type {
ConstraintType::Unique(_) => {
if self.columns.is_empty() {
return Err(ConstraintBuildError::ValidationError(
"Unique constraint must specify columns".to_string(),
));
}
Constraint {
name: self.name.unwrap_or_else(|| "constraint".to_string()),
constraint_type: ConstraintType::Unique(self.columns),
}
}
ConstraintType::Check(_) => {
let expression = self.expression.ok_or_else(|| {
ConstraintBuildError::ValidationError(
"Check constraint must have an expression".to_string(),
)
})?;
Constraint {
name: self.name.unwrap_or_else(|| "constraint".to_string()),
constraint_type: ConstraintType::Check(expression),
}
}
};
Ok(constraint)
}
}
impl ValidatableBuilder for ConstraintBuilder {
fn is_valid(&self) -> bool {
self.validation_errors().is_empty()
}
fn validation_errors(&self) -> Vec<String> {
let mut errors = Vec::new();
match &self.constraint_type {
ConstraintType::Unique(_) => {
if self.columns.is_empty() {
errors.push("Constraint must specify at least one column".to_string());
}
}
ConstraintType::Check(_) => {
if self.expression.is_none() {
errors.push("Check constraint must have an expression".to_string());
}
}
}
for (i, column) in self.columns.iter().enumerate() {
if column.trim().is_empty() {
errors.push(format!("Column {} at index {} cannot be empty", i, i));
}
}
let mut seen_columns = HashSet::new();
for column in &self.columns {
if !seen_columns.insert(column) {
errors.push(format!("Duplicate column name: {}", column));
}
}
if let Some(ref name) = self.name {
if name.trim().is_empty() {
errors.push("Constraint name cannot be empty".to_string());
}
}
if let Some(ref expression) = self.expression {
if expression.trim().is_empty() {
errors.push("Constraint expression cannot be empty".to_string());
}
}
errors
}
}
impl ConditionalBuilder for ConstraintBuilder {
fn when<F>(mut self, condition: bool, config_fn: F) -> Self
where
F: FnOnce(&mut Self),
Self: Sized,
{
if condition {
config_fn(&mut self);
}
self
}
}
impl InspectableBuilder for ConstraintBuilder {
fn debug_info(&self) -> String {
format!(
"ConstraintBuilder {{ type: {:?}, columns: {:?}, expression: {:?}, name: {:?} }}",
self.constraint_type, self.columns, self.expression, self.name
)
}
fn summary(&self) -> String {
let mut parts = Vec::new();
let constraint_desc = match &self.constraint_type {
ConstraintType::Unique(_) => "Unique constraint",
ConstraintType::Check(_) => "Check constraint",
};
parts.push(constraint_desc.to_string());
if !self.columns.is_empty() {
parts.push(format!("on columns: {}", self.columns.join(", ")));
}
if let Some(ref name) = self.name {
parts.push(format!("named '{}'", name));
}
if let Some(ref expr) = self.expression {
parts.push(format!("with expression: {}", expr));
}
if self.deferrable {
parts.push("deferrable".to_string());
}
if self.initially_deferred {
parts.push("initially deferred".to_string());
}
if let Some(ref comment) = self.comment {
parts.push(format!("with comment: {}", comment));
}
parts.join(", ")
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::schema::ConstraintType;
#[test]
fn test_primary_key_constraint() {
let constraint = ConstraintBuilder::primary_key()
.name("pk_users")
.columns(vec!["id"])
.build()
.unwrap();
assert_eq!(
constraint.constraint_type,
ConstraintType::Unique(vec!["id".to_string()])
);
assert_eq!(constraint.name, "pk_users");
}
#[test]
fn test_unique_constraint() {
let constraint = ConstraintBuilder::unique()
.name("uq_users_email")
.columns(vec!["email"])
.build()
.unwrap();
assert_eq!(
constraint.constraint_type,
ConstraintType::Unique(vec!["email".to_string()])
);
assert_eq!(constraint.name, "uq_users_email");
}
#[test]
fn test_check_constraint() {
let constraint = ConstraintBuilder::check("age > 0")
.name("chk_users_age")
.build()
.unwrap();
assert_eq!(
constraint.constraint_type,
ConstraintType::Check("age > 0".to_string())
);
assert_eq!(constraint.name, "chk_users_age");
}
#[test]
fn test_foreign_key_constraint() {
let constraint = ConstraintBuilder::foreign_key("users", "id")
.name("fk_posts_user_id")
.columns(vec!["user_id"])
.build()
.unwrap();
assert!(format!("{:?}", constraint.constraint_type).contains("REFERENCES users(id)"));
assert_eq!(constraint.name, "fk_posts_user_id");
}
#[test]
fn test_not_null_constraint() {
let constraint = ConstraintBuilder::not_null()
.column("email")
.build()
.unwrap();
assert_eq!(
constraint.constraint_type,
ConstraintType::Check("NOT NULL".to_string())
);
assert_eq!(constraint.name, "constraint");
}
#[test]
fn test_default_constraint() {
let constraint = ConstraintBuilder::default("'unknown'")
.column("status")
.build()
.unwrap();
assert_eq!(
constraint.constraint_type,
ConstraintType::Check("DEFAULT 'unknown'".to_string())
);
assert_eq!(constraint.name, "constraint");
}
#[test]
fn test_exclusion_constraint() {
let constraint =
ConstraintBuilder::exclusion_with_expression("email WITH =, username WITH =")
.name("excl_users_email_username")
.columns(vec!["email", "username"])
.build()
.unwrap();
assert_eq!(
constraint.constraint_type,
ConstraintType::Check("email WITH =, username WITH =".to_string())
);
assert_eq!(constraint.name, "excl_users_email_username");
}
#[test]
fn test_convenience_methods() {
let pk_constraint = ConstraintBuilder::primary_key_on(vec!["id", "tenant_id"])
.name("pk_composite")
.build()
.unwrap();
let unique_constraint = ConstraintBuilder::unique_on(vec!["email", "tenant_id"])
.name("uq_email_tenant")
.build()
.unwrap();
let fk_constraint = ConstraintBuilder::foreign_key_on(
vec!["user_id", "tenant_id"],
"users",
vec!["id", "tenant_id"],
)
.name("fk_composite")
.build()
.unwrap();
assert_eq!(
pk_constraint.constraint_type,
ConstraintType::Unique(vec!["id".to_string(), "tenant_id".to_string()])
);
assert_eq!(pk_constraint.name, "pk_composite");
assert_eq!(
unique_constraint.constraint_type,
ConstraintType::Unique(vec!["email".to_string(), "tenant_id".to_string()])
);
assert_eq!(unique_constraint.name, "uq_email_tenant");
assert!(format!("{:?}", fk_constraint.constraint_type)
.contains("REFERENCES users(id, tenant_id)"));
assert_eq!(fk_constraint.name, "fk_composite");
}
#[test]
fn test_validation_errors() {
let result = ConstraintBuilder::unique().build();
assert!(result.is_err());
assert!(matches!(
result.unwrap_err(),
ConstraintBuildError::ValidationError(_)
));
let result = ConstraintBuilder::check("").build();
assert!(result.is_err());
assert!(matches!(
result.unwrap_err(),
ConstraintBuildError::ValidationError(_)
));
}
#[test]
fn test_conditional_builder() {
let condition = true;
let constraint = ConstraintBuilder::primary_key()
.when(condition, |c| {
c.set_name("pk_when_true");
})
.column("id")
.build()
.unwrap();
assert_eq!(constraint.name, "pk_when_true");
}
#[test]
fn test_inspection_methods() {
let builder = ConstraintBuilder::primary_key()
.name("pk_test")
.columns(vec!["id", "tenant_id"]);
assert_eq!(builder.get_name(), Some("pk_test"));
assert_eq!(
builder.get_constraint_type(),
&ConstraintType::Unique(vec![])
);
assert_eq!(builder.get_columns(), &["id", "tenant_id"]);
assert_eq!(builder.column_count(), 2);
assert!(builder.has_column("id"));
assert!(!builder.has_column("nonexistent"));
assert!(builder.has_name());
assert!(!builder.has_expression());
assert!(!builder.has_comment());
}
#[test]
fn test_debug_info_and_summary() {
let builder = ConstraintBuilder::unique()
.name("uq_email")
.column("email")
.comment("Ensure unique emails");
let debug_info = builder.debug_info();
let summary = builder.summary();
assert!(debug_info.contains("ConstraintBuilder"));
assert!(debug_info.contains("Unique"));
assert!(debug_info.contains("email"));
assert!(summary.contains("Unique constraint"));
assert!(summary.contains("on columns: email"));
assert!(summary.contains("named 'uq_email'"));
assert!(summary.contains("with comment: Ensure unique emails"));
}
}