diesel-guard 0.10.0

Linter for dangerous Postgres migration patterns in Diesel and SQLx. Prevents downtime caused by unsafe schema changes.
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
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
use crate::checks::{Check, MigrationContext};
use crate::config::Config;
use crate::violation::Violation;
use camino::Utf8Path;
use pg_query::protobuf::node::Node as NodeEnum;
use rhai::{AST, Dynamic, Engine};
use std::sync::Arc;

/// Error encountered while loading or running a custom Rhai check script.
#[derive(thiserror::Error, Debug)]
#[error("{file}: {message}")]
pub struct ScriptError {
    pub file: String,
    pub message: String,
}

/// A custom check backed by a compiled Rhai script.
pub struct CustomCheck {
    name: &'static str,
    engine: Arc<Engine>,
    ast: AST,
}

impl CustomCheck {
    fn internal_error(&self, err: &dyn std::fmt::Display) -> Vec<Violation> {
        vec![Violation::new(
            format!("SCRIPT ERROR: {}", self.name),
            format!("Error in custom check '{}': {err}", self.name),
            "This is likely a diesel-guard bug. Please report it.",
        )]
    }
}

impl Check for CustomCheck {
    fn name(&self) -> &'static str {
        self.name
    }

    fn check(&self, node: &NodeEnum, config: &Config, ctx: &MigrationContext) -> Vec<Violation> {
        // Serialize the pg_query node to a Rhai Dynamic value via serde
        let dynamic_node = match rhai::serde::to_dynamic(node) {
            Ok(d) => d,
            Err(e) => return self.internal_error(&e),
        };

        let dynamic_config = match rhai::serde::to_dynamic(config) {
            Ok(d) => d,
            Err(e) => return self.internal_error(&e),
        };

        let dynamic_ctx = rhai::serde::to_dynamic(ctx).unwrap();

        let mut scope = rhai::Scope::new();
        scope.push("node", dynamic_node);
        scope.push("config", dynamic_config);
        scope.push("ctx", dynamic_ctx);

        match self
            .engine
            .eval_ast_with_scope::<Dynamic>(&mut scope, &self.ast)
        {
            Ok(result) => parse_script_result(self.name, result),
            Err(e) => {
                vec![Violation::new(
                    format!("SCRIPT ERROR: {}", self.name),
                    format!("Runtime error in custom check '{}': {e}", self.name),
                    "Fix the custom check script to eliminate the runtime error.",
                )]
            }
        }
    }
}

/// Parse the return value of a Rhai script into violations.
///
/// Accepted return types:
/// - `()` — no violation
/// - `#{ operation: "...", problem: "...", safe_alternative: "..." }` — one violation
/// - Array of maps — multiple violations
fn parse_script_result(check_name: &str, result: Dynamic) -> Vec<Violation> {
    if result.is_unit() {
        return vec![];
    }

    if result.is_map() {
        return match map_to_violation(check_name, result) {
            Some(v) => vec![v],
            None => vec![],
        };
    }

    if result.is_array() {
        return result
            .into_array()
            .unwrap_or_default()
            .into_iter()
            .filter_map(|v| map_to_violation(check_name, v))
            .collect();
    }

    vec![Violation::new(
        format!("SCRIPT ERROR: {check_name}"),
        format!(
            "Custom check returned {}, expected (), map, or array",
            result.type_name()
        ),
        "Fix the custom check script to return a valid type.",
    )]
}

