sql-splitter 1.17.0

High-performance CLI tool for splitting large SQL dump files into individual table files
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
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
//! CLI tests for `sql-splitter generate`.
//!
//! Two layers, matching the two places a conflict can be caught:
//!
//! - Pure clap-level conflicts (`conflicts_with`/`conflicts_with_all`) fail
//!   during [`Cli::try_parse_from`] itself, before any subcommand code runs.
//! - Value-conditional conflicts (e.g. `--json` claiming stdout at the same
//!   time as an explicit `--output -`) can't be expressed as a clap
//!   attribute, since `conflicts_with` only sees argument *presence*, not
//!   argument *values*. Those are rejected by
//!   `cmd::generate::GenerateArgs::try_into_request` instead, which is
//!   private to the `generate` module — so this layer is exercised end to
//!   end, as a subprocess, asserting on the process exit code (`2`, clap's
//!   own usage exit code, reused here so every usage rejection looks the
//!   same to a caller regardless of which layer caught it).

use std::fs;
use std::process::Command;

use clap::Parser;
use sql_splitter::cmd::Cli;

const SIMPLE_MODEL: &str = "tests/fixtures/generate/simple.yaml";

fn sql_splitter_bin() -> Command {
    Command::new(env!("CARGO_BIN_EXE_sql-splitter"))
}

#[test]
fn generate_benchmark_profiles_only_supported_depths_and_propagates_failures() {
    let script = include_str!("../scripts/benchmark-generate.sh");

    assert!(script.contains("for depth in basic full; do"));
    assert!(
        !script.contains("|| true"),
        "benchmark failures must make the harness fail"
    );
}

// ===========================================================================
// Clap-level conflicts
// ===========================================================================

#[test]
fn generate_cli_rejects_conflicting_modes_and_stdout_owners() {
    assert!(Cli::try_parse_from([
        "sql-splitter",
        "generate",
        "model.yaml",
        "--scale",
        "0.1",
        "--rows",
        "10"
    ])
    .is_err());

    assert!(Cli::try_parse_from([
        "sql-splitter",
        "generate",
        "model.yaml",
        "--check",
        "--dry-run"
    ])
    .is_err());

    assert!(Cli::try_parse_from([
        "sql-splitter",
        "generate",
        "model.yaml",
        "--seed",
        "1",
        "--randomize"
    ])
    .is_err());

    assert!(Cli::try_parse_from([
        "sql-splitter",
        "generate",
        "model.yaml",
        "--schema-only",
        "--data-only"
    ])
    .is_err());

    assert!(Cli::try_parse_from([
        "sql-splitter",
        "generate",
        "model.yaml",
        "--quiet",
        "--progress"
    ])
    .is_err());

    assert!(Cli::try_parse_from([
        "sql-splitter",
        "generate",
        "model.yaml",
        "--check",
        "--verify"
    ])
    .is_err());

    assert!(Cli::try_parse_from([
        "sql-splitter",
        "generate",
        "model.yaml",
        "--dry-run",
        "--verify"
    ])
    .is_err());
}

#[test]
fn generate_cli_parses_value_conditional_conflicts_clap_cannot_express() {
    // `--json --output -`: both a `--json` report and an explicit `-o -`
    // claim stdout. Clap's `conflicts_with` only tracks argument presence,
    // so it can't reject this by itself; it parses fine here and is instead
    // rejected by `try_into_request` (see the subprocess test below).
    assert!(Cli::try_parse_from([
        "sql-splitter",
        "generate",
        "model.yaml",
        "--json",
        "--output",
        "-"
    ])
    .is_ok());
}

// ===========================================================================
// End-to-end: usage conflicts caught post-clap (subprocess, exit code 2)
// ===========================================================================

#[test]
fn json_and_explicit_stdout_output_exit_with_usage_code() {
    let output = sql_splitter_bin()
        .args([
            "generate",
            "--config",
            SIMPLE_MODEL,
            "--json",
            "--output",
            "-",
        ])
        .output()
        .expect("failed to run sql-splitter");

    assert_eq!(output.status.code(), Some(2));
}

