Skip to main content

ignis_db/builders/
custom_sql.rs

1//! Custom SQL migration builder for handling patches and custom database operations
2//!
3//! This module provides a builder for creating custom SQL migrations that can handle
4//! any database operation that the standard builders cannot accommodate.
5
6use crate::builders::sql_validation::SqlValidator;
7use crate::builders::traits::{
8    ConditionalBuilder, InspectableBuilder, SchemaBuilder, ValidatableBuilder,
9};
10use crate::builders::validation::CustomSqlBuildError;
11use crate::migrate::Migration;
12use anyhow::Result;
13
14/// Builder for constructing custom SQL migrations
15#[derive(Debug, Clone)]
16pub struct CustomSqlBuilder {
17    id: Option<String>,
18    name: Option<String>,
19    up_sql: Option<String>,
20    down_sql: Option<String>,
21    description: Option<String>,
22    tags: Vec<String>,
23    requires_manual_review: bool,
24    is_destructive: bool,
25    dependencies: Vec<String>,
26    rollback_safe: bool,
27}
28
29impl CustomSqlBuilder {
30    /// Create a new custom SQL migration builder
31    pub fn new() -> Self {
32        Self {
33            id: None,
34            name: None,
35            up_sql: None,
36            down_sql: None,
37            description: None,
38            tags: Vec::new(),
39            requires_manual_review: false,
40            is_destructive: false,
41            dependencies: Vec::new(),
42            rollback_safe: true,
43        }
44    }
45
46    /// Create a custom SQL migration with a specific ID
47    pub fn with_id(id: impl Into<String>) -> Self {
48        Self::new().id(id)
49    }
50
51    /// Set the migration ID
52    pub fn id(mut self, id: impl Into<String>) -> Self {
53        self.id = Some(id.into());
54        self
55    }
56
57    /// Set the migration name
58    pub fn name(mut self, name: impl Into<String>) -> Self {
59        self.name = Some(name.into());
60        self
61    }
62
63    /// Set the up migration SQL
64    pub fn up_sql(mut self, sql: impl Into<String>) -> Self {
65        self.up_sql = Some(sql.into());
66        self
67    }
68
69    /// Set the down migration SQL (rollback)
70    pub fn down_sql(mut self, sql: impl Into<String>) -> Self {
71        self.down_sql = Some(sql.into());
72        self
73    }
74
75    /// Set a description for the migration
76    pub fn description(mut self, description: impl Into<String>) -> Self {
77        self.description = Some(description.into());
78        self
79    }
80
81    /// Add a tag to the migration
82    pub fn tag(mut self, tag: impl Into<String>) -> Self {
83        self.tags.push(tag.into());
84        self
85    }
86
87    /// Add multiple tags to the migration
88    pub fn tags(mut self, tags: impl IntoIterator<Item = impl Into<String>>) -> Self {
89        self.tags.extend(tags.into_iter().map(|t| t.into()));
90        self
91    }
92
93    /// Mark the migration as requiring manual review
94    pub fn requires_manual_review(mut self) -> Self {
95        self.requires_manual_review = true;
96        self
97    }
98
99    /// Mark the migration as destructive (will cause data loss)
100    pub fn destructive(mut self) -> Self {
101        self.is_destructive = true;
102        self.rollback_safe = false;
103        self
104    }
105
106    /// Mark the migration as non-destructive
107    pub fn non_destructive(mut self) -> Self {
108        self.is_destructive = false;
109        self.rollback_safe = true;
110        self
111    }
112
113    /// Add a dependency on another migration
114    pub fn depends_on(mut self, migration_id: impl Into<String>) -> Self {
115        self.dependencies.push(migration_id.into());
116        self
117    }
118
119    /// Add multiple dependencies
120    pub fn dependencies(mut self, deps: impl IntoIterator<Item = impl Into<String>>) -> Self {
121        self.dependencies.extend(deps.into_iter().map(|d| d.into()));
122        self
123    }
124
125    /// Mark the migration as rollback-safe
126    pub fn rollback_safe(mut self) -> Self {
127        self.rollback_safe = true;
128        self
129    }
130
131    /// Mark the migration as not rollback-safe
132    pub fn not_rollback_safe(mut self) -> Self {
133        self.rollback_safe = false;
134        self
135    }
136
137    /// Convenience method for creating a data migration
138    pub fn data_migration(id: impl Into<String>, name: impl Into<String>) -> Self {
139        Self::with_id(id)
140            .name(name)
141            .tag("data-migration")
142            .non_destructive()
143            .rollback_safe()
144    }
145
146    /// Convenience method for creating a schema patch
147    pub fn schema_patch(id: impl Into<String>, name: impl Into<String>) -> Self {
148        Self::with_id(id)
149            .name(name)
150            .tag("schema-patch")
151            .non_destructive()
152            .rollback_safe()
153    }
154
155    /// Convenience method for creating a destructive migration
156    pub fn destructive_migration(id: impl Into<String>, name: impl Into<String>) -> Self {
157        Self::with_id(id)
158            .name(name)
159            .tag("destructive")
160            .destructive()
161            .requires_manual_review()
162    }
163
164    /// Convenience method for creating a performance optimization
165    pub fn performance_optimization(id: impl Into<String>, name: impl Into<String>) -> Self {
166        Self::with_id(id)
167            .name(name)
168            .tag("performance")
169            .tag("optimization")
170            .non_destructive()
171            .rollback_safe()
172    }
173
174    /// Convenience method for creating a security patch
175    pub fn security_patch(id: impl Into<String>, name: impl Into<String>) -> Self {
176        Self::with_id(id)
177            .name(name)
178            .tag("security")
179            .tag("patch")
180            .non_destructive()
181            .rollback_safe()
182    }
183
184    /// Get the migration ID
185    pub fn get_id(&self) -> Option<&String> {
186        self.id.as_ref()
187    }
188
189    /// Get the migration name
190    pub fn get_name(&self) -> Option<&String> {
191        self.name.as_ref()
192    }
193
194    /// Get the up SQL
195    pub fn get_up_sql(&self) -> Option<&String> {
196        self.up_sql.as_ref()
197    }
198
199    /// Get the down SQL
200    pub fn get_down_sql(&self) -> Option<&String> {
201        self.down_sql.as_ref()
202    }
203
204    /// Check if the migration is destructive
205    pub fn is_destructive(&self) -> bool {
206        self.is_destructive
207    }
208
209    /// Check if the migration requires manual review
210    pub fn is_manual_review_required(&self) -> bool {
211        self.requires_manual_review
212    }
213
214    /// Check if the migration is rollback-safe
215    pub fn is_rollback_safe(&self) -> bool {
216        self.rollback_safe
217    }
218
219    /// Get all tags
220    pub fn get_tags(&self) -> &[String] {
221        &self.tags
222    }
223
224    /// Get all dependencies
225    pub fn get_dependencies(&self) -> &[String] {
226        &self.dependencies
227    }
228}
229
230impl SchemaBuilder for CustomSqlBuilder {
231    type Output = Migration;
232    type Error = CustomSqlBuildError;
233
234    fn build(self) -> Result<Self::Output, Self::Error> {
235        // Validate the migration before building
236        if !self.is_valid() {
237            let errors = self.validation_errors();
238            return Err(CustomSqlBuildError::ValidationError(errors.join("; ")));
239        }
240
241        let id = self.id.unwrap();
242        let name = self.name.unwrap();
243        let up_sql = self.up_sql.unwrap();
244
245        let mut migration = Migration::new(id, name, up_sql);
246
247        // Add down SQL if provided
248        if let Some(down_sql) = self.down_sql {
249            migration = migration.with_down(down_sql);
250        }
251
252        Ok(migration)
253    }
254}
255
256impl ValidatableBuilder for CustomSqlBuilder {
257    fn is_valid(&self) -> bool {
258        self.id.is_some()
259            && self.name.is_some()
260            && self.up_sql.is_some()
261            && !self.id.as_ref().unwrap().trim().is_empty()
262            && !self.name.as_ref().unwrap().trim().is_empty()
263            && !self.up_sql.as_ref().unwrap().trim().is_empty()
264    }
265
266    fn validation_errors(&self) -> Vec<String> {
267        let mut errors = Vec::new();
268
269        if self.id.is_none() {
270            errors.push("Migration ID is required".to_string());
271        } else if let Some(ref id) = self.id {
272            if id.trim().is_empty() {
273                errors.push("Migration ID cannot be empty".to_string());
274            }
275        }
276
277        if self.name.is_none() {
278            errors.push("Migration name is required".to_string());
279        } else if let Some(ref name) = self.name {
280            if name.trim().is_empty() {
281                errors.push("Migration name cannot be empty".to_string());
282            }
283        }
284
285        if self.up_sql.is_none() {
286            errors.push("Up migration SQL is required".to_string());
287        } else if let Some(ref sql) = self.up_sql {
288            if sql.trim().is_empty() {
289                errors.push("Up migration SQL cannot be empty".to_string());
290            } else {
291                // Enhanced SQL validation
292                let validator = SqlValidator::new();
293                let validation_result = validator.validate(sql);
294
295                if !validation_result.is_valid {
296                    errors.extend(validation_result.errors);
297                }
298
299                // Check for destructive operations if not marked as destructive
300                if !self.is_destructive && self.detect_destructive_operations(sql) {
301                    errors.push("Migration contains destructive operations but is not marked as destructive".to_string());
302                }
303            }
304        }
305
306        // Validate that destructive migrations have proper warnings
307        if self.is_destructive && !self.requires_manual_review {
308            errors.push("Destructive migrations must require manual review".to_string());
309        }
310
311        // Validate dependencies don't create circular references
312        if self
313            .dependencies
314            .contains(&self.id.as_ref().unwrap_or(&String::new()))
315        {
316            errors.push("Migration cannot depend on itself".to_string());
317        }
318
319        errors
320    }
321}
322
323impl CustomSqlBuilder {
324    /// Detect destructive operations in SQL
325    fn detect_destructive_operations(&self, sql: &str) -> bool {
326        let destructive_patterns = [
327            r"(?i)\b(DROP|TRUNCATE|DELETE)\b",
328            r"(?i)\b(ALTER\s+TABLE.*DROP)\b",
329            r"(?i)\b(ALTER\s+TABLE.*MODIFY)\b",
330        ];
331
332        destructive_patterns
333            .iter()
334            .any(|pattern| regex::Regex::new(pattern).unwrap().is_match(sql))
335    }
336}
337
338impl ConditionalBuilder for CustomSqlBuilder {
339    fn when<F>(mut self, condition: bool, config_fn: F) -> Self
340    where
341        F: FnOnce(&mut Self),
342        Self: Sized,
343    {
344        if condition {
345            config_fn(&mut self);
346        }
347        self
348    }
349
350    fn when_else<F, G>(mut self, condition: bool, if_true: F, if_false: G) -> Self
351    where
352        F: FnOnce(&mut Self),
353        G: FnOnce(&mut Self),
354        Self: Sized,
355    {
356        if condition {
357            if_true(&mut self);
358        } else {
359            if_false(&mut self);
360        }
361        self
362    }
363}
364
365impl InspectableBuilder for CustomSqlBuilder {
366    fn debug_info(&self) -> String {
367        format!(
368            "CustomSqlBuilder {{ id: {:?}, name: {:?}, up_sql: {:?}, down_sql: {:?}, tags: {:?}, destructive: {}, review_required: {} }}",
369            self.id, self.name, self.up_sql, self.down_sql, self.tags, self.is_destructive, self.requires_manual_review
370        )
371    }
372
373    fn summary(&self) -> String {
374        let mut parts = vec![format!(
375            "Custom SQL migration '{}'",
376            self.name.as_deref().unwrap_or("unnamed")
377        )];
378
379        if let Some(ref id) = self.id {
380            parts.push(format!("ID: {}", id));
381        }
382
383        if let Some(ref description) = self.description {
384            parts.push(format!("Description: {}", description));
385        }
386
387        if !self.tags.is_empty() {
388            parts.push(format!("Tags: {}", self.tags.join(", ")));
389        }
390
391        if self.is_destructive {
392            parts.push("DESTRUCTIVE".to_string());
393        }
394
395        if self.requires_manual_review {
396            parts.push("REQUIRES MANUAL REVIEW".to_string());
397        }
398
399        if !self.rollback_safe {
400            parts.push("NOT ROLLBACK SAFE".to_string());
401        }
402
403        if !self.dependencies.is_empty() {
404            parts.push(format!("Dependencies: {}", self.dependencies.join(", ")));
405        }
406
407        parts.join(", ")
408    }
409}
410
411#[cfg(test)]
412mod tests {
413    use super::*;
414
415    #[test]
416    fn test_custom_sql_builder_basic() {
417        let migration = CustomSqlBuilder::new()
418            .id("001_add_custom_index")
419            .name("Add custom index for performance")
420            .up_sql("CREATE INDEX CONCURRENTLY idx_custom ON users(email)")
421            .down_sql("DROP INDEX IF EXISTS idx_custom")
422            .description("Adds a custom index to improve query performance")
423            .tag("performance")
424            .tag("index")
425            .build()
426            .unwrap();
427
428        assert_eq!(migration.id, "001_add_custom_index");
429        assert_eq!(migration.name, "Add custom index for performance");
430        assert!(migration.up_sql.contains("CREATE INDEX"));
431        assert!(migration.down_sql.unwrap().contains("DROP INDEX"));
432    }
433
434    #[test]
435    fn test_custom_sql_builder_validation() {
436        // Missing ID should fail
437        let result = CustomSqlBuilder::new()
438            .name("test")
439            .up_sql("SELECT 1")
440            .build();
441        assert!(matches!(
442            result,
443            Err(CustomSqlBuildError::ValidationError(_))
444        ));
445
446        // Missing name should fail
447        let result = CustomSqlBuilder::new().id("001").up_sql("SELECT 1").build();
448        assert!(matches!(
449            result,
450            Err(CustomSqlBuildError::ValidationError(_))
451        ));
452
453        // Missing up SQL should fail
454        let result = CustomSqlBuilder::new().id("001").name("test").build();
455        assert!(matches!(
456            result,
457            Err(CustomSqlBuildError::ValidationError(_))
458        ));
459    }
460
461    #[test]
462    fn test_custom_sql_builder_convenience_methods() {
463        let data_migration = CustomSqlBuilder::data_migration("002", "Update user data")
464            .up_sql("UPDATE users SET status = 'active' WHERE status IS NULL")
465            .down_sql("UPDATE users SET status = NULL WHERE status = 'active'")
466            .build()
467            .unwrap();
468
469        assert_eq!(data_migration.id, "002");
470        assert_eq!(data_migration.name, "Update user data");
471
472        let destructive = CustomSqlBuilder::destructive_migration("003", "Drop old table")
473            .up_sql("DROP TABLE old_data")
474            .build()
475            .unwrap();
476
477        assert_eq!(destructive.id, "003");
478        assert_eq!(destructive.name, "Drop old table");
479    }
480}