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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
//! DDL Validation System
//!
//! This module provides comprehensive validation of generated SQL DDL statements
//! before execution, ensuring schema integrity and preventing malformed migrations.
//!
//! Uses existing common utilities for SQL safety and sqlx for database validation.

use anyhow::{anyhow, Result};
use sqlx::postgres::PgConnection;

use crate::common::validate_identifier;

/// DDL validation context containing validation rules and settings
#[derive(Debug, Clone)]
pub struct DdlValidationContext {
    /// Maximum identifier length allowed
    pub max_identifier_length: usize,
    /// Maximum column name length
    pub max_column_name_length: usize,
    /// Allowed data types for columns
    pub allowed_data_types: Vec<String>,
    /// Forbidden identifier patterns
    pub forbidden_patterns: Vec<String>,
    /// Strict mode - reject any warnings
    pub strict_mode: bool,
}

impl Default for DdlValidationContext {
    fn default() -> Self {
        Self {
            max_identifier_length: 63, // PostgreSQL limit
            max_column_name_length: 63,
            allowed_data_types: vec![
                "INTEGER",
                "BIGINT",
                "SMALLINT",
                "SERIAL",
                "BIGSERIAL",
                "SMALLSERIAL",
                "TEXT",
                "VARCHAR",
                "CHAR",
                "UUID",
                "BOOLEAN",
                "REAL",
                "DOUBLE PRECISION",
                "NUMERIC",
                "DECIMAL",
                "TIMESTAMP",
                "TIMESTAMPTZ",
                "DATE",
                "TIME",
                "JSON",
                "JSONB",
                "BYTEA",
                "ARRAY",
                "INTERVAL",
                "MONEY",
                "BIT",
                "BIT VARYING",
            ]
            .into_iter()
            .map(|s| s.to_string())
            .collect(),
            forbidden_patterns: vec![
                "TRUNCATE",
                "ALTER SYSTEM",
                "GRANT",
                "REVOKE",
                "CREATE USER",
                "CREATE ROLE",
                "CREATE DATABASE",
                "VACUUM",
                "ANALYZE",
                "REINDEX",
            ]
            .into_iter()
            .map(|s| s.to_string())
            .collect(),
            strict_mode: false,
        }
    }
}

/// DDL validation result containing validation status and details
#[derive(Debug, Clone)]
pub struct DdlValidationResult {
    /// Whether the DDL is valid
    pub is_valid: bool,
    /// List of validation errors
    pub errors: Vec<String>,
    /// List of validation warnings
    pub warnings: Vec<String>,
    /// Validation context used
    pub context: DdlValidationContext,
    /// Database connection info (if validation was performed)
    pub database_info: Option<DatabaseValidationInfo>,
}

/// Database validation information
#[derive(Debug, Clone)]
pub struct DatabaseValidationInfo {
    /// Database version
    pub version: String,
    /// Current schema
    pub current_schema: String,
    /// Available extensions
    pub extensions: Vec<String>,
    /// Current user
    pub current_user: String,
    /// Current database
    pub current_database: String,
}

/// Main DDL validator using sqlx for database validation
pub struct DdlValidator {
    context: DdlValidationContext,
}

impl DdlValidator {
    /// Create a new DDL validator with the given context
    pub fn new(context: DdlValidationContext) -> Self {
        Self { context }
    }

    /// Create a new DDL validator with default context
    pub fn new_default() -> Self {
        Self::new(DdlValidationContext::default())
    }

    /// Validate a DDL SQL statement using database connection
    pub async fn validate_ddl_with_db(
        &self,
        sql: &str,
        connection: &mut PgConnection,
    ) -> DdlValidationResult {
        let mut result = DdlValidationResult {
            is_valid: true,
            errors: Vec::new(),
            warnings: Vec::new(),
            context: self.context.clone(),
            database_info: None,
        };

        // 1. Basic SQL validation using common utilities
        if let Err(e) = self.validate_basic_sql(sql, &mut result) {
            result
                .errors
                .push(format!("Basic SQL validation failed: {}", e));
            result.is_valid = false;
            return result;
        }

        // 2. Database validation using sqlx
        if let Err(e) = self
            .validate_with_database(sql, connection, &mut result)
            .await
        {
            result
                .errors
                .push(format!("Database validation failed: {}", e));
            result.is_valid = false;
        }

        // 3. Check for forbidden patterns
        self.check_forbidden_patterns(sql, &mut result);

        // 4. Apply strict mode rules
        if self.context.strict_mode && !result.warnings.is_empty() {
            result.is_valid = false;
            result
                .errors
                .push("Strict mode: warnings are treated as errors".to_string());
        }

        result
    }