#[test]
fn json_generate_without_an_output_file_exits_with_usage_code() {
    // `generate --json` with no `-o` would render SQL and then discard it;
    // require a real output file (or --check/--dry-run) instead of silent loss.
    let output = sql_splitter_bin()
        .args(["generate", "--config", SIMPLE_MODEL, "--json"])
        .output()
        .expect("failed to run sql-splitter");

    assert_eq!(output.status.code(), Some(2));
}

#[test]
fn json_and_explicit_emit_config_stdout_exit_with_usage_code() {
    // `--json` (the report) and `--emit-config -` both claim stdout; this
    // usage rejection must fire before `--emit-config`'s "not available
    // yet" error (exit `1`), so the exit code here is `2`, not `1`.
    let output = sql_splitter_bin()
        .args([
            "generate",
            "--config",
            SIMPLE_MODEL,
            "--json",
            "--emit-config",
            "-",
        ])
        .output()
        .expect("failed to run sql-splitter");

    assert_eq!(output.status.code(), Some(2));
}

#[test]
fn explicit_stdout_sql_and_emit_config_stdout_exit_with_usage_code() {
    // Both generated SQL (`-o -`) and the emitted model (`--emit-config -`)
    // claim stdout at once — a collision `try_into_request` rejects with the
    // usage exit code `2`.
    let output = sql_splitter_bin()
        .args([
            "generate",
            "--config",
            SIMPLE_MODEL,
            "--emit-config",
            "-",
            "-o",
            "-",
        ])
        .output()
        .expect("failed to run sql-splitter");

    assert_eq!(output.status.code(), Some(2));
}

#[test]
fn emit_config_stdout_without_sql_output_emits_the_model() {
    // `--emit-config -` with no `-o` writes the resolved model to stdout and
    // generates no SQL — a valid EmitModel run, not a stdout collision.
    let output = sql_splitter_bin()
        .args(["generate", "--config", SIMPLE_MODEL, "--emit-config", "-"])
        .output()
        .expect("failed to run sql-splitter");

    assert_eq!(
        output.status.code(),
        Some(0),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("kind: model"), "stdout: {stdout}");
    assert!(!stdout.contains("INSERT INTO"), "stdout: {stdout}");
}

#[test]
fn check_with_an_input_dump_exits_with_usage_code() {
    let output = sql_splitter_bin()
        .args(["generate", "dump.sql", "--check"])
        .output()
        .expect("failed to run sql-splitter");

    assert_eq!(output.status.code(), Some(2));
    let stderr = String::from_utf8(output.stderr).expect("stderr is valid UTF-8");
    let normalized = stderr.to_ascii_lowercase();
    assert!(!normalized.contains("phase"), "stderr: {stderr}");
    assert!(!normalized.contains("task"), "stderr: {stderr}");
}

#[test]
fn check_without_a_config_exits_with_usage_code() {
    let output = sql_splitter_bin()
        .args(["generate", "--check"])
        .output()
        .expect("failed to run sql-splitter");

    assert_eq!(output.status.code(), Some(2));
    let stderr = String::from_utf8(output.stderr).expect("stderr is valid UTF-8");
    assert!(stderr.contains("--config"), "stderr: {stderr}");
}

#[test]
fn verify_without_a_real_output_file_exits_with_usage_code() {
    let output = sql_splitter_bin()
        .args(["generate", "--config", SIMPLE_MODEL, "--verify"])
        .output()
        .expect("failed to run sql-splitter");

    assert_eq!(output.status.code(), Some(2));
}

#[test]
fn excessive_batch_size_exits_with_usage_code() {
    // An absurdly large --batch-size would overflow the capacity hint and try
    // to preallocate an unbounded buffer; reject it at the CLI.
    let dir = tempfile::tempdir().unwrap();
    let out = dir.path().join("out.sql");
    let output = sql_splitter_bin()
        .args([
            "generate",
            "--config",
            SIMPLE_MODEL,
            "--batch-size",
            "2000000",
            "-o",
        ])
        .arg(&out)
        .output()
        .expect("failed to run sql-splitter");
    assert_eq!(output.status.code(), Some(2));
}

