use crate::builders::sql_validation::SqlValidator;
use crate::builders::traits::{
ConditionalBuilder, InspectableBuilder, SchemaBuilder, ValidatableBuilder,
};
use crate::builders::validation::CustomSqlBuildError;
use crate::migrate::Migration;
use anyhow::Result;
#[derive(Debug, Clone)]
pub struct CustomSqlBuilder {
id: Option<String>,
name: Option<String>,
up_sql: Option<String>,
down_sql: Option<String>,
description: Option<String>,
tags: Vec<String>,
requires_manual_review: bool,
is_destructive: bool,
dependencies: Vec<String>,
rollback_safe: bool,
}
impl CustomSqlBuilder {
pub fn new() -> Self {
Self {
id: None,
name: None,
up_sql: None,
down_sql: None,
description: None,
tags: Vec::new(),
requires_manual_review: false,
is_destructive: false,
dependencies: Vec::new(),
rollback_safe: true,
}
}
pub fn with_id(id: impl Into<String>) -> Self {
Self::new().id(id)
}
pub fn id(mut self, id: impl Into<String>) -> Self {
self.id = Some(id.into());
self
}
pub fn name(mut self, name: impl Into<String>) -> Self {
self.name = Some(name.into());
self
}
pub fn up_sql(mut self, sql: impl Into<String>) -> Self {
self.up_sql = Some(sql.into());
self
}
pub fn down_sql(mut self, sql: impl Into<String>) -> Self {
self.down_sql = Some(sql.into());
self
}
pub fn description(mut self, description: impl Into<String>) -> Self {
self.description = Some(description.into());
self
}
pub fn tag(mut self, tag: impl Into<String>) -> Self {
self.tags.push(tag.into());
self
}
pub fn tags(mut self, tags: impl IntoIterator<Item = impl Into<String>>) -> Self {
self.tags.extend(tags.into_iter().map(|t| t.into()));
self
}
pub fn requires_manual_review(mut self) -> Self {
self.requires_manual_review = true;
self
}
pub fn destructive(mut self) -> Self {
self.is_destructive = true;
self.rollback_safe = false;
self
}
pub fn non_destructive(mut self) -> Self {
self.is_destructive = false;
self.rollback_safe = true;
self
}
pub fn depends_on(mut self, migration_id: impl Into<String>) -> Self {
self.dependencies.push(migration_id.into());
self
}
pub fn dependencies(mut self, deps: impl IntoIterator<Item = impl Into<String>>) -> Self {
self.dependencies.extend(deps.into_iter().map(|d| d.into()));
self
}
pub fn rollback_safe(mut self) -> Self {
self.rollback_safe = true;
self
}
pub fn not_rollback_safe(mut self) -> Self {
self.rollback_safe = false;
self
}
pub fn data_migration(id: impl Into<String>, name: impl Into<String>) -> Self {
Self::with_id(id)
.name(name)
.tag("data-migration")
.non_destructive()
.rollback_safe()
}
pub fn schema_patch(id: impl Into<String>, name: impl Into<String>) -> Self {
Self::with_id(id)
.name(name)
.tag("schema-patch")
.non_destructive()
.rollback_safe()
}
pub fn destructive_migration(id: impl Into<String>, name: impl Into<String>) -> Self {
Self::with_id(id)
.name(name)
.tag("destructive")
.destructive()
.requires_manual_review()
}
pub fn performance_optimization(id: impl Into<String>, name: impl Into<String>) -> Self {
Self::with_id(id)
.name(name)
.tag("performance")
.tag("optimization")
.non_destructive()
.rollback_safe()
}
pub fn security_patch(id: impl Into<String>, name: impl Into<String>) -> Self {
Self::with_id(id)
.name(name)
.tag("security")
.tag("patch")
.non_destructive()
.rollback_safe()
}
pub fn get_id(&self) -> Option<&String> {
self.id.as_ref()
}
pub fn get_name(&self) -> Option<&String> {
self.name.as_ref()
}
pub fn get_up_sql(&self) -> Option<&String> {
self.up_sql.as_ref()
}
pub fn get_down_sql(&self) -> Option<&String> {
self.down_sql.as_ref()
}
pub fn is_destructive(&self) -> bool {
self.is_destructive
}
pub fn is_manual_review_required(&self) -> bool {
self.requires_manual_review
}
pub fn is_rollback_safe(&self) -> bool {
self.rollback_safe
}
pub fn get_tags(&self) -> &[String] {
&self.tags
}
pub fn get_dependencies(&self) -> &[String] {
&self.dependencies
}
}
impl SchemaBuilder for CustomSqlBuilder {
type Output = Migration;
type Error = CustomSqlBuildError;
fn build(self) -> Result<Self::Output, Self::Error> {
if !self.is_valid() {
let errors = self.validation_errors();
return Err(CustomSqlBuildError::ValidationError(errors.join("; ")));
}
let id = self.id.unwrap();
let name = self.name.unwrap();
let up_sql = self.up_sql.unwrap();
let mut migration = Migration::new(id, name, up_sql);
if let Some(down_sql) = self.down_sql {
migration = migration.with_down(down_sql);
}
Ok(migration)
}
}
impl ValidatableBuilder for CustomSqlBuilder {
fn is_valid(&self) -> bool {
self.id.is_some()
&& self.name.is_some()
&& self.up_sql.is_some()
&& !self.id.as_ref().unwrap().trim().is_empty()
&& !self.name.as_ref().unwrap().trim().is_empty()
&& !self.up_sql.as_ref().unwrap().trim().is_empty()
}
fn validation_errors(&self) -> Vec<String> {
let mut errors = Vec::new();
if self.id.is_none() {
errors.push("Migration ID is required".to_string());
} else if let Some(ref id) = self.id {
if id.trim().is_empty() {
errors.push("Migration ID cannot be empty".to_string());
}
}
if self.name.is_none() {
errors.push("Migration name is required".to_string());
} else if let Some(ref name) = self.name {
if name.trim().is_empty() {
errors.push("Migration name cannot be empty".to_string());
}
}
if self.up_sql.is_none() {
errors.push("Up migration SQL is required".to_string());
} else if let Some(ref sql) = self.up_sql {
if sql.trim().is_empty() {
errors.push("Up migration SQL cannot be empty".to_string());
} else {
let validator = SqlValidator::new();
let validation_result = validator.validate(sql);
if !validation_result.is_valid {
errors.extend(validation_result.errors);
}
if !self.is_destructive && self.detect_destructive_operations(sql) {
errors.push("Migration contains destructive operations but is not marked as destructive".to_string());
}
}
}
if self.is_destructive && !self.requires_manual_review {
errors.push("Destructive migrations must require manual review".to_string());
}
if self
.dependencies
.contains(&self.id.as_ref().unwrap_or(&String::new()))
{
errors.push("Migration cannot depend on itself".to_string());
}
errors
}
}
impl CustomSqlBuilder {
fn detect_destructive_operations(&self, sql: &str) -> bool {
let destructive_patterns = [
r"(?i)\b(DROP|TRUNCATE|DELETE)\b",
r"(?i)\b(ALTER\s+TABLE.*DROP)\b",
r"(?i)\b(ALTER\s+TABLE.*MODIFY)\b",
];
destructive_patterns
.iter()
.any(|pattern| regex::Regex::new(pattern).unwrap().is_match(sql))
}
}
impl ConditionalBuilder for CustomSqlBuilder {
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
}
fn when_else<F, G>(mut self, condition: bool, if_true: F, if_false: G) -> Self
where
F: FnOnce(&mut Self),
G: FnOnce(&mut Self),
Self: Sized,
{
if condition {
if_true(&mut self);
} else {
if_false(&mut self);
}
self
}
}
impl InspectableBuilder for CustomSqlBuilder {
fn debug_info(&self) -> String {
format!(
"CustomSqlBuilder {{ id: {:?}, name: {:?}, up_sql: {:?}, down_sql: {:?}, tags: {:?}, destructive: {}, review_required: {} }}",
self.id, self.name, self.up_sql, self.down_sql, self.tags, self.is_destructive, self.requires_manual_review
)
}
fn summary(&self) -> String {
let mut parts = vec![format!(
"Custom SQL migration '{}'",
self.name.as_deref().unwrap_or("unnamed")
)];
if let Some(ref id) = self.id {
parts.push(format!("ID: {}", id));
}
if let Some(ref description) = self.description {
parts.push(format!("Description: {}", description));
}
if !self.tags.is_empty() {
parts.push(format!("Tags: {}", self.tags.join(", ")));
}
if self.is_destructive {
parts.push("DESTRUCTIVE".to_string());
}
if self.requires_manual_review {
parts.push("REQUIRES MANUAL REVIEW".to_string());
}
if !self.rollback_safe {
parts.push("NOT ROLLBACK SAFE".to_string());
}
if !self.dependencies.is_empty() {
parts.push(format!("Dependencies: {}", self.dependencies.join(", ")));
}
parts.join(", ")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_custom_sql_builder_basic() {
let migration = CustomSqlBuilder::new()
.id("001_add_custom_index")
.name("Add custom index for performance")
.up_sql("CREATE INDEX CONCURRENTLY idx_custom ON users(email)")
.down_sql("DROP INDEX IF EXISTS idx_custom")
.description("Adds a custom index to improve query performance")
.tag("performance")
.tag("index")
.build()
.unwrap();
assert_eq!(migration.id, "001_add_custom_index");
assert_eq!(migration.name, "Add custom index for performance");
assert!(migration.up_sql.contains("CREATE INDEX"));
assert!(migration.down_sql.unwrap().contains("DROP INDEX"));
}
#[test]
fn test_custom_sql_builder_validation() {
let result = CustomSqlBuilder::new()
.name("test")
.up_sql("SELECT 1")
.build();
assert!(matches!(
result,
Err(CustomSqlBuildError::ValidationError(_))
));
let result = CustomSqlBuilder::new().id("001").up_sql("SELECT 1").build();
assert!(matches!(
result,
Err(CustomSqlBuildError::ValidationError(_))
));
let result = CustomSqlBuilder::new().id("001").name("test").build();
assert!(matches!(
result,
Err(CustomSqlBuildError::ValidationError(_))
));
}
#[test]
fn test_custom_sql_builder_convenience_methods() {
let data_migration = CustomSqlBuilder::data_migration("002", "Update user data")
.up_sql("UPDATE users SET status = 'active' WHERE status IS NULL")
.down_sql("UPDATE users SET status = NULL WHERE status = 'active'")
.build()
.unwrap();
assert_eq!(data_migration.id, "002");
assert_eq!(data_migration.name, "Update user data");
let destructive = CustomSqlBuilder::destructive_migration("003", "Drop old table")
.up_sql("DROP TABLE old_data")
.build()
.unwrap();
assert_eq!(destructive.id, "003");
assert_eq!(destructive.name, "Drop old table");
}
}