    /// Validate DDL without database connection (basic validation only)
    pub fn validate_ddl(&self, sql: &str) -> DdlValidationResult {
        let mut result = DdlValidationResult {
            is_valid: true,
            errors: Vec::new(),
            warnings: Vec::new(),
            context: self.context.clone(),
            database_info: None,
        };

        // Basic validation only using common utilities
        if let Err(e) = self.validate_basic_sql(sql, &mut result) {
            result
                .errors
                .push(format!("Basic SQL validation failed: {}", e));
            result.is_valid = false;
        }

        self.check_forbidden_patterns(sql, &mut result);

        if self.context.strict_mode && !result.warnings.is_empty() {
            result.is_valid = false;
            result
                .errors
                .push("Strict mode: warnings are treated as errors".to_string());
        }

        result
    }

    /// Validate basic SQL syntax and structure using common utilities
    fn validate_basic_sql(&self, sql: &str, _result: &mut DdlValidationResult) -> Result<()> {
        // Check for empty SQL
        if sql.trim().is_empty() {
            return Err(anyhow!("SQL statement is empty"));
        }

        // Check for dangerous patterns specific to DDL (not including CREATE, ALTER, DROP which are valid DDL keywords)
        if self.contains_ddl_dangerous_patterns(sql) {
            return Err(anyhow!("Dangerous DDL patterns detected in statement"));
        }

        // Check for forbidden patterns from context
        let upper_sql = sql.to_uppercase();
        for pattern in &self.context.forbidden_patterns {
            if upper_sql.contains(pattern) {
                return Err(anyhow!("Forbidden SQL pattern detected: {}", pattern));
            }
        }

        // Check for balanced parentheses
        if !self.check_balanced_parentheses(sql) {
            return Err(anyhow!("Unbalanced parentheses in SQL"));
        }

        // Check for balanced quotes
        if !self.check_balanced_quotes(sql) {
            return Err(anyhow!("Unbalanced quotes in SQL"));
        }

        Ok(())
    }

    /// Validate DDL using actual database connection via sqlx
    async fn validate_with_database(
        &self,
        sql: &str,
        connection: &mut PgConnection,
        result: &mut DdlValidationResult,
    ) -> Result<()> {
        // 1. Get database information
        let db_info = self.get_database_info(connection).await?;
        result.database_info = Some(db_info.clone());

        // 2. Validate SQL syntax using EXPLAIN (PostgreSQL's built-in validator)
        if let Err(e) = self.validate_sql_syntax(sql, connection).await {
            result
                .errors
                .push(format!("SQL syntax validation failed: {}", e));
            result.is_valid = false;
        }

        // 3. Check for potential schema conflicts
        if let Err(e) = self.check_schema_conflicts(sql, connection).await {
            result
                .warnings
                .push(format!("Potential schema conflict: {}", e));
        }

        // 4. Validate against current database state
        if let Err(e) = self.validate_against_current_state(sql, connection).await {
            result
                .warnings
                .push(format!("Database state validation: {}", e));
        }

        Ok(())
    }

    /// Get database information using sqlx
    async fn get_database_info(
        &self,
        connection: &mut PgConnection,
    ) -> Result<DatabaseValidationInfo> {
        // Get PostgreSQL version
        let version: String = sqlx::query_scalar("SELECT version()")
            .fetch_one(&mut *connection)
            .await?;

        // Get current schema
        let current_schema: String = sqlx::query_scalar("SELECT current_schema()")
            .fetch_one(&mut *connection)
            .await?;

        // Get current user
        let current_user: String = sqlx::query_scalar("SELECT current_user")
            .fetch_one(&mut *connection)
            .await?;

        // Get current database
        let current_database: String = sqlx::query_scalar("SELECT current_database()")
            .fetch_one(&mut *connection)
            .await?;

        // Get available extensions
        let extensions: Vec<String> =
            sqlx::query_scalar("SELECT array_to_string(extname, ',') FROM pg_extension")
                .fetch_all(&mut *connection)
                .await?
                .into_iter()
                .filter_map(|row: Option<String>| row)
                .collect();

        Ok(DatabaseValidationInfo {
            version,
            current_schema,
            extensions,
            current_user,
            current_database,
        })
    }