#[test]
fn zero_batch_size_exits_with_usage_code() {
    let dir = tempfile::tempdir().unwrap();
    let out = dir.path().join("out.sql");
    let output = sql_splitter_bin()
        .args([
            "generate",
            "--config",
            SIMPLE_MODEL,
            "--batch-size",
            "0",
            "-o",
        ])
        .arg(&out)
        .output()
        .expect("failed to run sql-splitter");

    assert_eq!(output.status.code(), Some(2));
}

#[test]
fn malformed_table_rows_pattern_exits_with_usage_code() {
    let output = sql_splitter_bin()
        .args([
            "generate",
            "--config",
            SIMPLE_MODEL,
            "--table-rows",
            "not-a-pattern",
            "--check",
        ])
        .output()
        .expect("failed to run sql-splitter");

    assert_eq!(output.status.code(), Some(2));
}

#[test]
fn table_targeted_by_both_table_rows_and_table_scale_exits_with_usage_code() {
    let output = sql_splitter_bin()
        .args([
            "generate",
            "--config",
            SIMPLE_MODEL,
            "--table-rows",
            "customers=10",
            "--table-scale",
            "customers=2.0",
            "--check",
        ])
        .output()
        .expect("failed to run sql-splitter");

    assert_eq!(output.status.code(), Some(2));
}

#[test]
fn compress_with_stdout_output_exits_with_usage_code() {
    let output = sql_splitter_bin()
        .args(["generate", "--config", SIMPLE_MODEL, "--compress", "gzip"])
        .output()
        .expect("failed to run sql-splitter");

    assert_eq!(output.status.code(), Some(2));
}

// ===========================================================================
// End-to-end: --verify generates, audits, and atomically publishes
// ===========================================================================

