ignis-db 0.2.0

A comprehensive PostgreSQL ORM with macro-driven schema management
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
//! Custom SQL migration builder for handling patches and custom database operations
//!
//! This module provides a builder for creating custom SQL migrations that can handle
//! any database operation that the standard builders cannot accommodate.

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;

/// Builder for constructing custom SQL migrations
#[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 {
    /// Create a new custom SQL migration builder
    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,
        }
    }

    /// Create a custom SQL migration with a specific ID
    pub fn with_id(id: impl Into<String>) -> Self {
        Self::new().id(id)
    }

    /// Set the migration ID
    pub fn id(mut self, id: impl Into<String>) -> Self {
        self.id = Some(id.into());
        self
    }

    /// Set the migration name
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Set the up migration SQL
    pub fn up_sql(mut self, sql: impl Into<String>) -> Self {
        self.up_sql = Some(sql.into());
        self
    }

    /// Set the down migration SQL (rollback)
    pub fn down_sql(mut self, sql: impl Into<String>) -> Self {
        self.down_sql = Some(sql.into());
        self
    }

    /// Set a description for the migration
    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }

    /// Add a tag to the migration
    pub fn tag(mut self, tag: impl Into<String>) -> Self {
        self.tags.push(tag.into());
        self
    }

    /// Add multiple tags to the migration
    pub fn tags(mut self, tags: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.tags.extend(tags.into_iter().map(|t| t.into()));
        self
    }

    /// Mark the migration as requiring manual review
    pub fn requires_manual_review(mut self) -> Self {
        self.requires_manual_review = true;
        self
    }

    /// Mark the migration as destructive (will cause data loss)
    pub fn destructive(mut self) -> Self {
        self.is_destructive = true;
        self.rollback_safe = false;
        self
    }

    /// Mark the migration as non-destructive
    pub fn non_destructive(mut self) -> Self {
        self.is_destructive = false;
        self.rollback_safe = true;
        self
    }

    /// Add a dependency on another migration
    pub fn depends_on(mut self, migration_id: impl Into<String>) -> Self {
        self.dependencies.push(migration_id.into());
        self
    }

    /// Add multiple dependencies
    pub fn dependencies(mut self, deps: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.dependencies.extend(deps.into_iter().map(|d| d.into()));
        self
    }

    /// Mark the migration as rollback-safe
    pub fn rollback_safe(mut self) -> Self {
        self.rollback_safe = true;
        self
    }

    /// Mark the migration as not rollback-safe
    pub fn not_rollback_safe(mut self) -> Self {
        self.rollback_safe = false;
        self
    }

    /// Convenience method for creating a data migration
    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()
    }

    /// Convenience method for creating a schema patch
    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()
    }

    /// Convenience method for creating a destructive migration
    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()
    }

    /// Convenience method for creating a performance optimization
    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()
    }

    /// Convenience method for creating a security patch
    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()
    }

    /// Get the migration ID
    pub fn get_id(&self) -> Option<&String> {
        self.id.as_ref()
    }

    /// Get the migration name
    pub fn get_name(&self) -> Option<&String> {
        self.name.as_ref()
    }

    /// Get the up SQL
    pub fn get_up_sql(&self) -> Option<&String> {
        self.up_sql.as_ref()
    }

    /// Get the down SQL
    pub fn get_down_sql(&self) -> Option<&String> {
        self.down_sql.as_ref()
    }

    /// Check if the migration is destructive
    pub fn is_destructive(&self) -> bool {
        self.is_destructive
    }

    /// Check if the migration requires manual review
    pub fn is_manual_review_required(&self) -> bool {
        self.requires_manual_review
    }

    /// Check if the migration is rollback-safe
    pub fn is_rollback_safe(&self) -> bool {
        self.rollback_safe
    }

    /// Get all tags
    pub fn get_tags(&self) -> &[String] {
        &self.tags
    }

    /// Get all dependencies
    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> {
        // Validate the migration before building
        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);

        // Add down SQL if provided
        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 {
                // Enhanced SQL validation
                let validator = SqlValidator::new();
                let validation_result = validator.validate(sql);

                if !validation_result.is_valid {
                    errors.extend(validation_result.errors);
                }

                // Check for destructive operations if not marked as destructive
                if !self.is_destructive && self.detect_destructive_operations(sql) {
                    errors.push("Migration contains destructive operations but is not marked as destructive".to_string());
                }
            }
        }

        // Validate that destructive migrations have proper warnings
        if self.is_destructive && !self.requires_manual_review {
            errors.push("Destructive migrations must require manual review".to_string());
        }

        // Validate dependencies don't create circular references
        if self
            .dependencies
            .contains(&self.id.as_ref().unwrap_or(&String::new()))
        {
            errors.push("Migration cannot depend on itself".to_string());
        }

        errors
    }
}

impl CustomSqlBuilder {
    /// Detect destructive operations in SQL
    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() {
        // Missing ID should fail
        let result = CustomSqlBuilder::new()
            .name("test")
            .up_sql("SELECT 1")
            .build();
        assert!(matches!(
            result,
            Err(CustomSqlBuildError::ValidationError(_))
        ));

        // Missing name should fail
        let result = CustomSqlBuilder::new().id("001").up_sql("SELECT 1").build();
        assert!(matches!(
            result,
            Err(CustomSqlBuildError::ValidationError(_))
        ));

        // Missing up SQL should fail
        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");
    }
}