    /// Validate SQL syntax using PostgreSQL's EXPLAIN
    async fn validate_sql_syntax(&self, sql: &str, connection: &mut PgConnection) -> Result<()> {
        // Use EXPLAIN to validate SQL syntax without executing
        let explain_sql = format!("EXPLAIN {}", sql);

        // This will fail if the SQL is malformed
        sqlx::query(&explain_sql).execute(connection).await?;

        Ok(())
    }

    /// Check for potential schema conflicts
    async fn check_schema_conflicts(&self, sql: &str, connection: &mut PgConnection) -> Result<()> {
        // Extract table name from SQL (simplified)
        let table_name = self.extract_table_name(sql);

        if let Some(name) = table_name {
            // Check if table already exists
            let exists: bool = sqlx::query_scalar(
                "SELECT EXISTS(SELECT 1 FROM information_schema.tables WHERE table_name = $1)",
            )
            .bind(&name)
            .fetch_one(&mut *connection)
            .await?;

            if exists {
                return Err(anyhow!("Table '{}' already exists", name));
            }
        }

        Ok(())
    }

    /// Validate against current database state
    async fn validate_against_current_state(
        &self,
        _sql: &str,
        connection: &mut PgConnection,
    ) -> Result<()> {
        // Check if we have necessary permissions
        let has_create_priv: bool =
            sqlx::query_scalar("SELECT has_table_privilege(current_user, 'CREATE')")
                .fetch_one(&mut *connection)
                .await?;

        if !has_create_priv {
            return Err(anyhow!("User lacks CREATE privilege"));
        }

        // Check for active transactions
        let active_transactions: i64 =
            sqlx::query_scalar("SELECT count(*) FROM pg_stat_activity WHERE state = 'active'")
                .fetch_one(&mut *connection)
                .await?;

        if active_transactions > 1 {
            return Err(anyhow!(
                "Active transactions detected - consider waiting for completion"
            ));
        }

        Ok(())
    }

    /// Extract table name from SQL (simplified)
    fn extract_table_name(&self, sql: &str) -> Option<String> {
        let upper_sql = sql.to_uppercase();

        if upper_sql.contains("CREATE TABLE") {
            // Simple extraction - in production you'd want more sophisticated parsing
            let parts: Vec<&str> = sql.split_whitespace().collect();
            for (i, part) in parts.iter().enumerate() {
                if part.to_uppercase() == "TABLE" && i + 1 < parts.len() {
                    let table_name = parts[i + 1].trim_matches('"').to_string();

                    // Use common utility to validate the extracted table name
                    if let Some(validated_name) = validate_identifier(&table_name) {
                        return Some(validated_name);
                    } else {
                        // If validation fails, return the original (will be caught later)
                        return Some(table_name);
                    }
                }
            }
        }

        None
    }

    /// Check for DDL-specific dangerous patterns (excluding valid DDL keywords)
    fn contains_ddl_dangerous_patterns(&self, sql: &str) -> bool {
        let upper_sql = sql.to_uppercase();

        // Check for dangerous patterns that are NOT valid DDL keywords
        if upper_sql.contains("UNION")
            || upper_sql.contains("EXEC")
            || upper_sql.contains("EXECUTE")
            || upper_sql.contains("INJECTION")
            || upper_sql.contains("SCRIPT")
            || upper_sql.contains("JAVASCRIPT")
        {
            return true;
        }

        // Check for multiple statements (potential injection)
        if sql.contains(';') && sql.matches(';').count() > 1 {
            return true;
        }

        false
    }

    /// Check for forbidden patterns in SQL
    fn check_forbidden_patterns(&self, sql: &str, result: &mut DdlValidationResult) {
        let upper_sql = sql.to_uppercase();

        for pattern in &self.context.forbidden_patterns {
            if upper_sql.contains(pattern) {
                result
                    .errors
                    .push(format!("Forbidden SQL pattern detected: {}", pattern));
                result.is_valid = false;
            }
        }
    }

    /// Check if parentheses are balanced
    fn check_balanced_parentheses(&self, sql: &str) -> bool {
        let mut count = 0;
        let mut in_string = false;
        let mut escape_next = false;

        for ch in sql.chars() {
            if escape_next {
                escape_next = false;
                continue;
            }

            if ch == '\\' {
                escape_next = true;
                continue;
            }

            if ch == '\'' && !escape_next {
                in_string = !in_string;
                continue;
            }

            if !in_string {
                match ch {
                    '(' => count += 1,
                    ')' => {
                        if count == 0 {
                            return false; // Unmatched closing parenthesis
                        }
                        count -= 1;
                    }
                    _ => {}
                }
            }
        }

        count == 0
    }