#[test]
fn verify_generates_audits_and_publishes_to_a_real_file() {
    let dir = tempfile::tempdir().unwrap();
    let out = dir.path().join("synthetic.sql");
    let output = sql_splitter_bin()
        .args(["generate", "--config", SIMPLE_MODEL, "--verify", "-o"])
        .arg(&out)
        .output()
        .expect("failed to run sql-splitter");

    assert_eq!(
        output.status.code(),
        Some(0),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert!(out.exists(), "verified output should be published");
    let published = std::fs::read_to_string(&out).unwrap();
    assert!(published.contains("INSERT INTO"), "{published}");
}

#[test]
fn verify_supports_data_only_and_schema_only_output() {
    let dir = tempfile::tempdir().unwrap();
    for (mode, expected, forbidden) in [
        ("--data-only", "INSERT INTO", "CREATE TABLE"),
        ("--schema-only", "CREATE TABLE", "INSERT INTO"),
    ] {
        let output_path = dir.path().join(format!("{}.sql", &mode[2..]));
        let run = sql_splitter_bin()
            .args(["generate", "--config", SIMPLE_MODEL, mode, "--verify", "-o"])
            .arg(&output_path)
            .output()
            .expect("failed to run sql-splitter");

        assert_eq!(
            run.status.code(),
            Some(0),
            "{mode} verification failed: {}",
            String::from_utf8_lossy(&run.stderr)
        );
        let sql = fs::read_to_string(output_path).unwrap();
        assert!(sql.contains(expected), "{mode} output: {sql}");
        assert!(!sql.contains(forbidden), "{mode} output: {sql}");
    }
}

// ===========================================================================
// Dump-to-model and dump-to-SQL workflows
// ===========================================================================

const PRODUCTION_DUMP: &str = "tests/fixtures/generate/production_shape.sql";

/// Workflow 1: `generate production.sql -o synthetic.sql` profiles the dump,
/// infers a model, and generates SQL — no config required.
#[test]
fn dump_workflow_infers_and_generates() {
    let dir = tempfile::tempdir().unwrap();
    let out = dir.path().join("synthetic.sql");

    let output = sql_splitter_bin()
        .args(["generate", PRODUCTION_DUMP, "--seed", "42", "-o"])
        .arg(&out)
        .output()
        .expect("failed to run sql-splitter");

    assert_eq!(
        output.status.code(),
        Some(0),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let sql = fs::read_to_string(&out).unwrap();
    assert!(sql.contains("INSERT INTO"), "sql: {sql}");
    // Tables from the dump are present.
    assert!(sql.contains("users"), "sql: {sql}");
}

/// Workflow 2: `generate production.sql --emit-config model.yaml --dry-run`
/// writes ONLY a complete model — no SQL anywhere.
#[test]
fn dump_workflow_emit_config_dry_run_writes_only_a_model() {
    let dir = tempfile::tempdir().unwrap();
    let model = dir.path().join("model.yaml");

    let output = sql_splitter_bin()
        .args(["generate", PRODUCTION_DUMP, "--emit-config"])
        .arg(&model)
        .arg("--dry-run")
        .output()
        .expect("failed to run sql-splitter");

    assert_eq!(
        output.status.code(),
        Some(0),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let yaml = fs::read_to_string(&model).unwrap();
    assert!(yaml.contains("kind: model"), "yaml: {yaml}");
    // Self-contained: inference disabled, observed counts retained, no raw
    // sample values leaked into the document.
    assert!(yaml.contains("inference: disabled"), "yaml: {yaml}");
    assert!(yaml.contains("kind: observed"), "yaml: {yaml}");

    // No SQL was produced on stdout.
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(!stdout.contains("INSERT INTO"), "stdout: {stdout}");
}

/// Workflow 3: `generate --config model.yaml -o synthetic.sql` needs no source
/// dump. We emit a model from the dump first, then generate purely from it.
#[test]
fn dump_workflow_config_only_needs_no_source() {
    let dir = tempfile::tempdir().unwrap();
    let model = dir.path().join("model.yaml");
    let out = dir.path().join("synthetic.sql");

    let emit = sql_splitter_bin()
        .args(["generate", PRODUCTION_DUMP, "--seed", "42", "--emit-config"])
        .arg(&model)
        .output()
        .expect("failed to run sql-splitter");
    assert_eq!(emit.status.code(), Some(0));

    // No input dump here — only the emitted model.
    let gen = sql_splitter_bin()
        .args(["generate", "--config"])
        .arg(&model)
        .arg("-o")
        .arg(&out)
        .output()
        .expect("failed to run sql-splitter");
    assert_eq!(
        gen.status.code(),
        Some(0),
        "stderr: {}",
        String::from_utf8_lossy(&gen.stderr)
    );
    assert!(fs::read_to_string(&out).unwrap().contains("INSERT INTO"));
}

/// Workflow 4: `generate production.sql --emit-config resolved.yaml -o out.sql`
/// writes AND executes the SAME resolved decisions. Reloading the emitted model
/// (seeded) reproduces byte-identical SQL, and removing the optional `profiles`
/// and `source` blocks from it does not change seeded output.
#[test]
fn dump_workflow_emit_and_execute_are_consistent_and_trimmable() {
    let dir = tempfile::tempdir().unwrap();
    let resolved = dir.path().join("resolved.yaml");
    let out1 = dir.path().join("out1.sql");

    // Emit + execute in one seeded run.
    let run = sql_splitter_bin()
        .args(["generate", PRODUCTION_DUMP, "--seed", "42", "--emit-config"])
        .arg(&resolved)
        .arg("-o")
        .arg(&out1)
        .output()
        .expect("failed to run sql-splitter");
    assert_eq!(
        run.status.code(),
        Some(0),
        "stderr: {}",
        String::from_utf8_lossy(&run.stderr)
    );
    let sql1 = fs::read_to_string(&out1).unwrap();
    assert!(sql1.contains("INSERT INTO"), "sql1: {sql1}");

    // Reload the emitted model (which carries seed 42) and regenerate: the
    // resolved decisions execute identically.
    let out2 = dir.path().join("out2.sql");
    let reload = sql_splitter_bin()
        .args(["generate", "--config"])
        .arg(&resolved)
        .arg("-o")
        .arg(&out2)
        .output()
        .expect("failed to run sql-splitter");
    assert_eq!(reload.status.code(), Some(0));
    assert_eq!(sql1, fs::read_to_string(&out2).unwrap());

    // Removing either optional metadata block — `profiles` or `source` — does
    // not change seeded output. (The compiler keeps one provenance marker as a
    // guard against a bare `observed` count, so each is dropped independently.)
    for drop_key in ["profiles", "source"] {
        let mut doc: serde_yaml_ng::Value =
            serde_yaml_ng::from_str(&fs::read_to_string(&resolved).unwrap()).unwrap();
        if let serde_yaml_ng::Value::Mapping(map) = &mut doc {
            map.remove(serde_yaml_ng::Value::from(drop_key));
        }
        let trimmed = dir.path().join(format!("trimmed_{drop_key}.yaml"));
        fs::write(&trimmed, serde_yaml_ng::to_string(&doc).unwrap()).unwrap();

        let out3 = dir.path().join(format!("out3_{drop_key}.sql"));
        let trimmed_run = sql_splitter_bin()
            .args(["generate", "--config"])
            .arg(&trimmed)
            .arg("-o")
            .arg(&out3)
            .output()
            .expect("failed to run sql-splitter");
        assert_eq!(
            trimmed_run.status.code(),
            Some(0),
            "dropping `{drop_key}` stderr: {}",
            String::from_utf8_lossy(&trimmed_run.stderr)
        );
        assert_eq!(
            sql1,
            fs::read_to_string(&out3).unwrap(),
            "dropping `{drop_key}` changed seeded output"
        );
    }
}

/// The conservative source-derived advisory fires (the dump's categorical
/// `status` column replays observed literals), survives `--quiet` and
/// `--strict`, and the JSON diagnostic lists paths and rule kinds but never the
/// values.
#[test]
fn dump_workflow_source_values_notice_survives_quiet_and_json_hides_values() {
    let dir = tempfile::tempdir().unwrap();
    let out = dir.path().join("synthetic.sql");

    // --quiet: the GEN-SOURCE-VALUES notice must still reach stderr.
    let quiet = sql_splitter_bin()
        .args(["generate", PRODUCTION_DUMP, "--seed", "42", "--quiet", "-o"])
        .arg(&out)
        .output()
        .expect("failed to run sql-splitter");
    assert_eq!(quiet.status.code(), Some(0));
    let stderr = String::from_utf8_lossy(&quiet.stderr);
    assert!(stderr.contains("GEN-SOURCE-VALUES"), "stderr: {stderr}");
    // The notice never leaks a value (e.g. the observed status `paid`).
    assert!(!stderr.contains("paid"), "stderr leaked a value: {stderr}");

    // --json: one ordinary advisory diagnostic carries paths + rule kinds, not
    // values. There is no second source_values reporting shape.
    let out_json = dir.path().join("synthetic_json.sql");
    let json = sql_splitter_bin()
        .args(["generate", PRODUCTION_DUMP, "--seed", "42", "--json", "-o"])
        .arg(&out_json)
        .output()
        .expect("failed to run sql-splitter");
    assert_eq!(json.status.code(), Some(0));
    let stdout = String::from_utf8_lossy(&json.stdout);
    let report: serde_json::Value =
        serde_json::from_str(&stdout).unwrap_or_else(|_| panic!("failed to parse JSON: {stdout}"));
    assert!(
        report.get("source_values").is_none(),
        "redundant shape: {stdout}"
    );
    let advisory = report["diagnostics"]
        .as_array()
        .expect("diagnostics array")
        .iter()
        .find(|diagnostic| diagnostic["code"] == "GEN-SOURCE-VALUES")
        .expect("GEN-SOURCE-VALUES advisory");
    assert_eq!(advisory["severity"], "advisory");
    assert_eq!(
        advisory["documentation_url"],
        "https://sql-splitter.dev/commands/generate/diagnostics/#GEN-SOURCE-VALUES"
    );
    let related = advisory["related"].as_array().expect("related locations");
    assert!(
        !related.is_empty(),
        "expected related locations: {advisory}"
    );
    for entry in related {
        assert!(entry.get("path").is_some(), "entry missing path: {entry}");
        assert!(
            entry.get("description").is_some(),
            "entry missing rule kind: {entry}"
        );
    }
    // No observed value string appears anywhere in the JSON report.
    assert!(!stdout.contains("paid"), "json leaked a value: {stdout}");

    let strict = sql_splitter_bin()
        .args([
            "generate",
            PRODUCTION_DUMP,
            "--seed",
            "42",
            "--strict",
            "--quiet",
            "-o",
        ])
        .arg(dir.path().join("strict.sql"))
        .output()
        .expect("failed to run sql-splitter");
    assert_eq!(
        strict.status.code(),
        Some(0),
        "advisories are never strict-fatal: {}",
        String::from_utf8_lossy(&strict.stderr)
    );
    assert!(
        String::from_utf8_lossy(&strict.stderr).contains("GEN-SOURCE-VALUES"),
        "advisory must survive quiet+strict"
    );
}

#[test]
fn runtime_generate_error_uses_the_json_diagnostic_envelope() {
    let dir = tempfile::tempdir().unwrap();
    let overrides = dir.path().join("overrides.yaml");
    fs::write(&overrides, "version: 1\nkind: overrides\ntables: {}\n").unwrap();

    let output = sql_splitter_bin()
        .args(["generate", "--config"])
        .arg(&overrides)
        .arg("--json")
        .arg("-o")
        .arg(dir.path().join("out.sql"))
        .output()
        .expect("failed to run sql-splitter");

    assert_eq!(output.status.code(), Some(1));
    let stdout = String::from_utf8_lossy(&output.stdout);
    let report: serde_json::Value =
        serde_json::from_str(&stdout).unwrap_or_else(|_| panic!("invalid JSON: {stdout}"));
    let diagnostic = &report["diagnostics"][0];
    assert_eq!(diagnostic["code"], "GEN-OVERRIDES-NO-BASE");
    assert_eq!(diagnostic["severity"], "error");
    assert_eq!(
        diagnostic["documentation_url"],
        "https://sql-splitter.dev/commands/generate/diagnostics/#GEN-OVERRIDES-NO-BASE"
    );
}

/// A seeded emit records the seed for byte-equivalent reload; an unseeded run
/// records the effective seed in its report while emitting no seed.
#[test]
fn dump_workflow_unseeded_run_records_effective_seed() {
    let dir = tempfile::tempdir().unwrap();
    let model = dir.path().join("model.yaml");
    let out = dir.path().join("synthetic.sql");

    let output = sql_splitter_bin()
        .args(["generate", PRODUCTION_DUMP, "--json", "--emit-config"])
        .arg(&model)
        .arg("-o")
        .arg(&out)
        .output()
        .expect("failed to run sql-splitter");
    assert_eq!(
        output.status.code(),
        Some(0),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let stdout = String::from_utf8_lossy(&output.stdout);
    let report: serde_json::Value =
        serde_json::from_str(&stdout).unwrap_or_else(|_| panic!("failed to parse JSON: {stdout}"));
    assert!(
        report["effective_seed"].as_u64().is_some(),
        "expected effective_seed: {stdout}"
    );

    // The emitted model records no seed (unseeded runs stay fresh on reload).
    let doc: serde_yaml_ng::Value =
        serde_yaml_ng::from_str(&fs::read_to_string(&model).unwrap()).unwrap();
    let seed = doc.get("seed");
    assert!(
        seed.is_none() || seed == Some(&serde_yaml_ng::Value::Null),
        "emitted model should record no seed, got {seed:?}"
    );
}

// ===========================================================================
// End-to-end: complete-model generate/check/dry-run happy paths
// ===========================================================================

#[test]
fn generate_writes_sql_to_the_given_output_file() {
    let dir = tempfile::tempdir().unwrap();
    let out = dir.path().join("synthetic.sql");

    let output = sql_splitter_bin()
        .args(["generate", "--config", SIMPLE_MODEL, "--seed", "42", "-o"])
        .arg(&out)
        .output()
        .expect("failed to run sql-splitter");

    assert_eq!(
        output.status.code(),
        Some(0),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let sql = fs::read_to_string(&out).unwrap();
    assert!(sql.contains("INSERT INTO"));
}

#[test]
fn generate_defaults_to_stdout_without_json_or_output() {
    let output = sql_splitter_bin()
        .args(["generate", "--config", SIMPLE_MODEL, "--seed", "42"])
        .output()
        .expect("failed to run sql-splitter");

    assert_eq!(
        output.status.code(),
        Some(0),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("INSERT INTO"), "stdout: {stdout}");
}

#[test]
fn check_mode_exits_zero_and_writes_no_sql() {
    let output = sql_splitter_bin()
        .args(["generate", "--config", SIMPLE_MODEL, "--check"])
        .output()
        .expect("failed to run sql-splitter");

    assert_eq!(
        output.status.code(),
        Some(0),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(!stdout.contains("INSERT INTO"));
}

#[test]
fn dry_run_mode_exits_zero_and_writes_no_sql() {
    let output = sql_splitter_bin()
        .args(["generate", "--config", SIMPLE_MODEL, "--dry-run"])
        .output()
        .expect("failed to run sql-splitter");

    assert_eq!(
        output.status.code(),
        Some(0),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(!stdout.contains("INSERT INTO"));
}

#[test]
fn json_report_to_a_file_output_is_valid_json_with_rows_written() {
    let dir = tempfile::tempdir().unwrap();
    let out = dir.path().join("synthetic.sql");

    let output = sql_splitter_bin()
        .args(["generate", "--config", SIMPLE_MODEL, "--json", "-o"])
        .arg(&out)
        .output()
        .expect("failed to run sql-splitter");

    assert_eq!(
        output.status.code(),
        Some(0),
        "stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    let json: serde_json::Value =
        serde_json::from_str(&stdout).unwrap_or_else(|_| panic!("failed to parse JSON: {stdout}"));
    assert_eq!(json["mode"], "generate");
    assert!(json["rows_written"].as_u64().unwrap() > 0);
    assert!(fs::read_to_string(&out).unwrap().contains("INSERT INTO"));
}

#[test]
fn same_seed_reproduces_identical_output() {
    let dir = tempfile::tempdir().unwrap();
    let first = dir.path().join("first.sql");
    let second = dir.path().join("second.sql");

    for out in [&first, &second] {
        let output = sql_splitter_bin()
            .args(["generate", "--config", SIMPLE_MODEL, "--seed", "7", "-o"])
            .arg(out)
            .output()
            .expect("failed to run sql-splitter");
        assert_eq!(output.status.code(), Some(0));
    }

    assert_eq!(
        fs::read_to_string(first).unwrap(),
        fs::read_to_string(second).unwrap()
    );
}

#[test]
fn different_seeds_produce_different_output() {
    let dir = tempfile::tempdir().unwrap();
    let first = dir.path().join("first.sql");
    let second = dir.path().join("second.sql");

    let output = sql_splitter_bin()
        .args(["generate", "--config", SIMPLE_MODEL, "--seed", "7", "-o"])
        .arg(&first)
        .output()
        .expect("failed to run sql-splitter");
    assert_eq!(output.status.code(), Some(0));

    let output = sql_splitter_bin()
        .args(["generate", "--config", SIMPLE_MODEL, "--seed", "8", "-o"])
        .arg(&second)
        .output()
        .expect("failed to run sql-splitter");
    assert_eq!(output.status.code(), Some(0));

    assert_ne!(
        fs::read_to_string(first).unwrap(),
        fs::read_to_string(second).unwrap()
    );
}

#[test]
fn an_invalid_model_exits_with_failure_code_not_usage_code() {
    let dir = tempfile::tempdir().unwrap();
    let missing = dir.path().join("does-not-exist.yaml");

    let output = sql_splitter_bin()
        .args(["generate", "--config"])
        .arg(&missing)
        .arg("--check")
        .output()
        .expect("failed to run sql-splitter");

    assert_eq!(output.status.code(), Some(1));
}

// ===========================================================================
// Lossy cross-dialect warnings are surfaced and strict-promoted
// ===========================================================================

/// A model whose MySQL `ENUM` column narrows to a plain string on any other
/// dialect — a genuinely lossy cross-dialect conversion.
const LOSSY_ENUM_MODEL: &str = r#"
version: 1
kind: model
source: { dialect: mysql }
defaults: { inference: disabled }
seed: 7
tables:
  widgets:
    rows: { kind: fixed, count: 3 }
    schema:
      name: widgets
      primary_key: [id]
      columns:
        - { name: id, type: bigint, nullable: false, primary_key: true }
        - { name: kind, type: "enum('a','b')", nullable: false }
    columns:
      id: { generator: { kind: sequence, start: 1 } }
      kind: { generator: { kind: choice, values: [a, b] } }
"#;

#[test]
fn lossy_cross_dialect_conversion_warns_on_a_normal_run() {
    let dir = tempfile::tempdir().unwrap();
    let model = dir.path().join("model.yaml");
    let out = dir.path().join("out.sql");
    fs::write(&model, LOSSY_ENUM_MODEL).unwrap();

    // Render the MySQL-source model to PostgreSQL: ENUM -> VARCHAR(255) is lossy.
    let run = sql_splitter_bin()
        .args(["generate", "--config"])
        .arg(&model)
        .args(["--dialect", "postgres", "-o"])
        .arg(&out)
        .output()
        .expect("failed to run sql-splitter");

    let stderr = String::from_utf8_lossy(&run.stderr);
    assert_eq!(run.status.code(), Some(0), "stderr: {stderr}");
    // The lossy conversion is no longer silent: it reaches the report diagnostics
    // and is printed (previously `renderer.warnings()` was dropped entirely).
    assert!(
        stderr.contains("GEN-LOSSY-TYPE"),
        "lossy warning not surfaced; stderr: {stderr}"
    );
    // The narrowed type is what actually landed in the DDL.
    assert!(fs::read_to_string(&out).unwrap().contains("VARCHAR(255)"));
}

#[test]
fn lossy_cross_dialect_conversion_fails_under_strict() {
    let dir = tempfile::tempdir().unwrap();
    let model = dir.path().join("model.yaml");
    let out = dir.path().join("out.sql");
    let emitted = dir.path().join("resolved.yaml");
    fs::write(&model, LOSSY_ENUM_MODEL).unwrap();
    fs::write(&out, "previous SQL\n").unwrap();
    fs::write(&emitted, "previous model\n").unwrap();

    // The SAME run under --strict promotes the lossy warning to a failure.
    let run = sql_splitter_bin()
        .args(["generate", "--config"])
        .arg(&model)
        .args(["--dialect", "postgres", "--strict", "--emit-config"])
        .arg(&emitted)
        .arg("-o")
        .arg(&out)
        .output()
        .expect("failed to run sql-splitter");

    let stderr = String::from_utf8_lossy(&run.stderr);
    assert_eq!(
        run.status.code(),
        Some(1),
        "expected strict failure; stderr: {stderr}"
    );
    assert!(stderr.contains("GEN-LOSSY-TYPE"), "stderr: {stderr}");
    assert_eq!(fs::read_to_string(out).unwrap(), "previous SQL\n");
    assert_eq!(fs::read_to_string(emitted).unwrap(), "previous model\n");
}

#[test]
fn strict_render_warning_writes_no_sql_to_stdout() {
    let dir = tempfile::tempdir().unwrap();
    let model = dir.path().join("model.yaml");
    fs::write(&model, LOSSY_ENUM_MODEL).unwrap();

    let run = sql_splitter_bin()
        .args(["generate", "--config"])
        .arg(&model)
        .args(["--dialect", "postgres", "--strict"])
        .output()
        .expect("failed to run sql-splitter");

    assert_eq!(run.status.code(), Some(1));
    assert!(run.stdout.is_empty(), "strict failure leaked generated SQL");
    assert!(String::from_utf8_lossy(&run.stderr).contains("GEN-LOSSY-TYPE"));
}

#[test]
fn same_dialect_run_has_no_lossy_warning() {
    let dir = tempfile::tempdir().unwrap();
    let model = dir.path().join("model.yaml");
    let out = dir.path().join("out.sql");
    fs::write(&model, LOSSY_ENUM_MODEL).unwrap();

    // Rendering to the model's own dialect maps nothing, so --strict still passes.
    let run = sql_splitter_bin()
        .args(["generate", "--config"])
        .arg(&model)
        .args(["--dialect", "mysql", "--strict", "-o"])
        .arg(&out)
        .output()
        .expect("failed to run sql-splitter");

    let stderr = String::from_utf8_lossy(&run.stderr);
    assert_eq!(run.status.code(), Some(0), "stderr: {stderr}");
    assert!(!stderr.contains("GEN-LOSSY-TYPE"), "stderr: {stderr}");
}