/// Convert a Rhai map Dynamic to a Violation.
fn map_to_violation(check_name: &str, value: Dynamic) -> Option<Violation> {
    let map = value.try_cast::<rhai::Map>()?;

    let operation = map
        .get("operation")
        .and_then(|v| v.clone().into_string().ok());
    let problem = map
        .get("problem")
        .and_then(|v| v.clone().into_string().ok());
    let safe_alternative = map
        .get("safe_alternative")
        .and_then(|v| v.clone().into_string().ok());

    if let (Some(op), Some(prob), Some(alt)) = (operation, problem, safe_alternative) {
        Some(Violation::new(op, prob, alt))
    } else {
        let mut issues = Vec::new();
        for key in &["operation", "problem", "safe_alternative"] {
            match map.get(*key) {
                None => issues.push(format!("'{key}' is missing")),
                Some(v) if v.clone().into_string().is_err() => {
                    issues.push(format!("'{key}' must be a string (got {})", v.type_name()));
                }
                _ => {}
            }
        }
        Some(Violation::new(
            format!("SCRIPT ERROR: {check_name}"),
            format!(
                "Custom check returned an invalid map: {}",
                issues.join(", ")
            ),
            "Fix the custom check script to return all three required string keys.",
        ))
    }
}

/// Build a Rhai module exposing commonly needed pg_query protobuf enum constants.
///
/// Scripts access these as `pg::OBJECT_TABLE`, `pg::AT_ADD_COLUMN`, etc.
fn create_pg_constants_module() -> rhai::Module {
    use pg_query::protobuf::{AlterTableType, ConstrType, DropBehavior, ObjectType};

    let mut m = rhai::Module::new();

    // ObjectType — used by DropStmt.remove_type, RenameStmt.rename_type, etc.
    m.set_var("OBJECT_INDEX", ObjectType::ObjectIndex as i64);
    m.set_var("OBJECT_TABLE", ObjectType::ObjectTable as i64);
    m.set_var("OBJECT_COLUMN", ObjectType::ObjectColumn as i64);
    m.set_var("OBJECT_DATABASE", ObjectType::ObjectDatabase as i64);
    m.set_var("OBJECT_SCHEMA", ObjectType::ObjectSchema as i64);
    m.set_var("OBJECT_SEQUENCE", ObjectType::ObjectSequence as i64);
    m.set_var("OBJECT_VIEW", ObjectType::ObjectView as i64);
    m.set_var("OBJECT_FUNCTION", ObjectType::ObjectFunction as i64);
    m.set_var("OBJECT_EXTENSION", ObjectType::ObjectExtension as i64);
    m.set_var("OBJECT_TRIGGER", ObjectType::ObjectTrigger as i64);
    m.set_var("OBJECT_TYPE", ObjectType::ObjectType as i64);

    // AlterTableType — used by AlterTableCmd.subtype
    m.set_var("AT_ADD_COLUMN", AlterTableType::AtAddColumn as i64);
    m.set_var("AT_COLUMN_DEFAULT", AlterTableType::AtColumnDefault as i64);
    m.set_var("AT_DROP_NOT_NULL", AlterTableType::AtDropNotNull as i64);
    m.set_var("AT_SET_NOT_NULL", AlterTableType::AtSetNotNull as i64);
    m.set_var("AT_DROP_COLUMN", AlterTableType::AtDropColumn as i64);
    m.set_var(
        "AT_ALTER_COLUMN_TYPE",
        AlterTableType::AtAlterColumnType as i64,
    );
    m.set_var("AT_ADD_CONSTRAINT", AlterTableType::AtAddConstraint as i64);
    m.set_var(
        "AT_DROP_CONSTRAINT",
        AlterTableType::AtDropConstraint as i64,
    );
    m.set_var(
        "AT_VALIDATE_CONSTRAINT",
        AlterTableType::AtValidateConstraint as i64,
    );

    // ConstrType — used by Constraint.contype
    m.set_var("CONSTR_NOTNULL", ConstrType::ConstrNotnull as i64);
    m.set_var("CONSTR_DEFAULT", ConstrType::ConstrDefault as i64);
    m.set_var("CONSTR_IDENTITY", ConstrType::ConstrIdentity as i64);
    m.set_var("CONSTR_GENERATED", ConstrType::ConstrGenerated as i64);
    m.set_var("CONSTR_CHECK", ConstrType::ConstrCheck as i64);
    m.set_var("CONSTR_PRIMARY", ConstrType::ConstrPrimary as i64);
    m.set_var("CONSTR_UNIQUE", ConstrType::ConstrUnique as i64);
    m.set_var("CONSTR_EXCLUSION", ConstrType::ConstrExclusion as i64);
    m.set_var("CONSTR_FOREIGN", ConstrType::ConstrForeign as i64);

    // DropBehavior — used by DropStmt.behavior
    m.set_var("DROP_RESTRICT", DropBehavior::DropRestrict as i64);
    m.set_var("DROP_CASCADE", DropBehavior::DropCascade as i64);

    m
}