    /// Check if quotes are balanced
    fn check_balanced_quotes(&self, sql: &str) -> bool {
        let mut count = 0;
        let mut escape_next = false;

        for ch in sql.chars() {
            if escape_next {
                escape_next = false;
                continue;
            }

            if ch == '\\' {
                escape_next = true;
                continue;
            }

            if ch == '\'' && !escape_next {
                count += 1;
            }
        }

        count % 2 == 0
    }
}

/// Convenience function to validate DDL with default settings
pub fn validate_ddl(sql: &str) -> DdlValidationResult {
    let validator = DdlValidator::new_default();
    validator.validate_ddl(sql)
}

/// Convenience function to validate DDL with custom context
pub fn validate_ddl_with_context(sql: &str, context: DdlValidationContext) -> DdlValidationResult {
    let validator = DdlValidator::new(context);
    validator.validate_ddl(sql)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_validate_create_table() {
        let sql = r#"
            CREATE TABLE users (
                id SERIAL PRIMARY KEY,
                name VARCHAR(255) NOT NULL,
                email VARCHAR(255) UNIQUE NOT NULL,
                created_at TIMESTAMPTZ DEFAULT NOW()
            );
        "#;

        let result = validate_ddl(sql);
        assert!(result.is_valid, "Valid CREATE TABLE should pass validation");
        assert!(result.errors.is_empty(), "Should have no errors");
    }

    #[test]
    fn test_validate_alter_table() {
        let sql = "ALTER TABLE users ADD COLUMN last_login TIMESTAMPTZ;";

        let result = validate_ddl(sql);
        assert!(result.is_valid, "Valid ALTER TABLE should pass validation");
    }

    #[test]
    fn test_validate_drop_table() {
        let sql = "DROP TABLE users;";

        let result = validate_ddl(sql);
        assert!(result.is_valid, "Valid DROP TABLE should pass validation");
    }

    #[test]
    fn test_validate_forbidden_patterns() {
        let sql = "TRUNCATE TABLE users;";

        let result = validate_ddl(sql);
        assert!(
            !result.is_valid,
            "SQL with forbidden patterns should fail validation"
        );
        assert!(result
            .errors
            .iter()
            .any(|e| e.contains("Forbidden SQL pattern")));
    }

    #[test]
    fn test_validate_unbalanced_parentheses() {
        let sql = "CREATE TABLE users (id INTEGER, name VARCHAR(255);";

        let result = validate_ddl(sql);
        assert!(
            !result.is_valid,
            "SQL with unbalanced parentheses should fail validation"
        );
        assert!(result
            .errors
            .iter()
            .any(|e| e.contains("Unbalanced parentheses")));
    }

    #[test]
    fn test_validate_unbalanced_quotes() {
        let sql = "CREATE TABLE users (id INTEGER, name VARCHAR(255)); -- 'unclosed quote";

        let result = validate_ddl(sql);
        assert!(
            !result.is_valid,
            "SQL with unbalanced quotes should fail validation"
        );
        assert!(result
            .errors
            .iter()
            .any(|e| e.contains("Unbalanced quotes")));
    }

    #[test]
    fn test_validate_dangerous_patterns() {
        let sql = "CREATE TABLE users UNION SELECT * FROM passwords;";

        let result = validate_ddl(sql);
        assert!(
            !result.is_valid,
            "SQL with dangerous patterns should fail validation"
        );
        assert!(result
            .errors
            .iter()
            .any(|e| e.contains("Dangerous DDL patterns")));
    }

    #[test]
    fn test_validate_multiple_statements() {
        let sql = "CREATE TABLE users; DROP TABLE passwords;";

        let result = validate_ddl(sql);
        assert!(
            !result.is_valid,
            "SQL with multiple statements should fail validation"
        );
        assert!(result
            .errors
            .iter()
            .any(|e| e.contains("Dangerous DDL patterns")));
    }

    #[test]
    fn test_validate_strict_mode() {
        let mut context = DdlValidationContext::default();
        context.strict_mode = true;

        let sql = "CREATE TABLE users (id INTEGER, name VARCHAR(255));";

        let result = validate_ddl_with_context(sql, context);
        assert!(
            result.is_valid,
            "Basic validation should pass even in strict mode"
        );
    }
}