Skip to main content

ignis_db/migrate/
ddl_validator.rs

1//! DDL Validation System
2//!
3//! This module provides comprehensive validation of generated SQL DDL statements
4//! before execution, ensuring schema integrity and preventing malformed migrations.
5//!
6//! Uses existing common utilities for SQL safety and sqlx for database validation.
7
8use anyhow::{anyhow, Result};
9use sqlx::postgres::PgConnection;
10
11use crate::common::validate_identifier;
12
13/// DDL validation context containing validation rules and settings
14#[derive(Debug, Clone)]
15pub struct DdlValidationContext {
16    /// Maximum identifier length allowed
17    pub max_identifier_length: usize,
18    /// Maximum column name length
19    pub max_column_name_length: usize,
20    /// Allowed data types for columns
21    pub allowed_data_types: Vec<String>,
22    /// Forbidden identifier patterns
23    pub forbidden_patterns: Vec<String>,
24    /// Strict mode - reject any warnings
25    pub strict_mode: bool,
26}
27
28impl Default for DdlValidationContext {
29    fn default() -> Self {
30        Self {
31            max_identifier_length: 63, // PostgreSQL limit
32            max_column_name_length: 63,
33            allowed_data_types: vec![
34                "INTEGER",
35                "BIGINT",
36                "SMALLINT",
37                "SERIAL",
38                "BIGSERIAL",
39                "SMALLSERIAL",
40                "TEXT",
41                "VARCHAR",
42                "CHAR",
43                "UUID",
44                "BOOLEAN",
45                "REAL",
46                "DOUBLE PRECISION",
47                "NUMERIC",
48                "DECIMAL",
49                "TIMESTAMP",
50                "TIMESTAMPTZ",
51                "DATE",
52                "TIME",
53                "JSON",
54                "JSONB",
55                "BYTEA",
56                "ARRAY",
57                "INTERVAL",
58                "MONEY",
59                "BIT",
60                "BIT VARYING",
61            ]
62            .into_iter()
63            .map(|s| s.to_string())
64            .collect(),
65            forbidden_patterns: vec![
66                "TRUNCATE",
67                "ALTER SYSTEM",
68                "GRANT",
69                "REVOKE",
70                "CREATE USER",
71                "CREATE ROLE",
72                "CREATE DATABASE",
73                "VACUUM",
74                "ANALYZE",
75                "REINDEX",
76            ]
77            .into_iter()
78            .map(|s| s.to_string())
79            .collect(),
80            strict_mode: false,
81        }
82    }
83}
84
85/// DDL validation result containing validation status and details
86#[derive(Debug, Clone)]
87pub struct DdlValidationResult {
88    /// Whether the DDL is valid
89    pub is_valid: bool,
90    /// List of validation errors
91    pub errors: Vec<String>,
92    /// List of validation warnings
93    pub warnings: Vec<String>,
94    /// Validation context used
95    pub context: DdlValidationContext,
96    /// Database connection info (if validation was performed)
97    pub database_info: Option<DatabaseValidationInfo>,
98}
99
100/// Database validation information
101#[derive(Debug, Clone)]
102pub struct DatabaseValidationInfo {
103    /// Database version
104    pub version: String,
105    /// Current schema
106    pub current_schema: String,
107    /// Available extensions
108    pub extensions: Vec<String>,
109    /// Current user
110    pub current_user: String,
111    /// Current database
112    pub current_database: String,
113}
114
115/// Main DDL validator using sqlx for database validation
116pub struct DdlValidator {
117    context: DdlValidationContext,
118}
119
120impl DdlValidator {
121    /// Create a new DDL validator with the given context
122    pub fn new(context: DdlValidationContext) -> Self {
123        Self { context }
124    }
125
126    /// Create a new DDL validator with default context
127    pub fn new_default() -> Self {
128        Self::new(DdlValidationContext::default())
129    }
130
131    /// Validate a DDL SQL statement using database connection
132    pub async fn validate_ddl_with_db(
133        &self,
134        sql: &str,
135        connection: &mut PgConnection,
136    ) -> DdlValidationResult {
137        let mut result = DdlValidationResult {
138            is_valid: true,
139            errors: Vec::new(),
140            warnings: Vec::new(),
141            context: self.context.clone(),
142            database_info: None,
143        };
144
145        // 1. Basic SQL validation using common utilities
146        if let Err(e) = self.validate_basic_sql(sql, &mut result) {
147            result
148                .errors
149                .push(format!("Basic SQL validation failed: {}", e));
150            result.is_valid = false;
151            return result;
152        }
153
154        // 2. Database validation using sqlx
155        if let Err(e) = self
156            .validate_with_database(sql, connection, &mut result)
157            .await
158        {
159            result
160                .errors
161                .push(format!("Database validation failed: {}", e));
162            result.is_valid = false;
163        }
164
165        // 3. Check for forbidden patterns
166        self.check_forbidden_patterns(sql, &mut result);
167
168        // 4. Apply strict mode rules
169        if self.context.strict_mode && !result.warnings.is_empty() {
170            result.is_valid = false;
171            result
172                .errors
173                .push("Strict mode: warnings are treated as errors".to_string());
174        }
175
176        result
177    }
178
179    /// Validate DDL without database connection (basic validation only)
180    pub fn validate_ddl(&self, sql: &str) -> DdlValidationResult {
181        let mut result = DdlValidationResult {
182            is_valid: true,
183            errors: Vec::new(),
184            warnings: Vec::new(),
185            context: self.context.clone(),
186            database_info: None,
187        };
188
189        // Basic validation only using common utilities
190        if let Err(e) = self.validate_basic_sql(sql, &mut result) {
191            result
192                .errors
193                .push(format!("Basic SQL validation failed: {}", e));
194            result.is_valid = false;
195        }
196
197        self.check_forbidden_patterns(sql, &mut result);
198
199        if self.context.strict_mode && !result.warnings.is_empty() {
200            result.is_valid = false;
201            result
202                .errors
203                .push("Strict mode: warnings are treated as errors".to_string());
204        }
205
206        result
207    }
208
209    /// Validate basic SQL syntax and structure using common utilities
210    fn validate_basic_sql(&self, sql: &str, _result: &mut DdlValidationResult) -> Result<()> {
211        // Check for empty SQL
212        if sql.trim().is_empty() {
213            return Err(anyhow!("SQL statement is empty"));
214        }
215
216        // Check for dangerous patterns specific to DDL (not including CREATE, ALTER, DROP which are valid DDL keywords)
217        if self.contains_ddl_dangerous_patterns(sql) {
218            return Err(anyhow!("Dangerous DDL patterns detected in statement"));
219        }
220
221        // Check for forbidden patterns from context
222        let upper_sql = sql.to_uppercase();
223        for pattern in &self.context.forbidden_patterns {
224            if upper_sql.contains(pattern) {
225                return Err(anyhow!("Forbidden SQL pattern detected: {}", pattern));
226            }
227        }
228
229        // Check for balanced parentheses
230        if !self.check_balanced_parentheses(sql) {
231            return Err(anyhow!("Unbalanced parentheses in SQL"));
232        }
233
234        // Check for balanced quotes
235        if !self.check_balanced_quotes(sql) {
236            return Err(anyhow!("Unbalanced quotes in SQL"));
237        }
238
239        Ok(())
240    }
241
242    /// Validate DDL using actual database connection via sqlx
243    async fn validate_with_database(
244        &self,
245        sql: &str,
246        connection: &mut PgConnection,
247        result: &mut DdlValidationResult,
248    ) -> Result<()> {
249        // 1. Get database information
250        let db_info = self.get_database_info(connection).await?;
251        result.database_info = Some(db_info.clone());
252
253        // 2. Validate SQL syntax using EXPLAIN (PostgreSQL's built-in validator)
254        if let Err(e) = self.validate_sql_syntax(sql, connection).await {
255            result
256                .errors
257                .push(format!("SQL syntax validation failed: {}", e));
258            result.is_valid = false;
259        }
260
261        // 3. Check for potential schema conflicts
262        if let Err(e) = self.check_schema_conflicts(sql, connection).await {
263            result
264                .warnings
265                .push(format!("Potential schema conflict: {}", e));
266        }
267
268        // 4. Validate against current database state
269        if let Err(e) = self.validate_against_current_state(sql, connection).await {
270            result
271                .warnings
272                .push(format!("Database state validation: {}", e));
273        }
274
275        Ok(())
276    }
277
278    /// Get database information using sqlx
279    async fn get_database_info(
280        &self,
281        connection: &mut PgConnection,
282    ) -> Result<DatabaseValidationInfo> {
283        // Get PostgreSQL version
284        let version: String = sqlx::query_scalar("SELECT version()")
285            .fetch_one(&mut *connection)
286            .await?;
287
288        // Get current schema
289        let current_schema: String = sqlx::query_scalar("SELECT current_schema()")
290            .fetch_one(&mut *connection)
291            .await?;
292
293        // Get current user
294        let current_user: String = sqlx::query_scalar("SELECT current_user")
295            .fetch_one(&mut *connection)
296            .await?;
297
298        // Get current database
299        let current_database: String = sqlx::query_scalar("SELECT current_database()")
300            .fetch_one(&mut *connection)
301            .await?;
302
303        // Get available extensions
304        let extensions: Vec<String> =
305            sqlx::query_scalar("SELECT array_to_string(extname, ',') FROM pg_extension")
306                .fetch_all(&mut *connection)
307                .await?
308                .into_iter()
309                .filter_map(|row: Option<String>| row)
310                .collect();
311
312        Ok(DatabaseValidationInfo {
313            version,
314            current_schema,
315            extensions,
316            current_user,
317            current_database,
318        })
319    }
320
321    /// Validate SQL syntax using PostgreSQL's EXPLAIN
322    async fn validate_sql_syntax(&self, sql: &str, connection: &mut PgConnection) -> Result<()> {
323        // Use EXPLAIN to validate SQL syntax without executing
324        let explain_sql = format!("EXPLAIN {}", sql);
325
326        // This will fail if the SQL is malformed
327        sqlx::query(&explain_sql).execute(connection).await?;
328
329        Ok(())
330    }
331
332    /// Check for potential schema conflicts
333    async fn check_schema_conflicts(&self, sql: &str, connection: &mut PgConnection) -> Result<()> {
334        // Extract table name from SQL (simplified)
335        let table_name = self.extract_table_name(sql);
336
337        if let Some(name) = table_name {
338            // Check if table already exists
339            let exists: bool = sqlx::query_scalar(
340                "SELECT EXISTS(SELECT 1 FROM information_schema.tables WHERE table_name = $1)",
341            )
342            .bind(&name)
343            .fetch_one(&mut *connection)
344            .await?;
345
346            if exists {
347                return Err(anyhow!("Table '{}' already exists", name));
348            }
349        }
350
351        Ok(())
352    }
353
354    /// Validate against current database state
355    async fn validate_against_current_state(
356        &self,
357        _sql: &str,
358        connection: &mut PgConnection,
359    ) -> Result<()> {
360        // Check if we have necessary permissions
361        let has_create_priv: bool =
362            sqlx::query_scalar("SELECT has_table_privilege(current_user, 'CREATE')")
363                .fetch_one(&mut *connection)
364                .await?;
365
366        if !has_create_priv {
367            return Err(anyhow!("User lacks CREATE privilege"));
368        }
369
370        // Check for active transactions
371        let active_transactions: i64 =
372            sqlx::query_scalar("SELECT count(*) FROM pg_stat_activity WHERE state = 'active'")
373                .fetch_one(&mut *connection)
374                .await?;
375
376        if active_transactions > 1 {
377            return Err(anyhow!(
378                "Active transactions detected - consider waiting for completion"
379            ));
380        }
381
382        Ok(())
383    }
384
385    /// Extract table name from SQL (simplified)
386    fn extract_table_name(&self, sql: &str) -> Option<String> {
387        let upper_sql = sql.to_uppercase();
388
389        if upper_sql.contains("CREATE TABLE") {
390            // Simple extraction - in production you'd want more sophisticated parsing
391            let parts: Vec<&str> = sql.split_whitespace().collect();
392            for (i, part) in parts.iter().enumerate() {
393                if part.to_uppercase() == "TABLE" && i + 1 < parts.len() {
394                    let table_name = parts[i + 1].trim_matches('"').to_string();
395
396                    // Use common utility to validate the extracted table name
397                    if let Some(validated_name) = validate_identifier(&table_name) {
398                        return Some(validated_name);
399                    } else {
400                        // If validation fails, return the original (will be caught later)
401                        return Some(table_name);
402                    }
403                }
404            }
405        }
406
407        None
408    }
409
410    /// Check for DDL-specific dangerous patterns (excluding valid DDL keywords)
411    fn contains_ddl_dangerous_patterns(&self, sql: &str) -> bool {
412        let upper_sql = sql.to_uppercase();
413
414        // Check for dangerous patterns that are NOT valid DDL keywords
415        if upper_sql.contains("UNION")
416            || upper_sql.contains("EXEC")
417            || upper_sql.contains("EXECUTE")
418            || upper_sql.contains("INJECTION")
419            || upper_sql.contains("SCRIPT")
420            || upper_sql.contains("JAVASCRIPT")
421        {
422            return true;
423        }
424
425        // Check for multiple statements (potential injection)
426        if sql.contains(';') && sql.matches(';').count() > 1 {
427            return true;
428        }
429
430        false
431    }
432
433    /// Check for forbidden patterns in SQL
434    fn check_forbidden_patterns(&self, sql: &str, result: &mut DdlValidationResult) {
435        let upper_sql = sql.to_uppercase();
436
437        for pattern in &self.context.forbidden_patterns {
438            if upper_sql.contains(pattern) {
439                result
440                    .errors
441                    .push(format!("Forbidden SQL pattern detected: {}", pattern));
442                result.is_valid = false;
443            }
444        }
445    }
446
447    /// Check if parentheses are balanced
448    fn check_balanced_parentheses(&self, sql: &str) -> bool {
449        let mut count = 0;
450        let mut in_string = false;
451        let mut escape_next = false;
452
453        for ch in sql.chars() {
454            if escape_next {
455                escape_next = false;
456                continue;
457            }
458
459            if ch == '\\' {
460                escape_next = true;
461                continue;
462            }
463
464            if ch == '\'' && !escape_next {
465                in_string = !in_string;
466                continue;
467            }
468
469            if !in_string {
470                match ch {
471                    '(' => count += 1,
472                    ')' => {
473                        if count == 0 {
474                            return false; // Unmatched closing parenthesis
475                        }
476                        count -= 1;
477                    }
478                    _ => {}
479                }
480            }
481        }
482
483        count == 0
484    }
485
486    /// Check if quotes are balanced
487    fn check_balanced_quotes(&self, sql: &str) -> bool {
488        let mut count = 0;
489        let mut escape_next = false;
490
491        for ch in sql.chars() {
492            if escape_next {
493                escape_next = false;
494                continue;
495            }
496
497            if ch == '\\' {
498                escape_next = true;
499                continue;
500            }
501
502            if ch == '\'' && !escape_next {
503                count += 1;
504            }
505        }
506
507        count % 2 == 0
508    }
509}
510
511/// Convenience function to validate DDL with default settings
512pub fn validate_ddl(sql: &str) -> DdlValidationResult {
513    let validator = DdlValidator::new_default();
514    validator.validate_ddl(sql)
515}
516
517/// Convenience function to validate DDL with custom context
518pub fn validate_ddl_with_context(sql: &str, context: DdlValidationContext) -> DdlValidationResult {
519    let validator = DdlValidator::new(context);
520    validator.validate_ddl(sql)
521}
522
523#[cfg(test)]
524mod tests {
525    use super::*;
526
527    #[test]
528    fn test_validate_create_table() {
529        let sql = r#"
530            CREATE TABLE users (
531                id SERIAL PRIMARY KEY,
532                name VARCHAR(255) NOT NULL,
533                email VARCHAR(255) UNIQUE NOT NULL,
534                created_at TIMESTAMPTZ DEFAULT NOW()
535            );
536        "#;
537
538        let result = validate_ddl(sql);
539        assert!(result.is_valid, "Valid CREATE TABLE should pass validation");
540        assert!(result.errors.is_empty(), "Should have no errors");
541    }
542
543    #[test]
544    fn test_validate_alter_table() {
545        let sql = "ALTER TABLE users ADD COLUMN last_login TIMESTAMPTZ;";
546
547        let result = validate_ddl(sql);
548        assert!(result.is_valid, "Valid ALTER TABLE should pass validation");
549    }
550
551    #[test]
552    fn test_validate_drop_table() {
553        let sql = "DROP TABLE users;";
554
555        let result = validate_ddl(sql);
556        assert!(result.is_valid, "Valid DROP TABLE should pass validation");
557    }
558
559    #[test]
560    fn test_validate_forbidden_patterns() {
561        let sql = "TRUNCATE TABLE users;";
562
563        let result = validate_ddl(sql);
564        assert!(
565            !result.is_valid,
566            "SQL with forbidden patterns should fail validation"
567        );
568        assert!(result
569            .errors
570            .iter()
571            .any(|e| e.contains("Forbidden SQL pattern")));
572    }
573
574    #[test]
575    fn test_validate_unbalanced_parentheses() {
576        let sql = "CREATE TABLE users (id INTEGER, name VARCHAR(255);";
577
578        let result = validate_ddl(sql);
579        assert!(
580            !result.is_valid,
581            "SQL with unbalanced parentheses should fail validation"
582        );
583        assert!(result
584            .errors
585            .iter()
586            .any(|e| e.contains("Unbalanced parentheses")));
587    }
588
589    #[test]
590    fn test_validate_unbalanced_quotes() {
591        let sql = "CREATE TABLE users (id INTEGER, name VARCHAR(255)); -- 'unclosed quote";
592
593        let result = validate_ddl(sql);
594        assert!(
595            !result.is_valid,
596            "SQL with unbalanced quotes should fail validation"
597        );
598        assert!(result
599            .errors
600            .iter()
601            .any(|e| e.contains("Unbalanced quotes")));
602    }
603
604    #[test]
605    fn test_validate_dangerous_patterns() {
606        let sql = "CREATE TABLE users UNION SELECT * FROM passwords;";
607
608        let result = validate_ddl(sql);
609        assert!(
610            !result.is_valid,
611            "SQL with dangerous patterns should fail validation"
612        );
613        assert!(result
614            .errors
615            .iter()
616            .any(|e| e.contains("Dangerous DDL patterns")));
617    }
618
619    #[test]
620    fn test_validate_multiple_statements() {
621        let sql = "CREATE TABLE users; DROP TABLE passwords;";
622
623        let result = validate_ddl(sql);
624        assert!(
625            !result.is_valid,
626            "SQL with multiple statements should fail validation"
627        );
628        assert!(result
629            .errors
630            .iter()
631            .any(|e| e.contains("Dangerous DDL patterns")));
632    }
633
634    #[test]
635    fn test_validate_strict_mode() {
636        let mut context = DdlValidationContext::default();
637        context.strict_mode = true;
638
639        let sql = "CREATE TABLE users (id INTEGER, name VARCHAR(255));";
640
641        let result = validate_ddl_with_context(sql, context);
642        assert!(
643            result.is_valid,
644            "Basic validation should pass even in strict mode"
645        );
646    }
647}