/// Create a sandboxed Rhai engine with safety limits.
fn create_engine() -> Engine {
    let mut engine = Engine::new();
    engine.set_max_operations(100_000);
    engine.set_max_string_size(10_000);
    engine.set_max_array_size(1_000);
    engine.set_max_map_size(1_000);
    engine.register_static_module("pg", create_pg_constants_module().into());
    engine
}

/// Load all `.rhai` files from a directory and compile them into custom checks.
///
/// Returns successfully compiled checks and any errors encountered.
/// Compilation errors are non-fatal — they're collected as `ScriptError`s.
pub fn load_custom_checks(
    dir: &Utf8Path,
    config: &crate::config::Config,
) -> (Vec<Box<dyn Check>>, Vec<ScriptError>) {
    let mut checks: Vec<Box<dyn Check>> = Vec::new();
    let mut errors: Vec<ScriptError> = Vec::new();

    let engine = Arc::new(create_engine());

    let read_dir = match std::fs::read_dir(dir) {
        Ok(rd) => rd,
        Err(e) => {
            errors.push(ScriptError {
                file: dir.to_string(),
                message: format!("Failed to read directory: {e}"),
            });
            return (checks, errors);
        }
    };

    let mut entries: Vec<_> = read_dir
        .filter_map(std::result::Result::ok)
        .filter(|entry| entry.path().extension().is_some_and(|ext| ext == "rhai"))
        .collect();

    // Sort for deterministic order
    entries.sort_by_key(std::fs::DirEntry::file_name);

    for entry in entries {
        let path = entry.path();
        let stem = path
            .file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or("unknown");

        // Skip scripts disabled via config
        if !config.is_check_enabled(stem) {
            continue;
        }

        let source = match std::fs::read_to_string(&path) {
            Ok(s) => s,
            Err(e) => {
                errors.push(ScriptError {
                    file: path.display().to_string(),
                    message: format!("Failed to read: {e}"),
                });
                continue;
            }
        };

        match engine.compile(&source) {
            Ok(ast) => {
                // Leak the name — finite: one per script at startup
                let name: &'static str = Box::leak(stem.to_string().into_boxed_str());
                checks.push(Box::new(CustomCheck {
                    name,
                    engine: Arc::clone(&engine),
                    ast,
                }));
            }
            Err(e) => {
                errors.push(ScriptError {
                    file: path.display().to_string(),
                    message: format!("Compilation error: {e}"),
                });
            }
        }
    }

    (checks, errors)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::checks::pg_helpers::extract_node;
    use std::fs;
    use tempfile::TempDir;

    /// Helper: run a script against a node and return violations.
    fn run_script(script: &str, sql: &str) -> Vec<Violation> {
        run_script_with_config(script, sql, &crate::config::Config::default())
    }

    /// Helper: run a script against a node with explicit config and return violations.
    fn run_script_with_config(
        script: &str,
        sql: &str,
        config: &crate::config::Config,
    ) -> Vec<Violation> {
        run_script_with_ctx(
            script,
            sql,
            config,
            &crate::checks::MigrationContext::default(),
        )
    }

    /// Helper: run a script against a node with explicit config and ctx and return violations.
    fn run_script_with_ctx(
        script: &str,
        sql: &str,
        config: &crate::config::Config,
        ctx: &crate::checks::MigrationContext,
    ) -> Vec<Violation> {
        let engine = Arc::new(create_engine());
        let ast = engine.compile(script).expect("script should compile");
        let name: &'static str = Box::leak("test_check".to_string().into_boxed_str());
        let check = CustomCheck { name, engine, ast };

        let stmts = crate::parser::parse(sql).expect("SQL should parse");
        let mut all_violations = Vec::new();
        for raw_stmt in &stmts {
            if let Some(node) = extract_node(raw_stmt) {
                all_violations.extend(check.check(node, config, ctx));
            }
        }
        all_violations
    }

    #[test]
    fn test_script_returns_unit_no_violations() {
        let violations = run_script(
            r"
            // Script that always returns unit (no violation)
            let stmt = node.CreateStmt;
            if stmt == () { return; }
            ",
            "CREATE INDEX idx ON t(id);",
        );
        assert!(violations.is_empty());
    }

    #[test]
    fn test_script_returns_map_one_violation() {
        let violations = run_script(
            r#"
            let stmt = node.IndexStmt;
            if stmt == () { return; }
            if !stmt.concurrent {
                #{
                    operation: "INDEX without CONCURRENTLY",
                    problem: "locks table",
                    safe_alternative: "use CONCURRENTLY"
                }
            }
            "#,
            "CREATE INDEX idx ON users(email);",
        );
        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].operation, "INDEX without CONCURRENTLY");
        assert_eq!(violations[0].problem, "locks table");
    }

    #[test]
    fn test_script_returns_array_multiple_violations() {
        let violations = run_script(
            r#"
            let stmt = node.IndexStmt;
            if stmt == () { return; }
            [
                #{ operation: "violation 1", problem: "p1", safe_alternative: "s1" },
                #{ operation: "violation 2", problem: "p2", safe_alternative: "s2" }
            ]
            "#,
            "CREATE INDEX idx ON users(email);",
        );
        assert_eq!(violations.len(), 2);
        assert_eq!(violations[0].operation, "violation 1");
        assert_eq!(violations[1].operation, "violation 2");
    }

    #[test]
    fn test_script_invalid_return_type_no_crash() {
        // Returning a string instead of map — should produce an error violation
        let violations = run_script(
            r#"
            "not a valid return type"
            "#,
            "CREATE INDEX idx ON users(email);",
        );
        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].operation, "SCRIPT ERROR: test_check");
    }

    #[test]
    fn test_script_infinite_loop_hits_max_operations() {
        // Engine's max_operations limit should kick in and surface as a SCRIPT ERROR
        let violations = run_script(
            r"
            loop { }
            ",
            "CREATE INDEX idx ON users(email);",
        );
        assert_eq!(
            violations.len(),
            1,
            "expected 1 SCRIPT ERROR, got: {violations:?}"
        );
        assert_eq!(violations[0].operation, "SCRIPT ERROR: test_check");
    }

    #[test]
    fn test_script_wrong_node_type_returns_unit() {
        // Script looks for CreateStmt but we give it an IndexStmt
        let violations = run_script(
            r#"
            let stmt = node.CreateStmt;
            if stmt == () { return; }
            #{ operation: "found", problem: "p", safe_alternative: "s" }
            "#,
            "CREATE INDEX idx ON users(email);",
        );
        assert!(violations.is_empty());
    }

    #[test]
    fn test_compilation_error_reported() {
        let engine = Arc::new(create_engine());
        let result = engine.compile("this is not valid rhai {{{");
        assert!(result.is_err());
    }

    #[test]
    fn test_load_custom_checks_from_directory() {
        let dir = TempDir::new().unwrap();
        let dir_path = Utf8Path::from_path(dir.path()).unwrap();

        // Write a valid check script
        fs::write(
            dir.path().join("require_concurrent.rhai"),
            r#"
            let stmt = node.IndexStmt;
            if stmt == () { return; }
            if !stmt.concurrent {
                #{ operation: "custom", problem: "no concurrently", safe_alternative: "use it" }
            }
            "#,
        )
        .unwrap();

        // Write an invalid script
        fs::write(dir.path().join("broken.rhai"), "this is not valid {{{").unwrap();

        // Write a non-rhai file (should be ignored)
        fs::write(dir.path().join("notes.txt"), "not a script").unwrap();

        let config = crate::config::Config::default();
        let (checks, errors) = load_custom_checks(dir_path, &config);

        // One valid check loaded
        assert_eq!(checks.len(), 1);
        assert_eq!(checks[0].name(), "require_concurrent");

        // One compilation error reported
        assert_eq!(errors.len(), 1);
        assert!(errors[0].file.contains("broken.rhai"));
    }

    #[test]
    fn test_empty_script_no_violations() {
        // An empty .rhai file evaluates to () — should produce no violations
        let violations = run_script("", "CREATE INDEX idx ON users(email);");
        assert!(violations.is_empty());
    }

    #[test]
    fn test_map_with_missing_keys_produces_error_violation() {
        // Map missing "safe_alternative" — should produce an error violation
        let violations = run_script(
            r#"
            #{ operation: "op", problem: "p" }
            "#,
            "CREATE INDEX idx ON users(email);",
        );
        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].operation, "SCRIPT ERROR: test_check");
        assert_eq!(
            violations[0].problem,
            "Custom check returned an invalid map: 'safe_alternative' is missing"
        );
    }

    #[test]
    fn test_map_with_misspelled_key_produces_error_violation() {
        // Typo: "safe_alterative" instead of "safe_alternative"
        let violations = run_script(
            r#"
            #{ operation: "op", problem: "p", safe_alterative: "s" }
            "#,
            "CREATE INDEX idx ON users(email);",
        );
        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].operation, "SCRIPT ERROR: test_check");
        assert_eq!(
            violations[0].problem,
            "Custom check returned an invalid map: 'safe_alternative' is missing"
        );
    }

    #[test]
    fn test_pg_constants_accessible_in_scripts() {
        let violations = run_script(
            r#"
            let stmt = node.DropStmt;
            if stmt == () { return; }
            if stmt.remove_type == pg::OBJECT_INDEX {
                #{ operation: "DROP INDEX", problem: "not concurrent", safe_alternative: "use CONCURRENTLY" }
            }
            "#,
            "DROP INDEX idx_users_email;",
        );
        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].operation, "DROP INDEX");
    }

    #[test]
    fn test_config_postgres_version_accessible_in_scripts() {
        let config = crate::config::Config {
            postgres_version: Some(14),
            ..Default::default()
        };
        // Script skips violation when postgres_version >= 14
        let violations = run_script_with_config(
            r#"
            let stmt = node.IndexStmt;
            if stmt == () { return; }
            if config.postgres_version != () && config.postgres_version >= 14 { return; }
            #{ operation: "INDEX without CONCURRENTLY", problem: "locks table", safe_alternative: "use CONCURRENTLY" }
            "#,
            "CREATE INDEX idx ON users(email);",
            &config,
        );
        assert!(violations.is_empty());

        // Same script with pg 10 should produce a violation
        let config_old = crate::config::Config {
            postgres_version: Some(10),
            ..Default::default()
        };
        let violations = run_script_with_config(
            r#"
            let stmt = node.IndexStmt;
            if stmt == () { return; }
            if config.postgres_version != () && config.postgres_version >= 14 { return; }
            #{ operation: "INDEX without CONCURRENTLY", problem: "locks table", safe_alternative: "use CONCURRENTLY" }
            "#,
            "CREATE INDEX idx ON users(email);",
            &config_old,
        );
        assert_eq!(violations.len(), 1);
    }

    #[test]
    fn test_pg_constants_no_match() {
        // Script checks for OBJECT_TABLE but SQL drops an index — should not match
        let violations = run_script(
            r#"
            let stmt = node.DropStmt;
            if stmt == () { return; }
            if stmt.remove_type == pg::OBJECT_TABLE {
                #{ operation: "DROP TABLE", problem: "dangerous", safe_alternative: "be careful" }
            }
            "#,
            "DROP INDEX idx_users_email;",
        );
        assert!(violations.is_empty());
    }

    #[test]
    fn test_load_custom_checks_respects_disable() {
        let dir = TempDir::new().unwrap();
        let dir_path = Utf8Path::from_path(dir.path()).unwrap();

        fs::write(dir.path().join("my_check.rhai"), r"return;").unwrap();

        let config = crate::config::Config {
            disable_checks: vec!["my_check".to_string()],
            ..Default::default()
        };

        let (checks, errors) = load_custom_checks(dir_path, &config);
        assert_eq!(checks.len(), 0);
        assert_eq!(errors.len(), 0);
    }

    #[test]
    fn test_load_custom_checks_nonexistent_directory() {
        let dir = TempDir::new().unwrap();
        let missing = dir.path().join("does_not_exist");
        let dir_path = Utf8Path::from_path(&missing).unwrap();
        let config = crate::config::Config::default();
        let (checks, errors) = load_custom_checks(dir_path, &config);
        assert_eq!(checks.len(), 0);
        assert_eq!(errors.len(), 1);
        assert!(errors[0].message.contains("Failed to read directory"));
    }

    #[test]
    fn test_ctx_run_in_transaction_false_no_violation() {
        // CONCURRENTLY outside a transaction — no violation
        let ctx = crate::checks::MigrationContext {
            run_in_transaction: false,
            no_transaction_hint: "",
        };
        let violations = run_script_with_ctx(
            r#"
            let stmt = node.IndexStmt;
            if stmt == () { return; }
            if stmt.concurrent && ctx.run_in_transaction {
                #{ operation: "CONCURRENTLY in transaction", problem: "will fail", safe_alternative: ctx.no_transaction_hint }
            }
            "#,
            "CREATE INDEX CONCURRENTLY idx ON users(email);",
            &crate::config::Config::default(),
            &ctx,
        );
        assert!(violations.is_empty());
    }

    #[test]
    fn test_ctx_run_in_transaction_true_produces_violation() {
        // CONCURRENTLY inside a transaction — should flag it
        let ctx = crate::checks::MigrationContext {
            run_in_transaction: true,
            no_transaction_hint: "Add -- diesel:no-transaction to the migration file.",
        };
        let violations = run_script_with_ctx(
            r#"
            let stmt = node.IndexStmt;
            if stmt == () { return; }
            if stmt.concurrent && ctx.run_in_transaction {
                #{
                    operation: "CONCURRENTLY in transaction",
                    problem: "will fail",
                    safe_alternative: ctx.no_transaction_hint
                }
            }
            "#,
            "CREATE INDEX CONCURRENTLY idx ON users(email);",
            &crate::config::Config::default(),
            &ctx,
        );
        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].operation, "CONCURRENTLY in transaction");
        assert!(
            violations[0]
                .safe_alternative
                .contains("diesel:no-transaction")
        );
    }

    #[test]
    fn test_load_custom_checks_unreadable_file() {
        let dir = TempDir::new().unwrap();
        let dir_path = Utf8Path::from_path(dir.path()).unwrap();

        // A directory at the .rhai path always fails fs::read_to_string,
        // even under root — unlike chmod 0o000 which root can bypass.
        let script_path = dir.path().join("unreadable.rhai");
        fs::create_dir(&script_path).unwrap();

        let config = crate::config::Config::default();
        let (checks, errors) = load_custom_checks(dir_path, &config);

        assert_eq!(checks.len(), 0);
        assert_eq!(errors.len(), 1);
        assert!(errors[0].message.contains("Failed to read"));
    }

    #[test]
    fn test_map_with_non_string_operation_field() {
        // operation is an integer, not a string — into_string() returns None,
        // so the match falls through to the error-violation arm in map_to_violation.
        let violations = run_script(
            r#"
            #{ operation: 42, problem: "p", safe_alternative: "s" }
            "#,
            "CREATE INDEX idx ON users(email);",
        );
        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].operation, "SCRIPT ERROR: test_check");
        assert_eq!(
            violations[0].problem,
            "Custom check returned an invalid map: 'operation' must be a string (got i64)"
        );
    }

    #[test]
    fn test_map_with_non_string_problem_field() {
        let violations = run_script(
            r#"#{ operation: "op", problem: 42, safe_alternative: "s" }"#,
            "CREATE INDEX idx ON users(email);",
        );
        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].operation, "SCRIPT ERROR: test_check");
        assert!(
            violations[0].problem.contains("'problem' must be a string"),
            "got: {}",
            violations[0].problem
        );
    }

    #[test]
    fn test_map_with_non_string_safe_alternative_field() {
        let violations = run_script(
            r#"#{ operation: "op", problem: "p", safe_alternative: false }"#,
            "CREATE INDEX idx ON users(email);",
        );
        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].operation, "SCRIPT ERROR: test_check");
        assert!(
            violations[0]
                .problem
                .contains("'safe_alternative' must be a string"),
            "got: {}",
            violations[0].problem
        );
    }

    fn make_test_check() -> CustomCheck {
        let engine = Arc::new(create_engine());
        let ast = engine.compile("()").expect("script should compile");
        let name: &'static str = Box::leak("test_check".to_string().into_boxed_str());
        CustomCheck { name, engine, ast }
    }

    #[test]
    fn test_internal_error_yields_script_error_violation() {
        let check = make_test_check();
        let violations = check.internal_error(&"boom");
        assert_eq!(violations.len(), 1);
        let v = &violations[0];
        assert_eq!(v.operation, "SCRIPT ERROR: test_check");
        assert_eq!(v.problem, "Error in custom check 'test_check': boom");
        assert_eq!(
            v.safe_alternative,
            "This is likely a diesel-guard bug. Please report it."
        );
    }

    #[test]
    fn test_script_runtime_error_yields_script_error_violation() {
        // Division by zero is a runtime error that does NOT contain "ErrorTerminated".
        // A broken script must not silently disable the safety check — it must surface
        // as a SCRIPT ERROR violation.
        let violations = run_script("1 / 0", "CREATE INDEX idx ON users(email);");
        assert_eq!(
            violations.len(),
            1,
            "expected 1 SCRIPT ERROR violation, got: {violations:?}"
        );
        let v = &violations[0];
        assert_eq!(v.operation, "SCRIPT ERROR: test_check");
        assert_eq!(
            v.problem,
            "Runtime error in custom check 'test_check': Division by zero: 1 / 0"
        );
        assert_eq!(
            v.safe_alternative,
            "Fix the custom check script to eliminate the runtime error."
        );
    }

    #[test]
    fn test_pg_alter_table_constraint_and_drop_constants_accessible() {
        // Verify one representative constant from each untested group:
        // AT_ADD_COLUMN (AlterTableType), CONSTR_PRIMARY (ConstrType), DROP_CASCADE (DropBehavior).
        let violations = run_script(
            r#"
            let at = pg::AT_ADD_COLUMN;
            let ct = pg::CONSTR_PRIMARY;
            let db = pg::DROP_CASCADE;
            if at == () || ct == () || db == () {
                return #{ operation: "MISSING CONSTANT", problem: "a pg constant was ()", safe_alternative: "" };
            }
            "#,
            "SELECT 1;",
        );
        assert!(
            violations.is_empty(),
            "All pg constants should be accessible, got: {violations:?}"
        );
    }
}