sql-splitter 1.13.1

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
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
pub(crate) mod analyze;
pub(crate) mod convert;
mod diff;
mod glob_util;
pub(crate) mod graph;
pub(crate) mod merge;
mod order;
mod query;
pub(crate) mod redact;
pub(crate) mod sample;
pub(crate) mod shard;
pub(crate) mod split;
pub(crate) mod validate;

use clap::{CommandFactory, Parser, Subcommand, ValueHint};
use clap_complete::{generate, Shell};
use std::io;
use std::path::PathBuf;

const AFTER_HELP: &str = "\x1b[1mCommon workflows:\x1b[0m
  Split a dump into per-table files:
    sql-splitter split dump.sql -o tables/

  Create a 10% sample for development:
    sql-splitter sample dump.sql -o dev.sql --percent 10 --preserve-relations

  Convert MySQL to PostgreSQL:
    sql-splitter convert mysql.sql --to postgres -o pg.sql

  Compare two dumps for changes:
    sql-splitter diff old.sql new.sql --format sql -o migration.sql

\x1b[1mMore info:\x1b[0m
  Run 'sql-splitter <command> --help' for command-specific options.
  Documentation: https://github.com/helgesverre/sql-splitter
  Enable completions: sql-splitter completions <shell>";

#[derive(Parser)]
#[command(name = "sql-splitter")]
#[command(author = "Helge Sverre <helge.sverre@gmail.com>")]
#[command(version)]
#[command(
    about = "High-performance CLI for splitting, merging, converting, and analyzing SQL dump files"
)]
#[command(after_help = AFTER_HELP)]
#[command(arg_required_else_help = true)]
#[command(max_term_width = 100)]
pub struct Cli {
    #[command(subcommand)]
    pub command: Commands,
}

// Help heading constants for consistency
const INPUT_OUTPUT: &str = "Input/Output";
const FILTERING: &str = "Filtering";
const MODE: &str = "Mode";
const BEHAVIOR: &str = "Behavior";
const LIMITS: &str = "Limits";
const OUTPUT_FORMAT: &str = "Output";

#[derive(Subcommand)]
pub enum Commands {
    /// Split a SQL dump into individual table files
    #[command(visible_alias = "sp")]
    #[command(after_help = "\x1b[1mExamples:\x1b[0m
  sql-splitter split dump.sql -o tables/
  sql-splitter split dump.sql.gz -o tables/ --tables users,orders
  sql-splitter split dump.sql -o schema/ --schema-only
  sql-splitter split \"backups/*.sql\" -o out/ --fail-fast")]
    Split {
        /// Input SQL file or glob pattern (e.g., *.sql, dumps/**/*.sql)
        #[arg(value_hint = ValueHint::FilePath, help_heading = INPUT_OUTPUT)]
        file: PathBuf,

        /// Output directory for split files
        #[arg(short, long, default_value = "output", value_hint = ValueHint::DirPath, help_heading = INPUT_OUTPUT)]
        output: PathBuf,

        /// SQL dialect: mysql, postgres, sqlite, mssql (auto-detected if omitted)
        #[arg(short, long, help_heading = INPUT_OUTPUT)]
        dialect: Option<String>,

        /// Only split specific tables (comma-separated)
        #[arg(short, long, help_heading = FILTERING)]
        tables: Option<String>,

        /// Only include schema statements (CREATE, ALTER, DROP)
        #[arg(long, conflicts_with = "data_only", help_heading = FILTERING)]
        schema_only: bool,

        /// Only include data statements (INSERT, COPY)
        #[arg(long, conflicts_with = "schema_only", help_heading = FILTERING)]
        data_only: bool,

        /// Show verbose output
        #[arg(short, long, help_heading = OUTPUT_FORMAT)]
        verbose: bool,

        /// Show progress bar
        #[arg(short, long, help_heading = OUTPUT_FORMAT)]
        progress: bool,

        /// Output results as JSON
        #[arg(long, help_heading = OUTPUT_FORMAT)]
        json: bool,

        /// Preview without writing files
        #[arg(long, help_heading = BEHAVIOR)]
        dry_run: bool,

        /// Stop on first error (for glob patterns)
        #[arg(long, help_heading = BEHAVIOR)]
        fail_fast: bool,
    },

    /// Analyze a SQL dump and display table statistics
    #[command(visible_alias = "an")]
    #[command(after_help = "\x1b[1mExamples:\x1b[0m
  sql-splitter analyze dump.sql
  sql-splitter analyze dump.sql.gz --progress
  sql-splitter analyze \"dumps/*.sql\" --json")]
    Analyze {
        /// Input SQL file or glob pattern
        #[arg(value_hint = ValueHint::FilePath, help_heading = INPUT_OUTPUT)]
        file: PathBuf,

        /// SQL dialect: mysql, postgres, sqlite, mssql (auto-detected if omitted)
        #[arg(short, long, help_heading = INPUT_OUTPUT)]
        dialect: Option<String>,

        /// Show progress bar
        #[arg(short, long, help_heading = OUTPUT_FORMAT)]
        progress: bool,

        /// Output results as JSON
        #[arg(long, help_heading = OUTPUT_FORMAT)]
        json: bool,

        /// Stop on first error (for glob patterns)
        #[arg(long, help_heading = BEHAVIOR)]
        fail_fast: bool,
    },

    /// Merge split SQL files back into a single dump
    #[command(visible_alias = "mg")]
    #[command(after_help = "\x1b[1mExamples:\x1b[0m
  sql-splitter merge tables/ -o restored.sql
  sql-splitter merge tables/ -o restored.sql --transaction
  sql-splitter merge tables/ -o partial.sql --tables users,orders
  sql-splitter merge tables/ -o clean.sql --exclude logs,cache")]
    Merge {
        /// Directory containing split SQL files
        #[arg(value_hint = ValueHint::DirPath, help_heading = INPUT_OUTPUT)]
        input_dir: PathBuf,

        /// Output SQL file (default: stdout)
        #[arg(short, long, value_hint = ValueHint::FilePath, help_heading = INPUT_OUTPUT)]
        output: Option<PathBuf>,

        /// SQL dialect for output formatting
        #[arg(short, long, default_value = "mysql", help_heading = INPUT_OUTPUT)]
        dialect: Option<String>,

        /// Only merge specific tables (comma-separated)
        #[arg(short, long, help_heading = FILTERING)]
        tables: Option<String>,

        /// Exclude specific tables (comma-separated)
        #[arg(short, long, help_heading = FILTERING)]
        exclude: Option<String>,

        /// Wrap output in BEGIN/COMMIT transaction
        #[arg(long, help_heading = BEHAVIOR)]
        transaction: bool,

        /// Omit header comments
        #[arg(long, help_heading = BEHAVIOR)]
        no_header: bool,

        /// Show progress bar
        #[arg(short, long, help_heading = OUTPUT_FORMAT)]
        progress: bool,

        /// Output results as JSON
        #[arg(long, help_heading = OUTPUT_FORMAT)]
        json: bool,

        /// Preview without writing files
        #[arg(long, help_heading = BEHAVIOR)]
        dry_run: bool,
    },

    /// Create a reduced dataset preserving FK relationships
    #[command(visible_alias = "sa")]
    #[command(after_help = "\x1b[1mExamples:\x1b[0m
  sql-splitter sample dump.sql -o dev.sql --percent 10
  sql-splitter sample dump.sql -o dev.sql --rows 1000 --preserve-relations
  sql-splitter sample dump.sql -o dev.sql --percent 5 --seed 42
  sql-splitter sample dump.sql -o dev.sql --tables users,orders --percent 20")]
    Sample {
        /// Input SQL file (supports .gz, .bz2, .xz, .zst)
        #[arg(value_hint = ValueHint::FilePath, help_heading = INPUT_OUTPUT)]
        file: PathBuf,

        /// Output SQL file (default: stdout)
        #[arg(short, long, value_hint = ValueHint::FilePath, help_heading = INPUT_OUTPUT)]
        output: Option<PathBuf>,

        /// SQL dialect: mysql, postgres, sqlite, mssql (auto-detected if omitted)
        #[arg(short, long, help_heading = INPUT_OUTPUT)]
        dialect: Option<String>,

        /// YAML config file for per-table settings
        #[arg(short, long, value_hint = ValueHint::FilePath, help_heading = INPUT_OUTPUT)]
        config: Option<PathBuf>,

        /// Sample percentage of rows (1-100)
        #[arg(long, conflicts_with = "rows", help_heading = MODE)]
        percent: Option<u32>,

        /// Sample fixed number of rows per table
        #[arg(long, conflicts_with = "percent", help_heading = MODE)]
        rows: Option<usize>,

        /// Random seed for reproducible sampling
        #[arg(long, help_heading = MODE)]
        seed: Option<u64>,

        /// Only sample specific tables (comma-separated)
        #[arg(short, long, help_heading = FILTERING)]
        tables: Option<String>,

        /// Exclude specific tables (comma-separated)
        #[arg(short, long, help_heading = FILTERING)]
        exclude: Option<String>,

        /// Tables to start sampling from (comma-separated)
        #[arg(long, help_heading = FILTERING)]
        root_tables: Option<String>,

        /// Handle lookup tables: none, lookups, all
        #[arg(long, default_value = "lookups", help_heading = FILTERING)]
        include_global: Option<String>,

        /// Maintain FK integrity by including referenced rows
        #[arg(long, help_heading = BEHAVIOR)]
        preserve_relations: bool,

        /// Fail on FK integrity violations
        #[arg(long, help_heading = BEHAVIOR)]
        strict_fk: bool,

        /// Exclude CREATE TABLE statements from output
        #[arg(long, help_heading = BEHAVIOR)]
        no_schema: bool,

        /// Max total rows to sample (0 = unlimited)
        #[arg(long, help_heading = LIMITS)]
        max_total_rows: Option<usize>,

        /// Disable row limit
        #[arg(long, help_heading = LIMITS)]
        no_limit: bool,

        /// Show progress bar
        #[arg(short, long, help_heading = OUTPUT_FORMAT)]
        progress: bool,

        /// Output results as JSON
        #[arg(long, help_heading = OUTPUT_FORMAT)]
        json: bool,

        /// Preview without writing files
        #[arg(long, help_heading = BEHAVIOR)]
        dry_run: bool,
    },

    /// Extract tenant-specific data from a multi-tenant dump
    #[command(visible_alias = "sh")]
    #[command(after_help = "\x1b[1mExamples:\x1b[0m
  sql-splitter shard dump.sql -o tenant.sql --tenant-value 123
  sql-splitter shard dump.sql -o tenant.sql --tenant-column company_id --tenant-value 42
  sql-splitter shard dump.sql -o shards/ --tenant-values \"1,2,3\"")]
    Shard {
        /// Input SQL file (supports .gz, .bz2, .xz, .zst)
        #[arg(value_hint = ValueHint::FilePath, help_heading = INPUT_OUTPUT)]
        file: PathBuf,

        /// Output SQL file or directory (default: stdout)
        #[arg(short, long, value_hint = ValueHint::FilePath, help_heading = INPUT_OUTPUT)]
        output: Option<PathBuf>,

        /// SQL dialect: mysql, postgres, sqlite, mssql (auto-detected if omitted)
        #[arg(short, long, help_heading = INPUT_OUTPUT)]
        dialect: Option<String>,

        /// YAML config file for table classification
        #[arg(short, long, value_hint = ValueHint::FilePath, help_heading = INPUT_OUTPUT)]
        config: Option<PathBuf>,

        /// Column containing tenant ID (auto-detected if omitted)
        #[arg(long, help_heading = MODE)]
        tenant_column: Option<String>,

        /// Single tenant value to extract
        #[arg(long, conflicts_with = "tenant_values", help_heading = MODE)]
        tenant_value: Option<String>,

        /// Multiple tenant values (comma-separated, outputs to directory)
        #[arg(long, conflicts_with = "tenant_value", help_heading = MODE)]
        tenant_values: Option<String>,

        /// Tables containing tenant column (comma-separated)
        #[arg(long, help_heading = FILTERING)]
        root_tables: Option<String>,

        /// Handle lookup tables: none, lookups, all
        #[arg(long, default_value = "lookups", help_heading = FILTERING)]
        include_global: Option<String>,

        /// Fail on FK integrity violations
        #[arg(long, help_heading = BEHAVIOR)]
        strict_fk: bool,

        /// Exclude CREATE TABLE statements from output
        #[arg(long, help_heading = BEHAVIOR)]
        no_schema: bool,

        /// Max rows to select (0 = unlimited)
        #[arg(long, help_heading = LIMITS)]
        max_selected_rows: Option<usize>,

        /// Disable row limit
        #[arg(long, help_heading = LIMITS)]
        no_limit: bool,

        /// Show progress bar
        #[arg(short, long, help_heading = OUTPUT_FORMAT)]
        progress: bool,

        /// Output results as JSON
        #[arg(long, help_heading = OUTPUT_FORMAT)]
        json: bool,

        /// Preview without writing files
        #[arg(long, help_heading = BEHAVIOR)]
        dry_run: bool,
    },

    /// Convert a SQL dump between MySQL, PostgreSQL, and SQLite
    #[command(visible_alias = "cv")]
    #[command(after_help = "\x1b[1mExamples:\x1b[0m
  sql-splitter convert mysql.sql --to postgres -o pg.sql
  sql-splitter convert pg_dump.sql --to mysql -o mysql.sql
  sql-splitter convert dump.sql --from mysql --to sqlite -o sqlite.sql
  sql-splitter convert mysql.sql --to postgres | psql mydb")]
    Convert {
        /// Input SQL file or glob pattern
        #[arg(value_hint = ValueHint::FilePath, help_heading = INPUT_OUTPUT)]
        file: PathBuf,

        /// Output SQL file or directory (default: stdout)
        #[arg(short, long, value_hint = ValueHint::FilePath, help_heading = INPUT_OUTPUT)]
        output: Option<PathBuf>,

        /// Source dialect (auto-detected if omitted)
        #[arg(long, help_heading = MODE)]
        from: Option<String>,

        /// Target dialect (required)
        #[arg(long, help_heading = MODE)]
        to: String,

        /// Fail on unsupported features instead of warning
        #[arg(long, help_heading = BEHAVIOR)]
        strict: bool,

        /// Show progress bar
        #[arg(short, long, help_heading = OUTPUT_FORMAT)]
        progress: bool,

        /// Output results as JSON
        #[arg(long, help_heading = OUTPUT_FORMAT)]
        json: bool,

        /// Preview without writing files
        #[arg(long, help_heading = BEHAVIOR)]
        dry_run: bool,

        /// Stop on first error (for glob patterns)
        #[arg(long, help_heading = BEHAVIOR)]
        fail_fast: bool,
    },

    /// Validate SQL dump syntax, encoding, and data integrity
    #[command(visible_alias = "val")]
    #[command(after_help = "\x1b[1mExamples:\x1b[0m
  sql-splitter validate dump.sql
  sql-splitter validate dump.sql --strict
  sql-splitter validate \"dumps/*.sql\" --json --fail-fast
  sql-splitter validate dump.sql --no-fk-checks")]
    Validate {
        /// Input SQL file or glob pattern
        #[arg(value_hint = ValueHint::FilePath, help_heading = INPUT_OUTPUT)]
        file: PathBuf,

        /// SQL dialect: mysql, postgres, sqlite, mssql (auto-detected if omitted)
        #[arg(short, long, help_heading = INPUT_OUTPUT)]
        dialect: Option<String>,

        /// Treat warnings as errors (exit code 1)
        #[arg(long, help_heading = BEHAVIOR)]
        strict: bool,

        /// Skip PK/FK data integrity checks
        #[arg(long, help_heading = BEHAVIOR)]
        no_fk_checks: bool,

        /// Stop on first error (for glob patterns)
        #[arg(long, help_heading = BEHAVIOR)]
        fail_fast: bool,

        /// Max rows per table for PK/FK checks (0 = unlimited)
        #[arg(long, default_value = "1000000", help_heading = LIMITS)]
        max_rows_per_table: usize,

        /// Disable row limit for PK/FK checks
        #[arg(long, help_heading = LIMITS)]
        no_limit: bool,

        /// Show progress bar
        #[arg(short, long, help_heading = OUTPUT_FORMAT)]
        progress: bool,

        /// Output results as JSON
        #[arg(long, help_heading = OUTPUT_FORMAT)]
        json: bool,
    },

    /// Compare two SQL dumps and report schema + data differences
    #[command(visible_alias = "df")]
    #[command(after_help = "\x1b[1mExamples:\x1b[0m
  sql-splitter diff old.sql new.sql
  sql-splitter diff old.sql new.sql --schema-only
  sql-splitter diff old.sql new.sql --format sql -o migration.sql
  sql-splitter diff old.sql new.sql --verbose --ignore-columns \"*.updated_at\"
  sql-splitter diff old.sql new.sql --primary-key logs:timestamp+message")]
    Diff {
        /// Original SQL dump file
        #[arg(value_hint = ValueHint::FilePath, help_heading = INPUT_OUTPUT)]
        old_file: PathBuf,

        /// Updated SQL dump file
        #[arg(value_hint = ValueHint::FilePath, help_heading = INPUT_OUTPUT)]
        new_file: PathBuf,

        /// Output file (default: stdout)
        #[arg(short, long, value_hint = ValueHint::FilePath, help_heading = INPUT_OUTPUT)]
        output: Option<PathBuf>,

        /// SQL dialect: mysql, postgres, sqlite, mssql (auto-detected if omitted)
        #[arg(short, long, help_heading = INPUT_OUTPUT)]
        dialect: Option<String>,

        /// Only compare these tables (comma-separated)
        #[arg(short, long, help_heading = FILTERING)]
        tables: Option<String>,

        /// Exclude these tables (comma-separated)
        #[arg(short, long, help_heading = FILTERING)]
        exclude: Option<String>,

        /// Ignore columns matching glob patterns (e.g., *.updated_at)
        #[arg(long, help_heading = FILTERING)]
        ignore_columns: Option<String>,

        /// Compare schema only, skip data
        #[arg(long, conflicts_with = "data_only", help_heading = MODE)]
        schema_only: bool,

        /// Compare data only, skip schema
        #[arg(long, conflicts_with = "schema_only", help_heading = MODE)]
        data_only: bool,

        /// Override primary key (format: table:col1+col2,table2:col)
        #[arg(long, help_heading = MODE)]
        primary_key: Option<String>,

        /// Compare tables without PK using all columns as key
        #[arg(long, help_heading = BEHAVIOR)]
        allow_no_pk: bool,

        /// Ignore column order differences in schema
        #[arg(long, help_heading = BEHAVIOR)]
        ignore_order: bool,

        /// Max PK entries per table (limits memory)
        #[arg(long, default_value = "10000000", help_heading = LIMITS)]
        max_pk_entries: usize,

        /// Output format: text, json, sql
        #[arg(short, long, default_value = "text", help_heading = OUTPUT_FORMAT)]
        format: Option<String>,

        /// Show sample PK values for changes
        #[arg(short, long, help_heading = OUTPUT_FORMAT)]
        verbose: bool,

        /// Show progress bar
        #[arg(short, long, help_heading = OUTPUT_FORMAT)]
        progress: bool,
    },

    /// Redact sensitive data (PII) from SQL dumps
    #[command(visible_alias = "rd")]
    #[command(after_help = "\x1b[1mExamples:\x1b[0m
  sql-splitter redact dump.sql -o safe.sql --config redact.yaml
  sql-splitter redact dump.sql -o safe.sql --null \"*.ssn\" --hash \"*.email\"
  sql-splitter redact dump.sql --generate-config -o redact.yaml
  sql-splitter redact dump.sql -o safe.sql --config redact.yaml --seed 42")]
    Redact {
        /// Input SQL file (supports .gz, .bz2, .xz, .zst)
        #[arg(value_hint = ValueHint::FilePath, help_heading = INPUT_OUTPUT)]
        file: PathBuf,

        /// Output file (default: stdout)
        #[arg(short, long, value_hint = ValueHint::FilePath, help_heading = INPUT_OUTPUT)]
        output: Option<PathBuf>,

        /// SQL dialect: mysql, postgres, sqlite, mssql (auto-detected if omitted)
        #[arg(short, long, help_heading = INPUT_OUTPUT)]
        dialect: Option<String>,

        /// YAML config file for redaction rules
        #[arg(short, long, value_hint = ValueHint::FilePath, help_heading = INPUT_OUTPUT)]
        config: Option<PathBuf>,

        /// Generate annotated YAML config by analyzing input file
        #[arg(long, help_heading = MODE)]
        generate_config: bool,

        /// Columns to set to NULL (glob patterns, comma-separated)
        #[arg(long, value_delimiter = ',', help_heading = "Inline Strategies")]
        null: Vec<String>,

        /// Columns to hash with SHA256 (glob patterns)
        #[arg(long, value_delimiter = ',', help_heading = "Inline Strategies")]
        hash: Vec<String>,

        /// Columns to replace with fake data (glob patterns)
        #[arg(long, value_delimiter = ',', help_heading = "Inline Strategies")]
        fake: Vec<String>,

        /// Columns to mask (format: pattern=column, e.g., "****-XXXX=*.credit_card")
        #[arg(long, value_delimiter = ',', help_heading = "Inline Strategies")]
        mask: Vec<String>,

        /// Column=value pairs for constant replacement
        #[arg(long, value_delimiter = ',', help_heading = "Inline Strategies")]
        constant: Vec<String>,

        /// Random seed for reproducible redaction
        #[arg(long, help_heading = MODE)]
        seed: Option<u64>,

        /// Locale for fake data generation (default: en)
        #[arg(long, default_value = "en", help_heading = MODE)]
        locale: String,

        /// Only redact specific tables (comma-separated)
        #[arg(short, long, value_delimiter = ',', help_heading = FILTERING)]
        tables: Vec<String>,

        /// Exclude specific tables (comma-separated)
        #[arg(short = 'x', long, value_delimiter = ',', help_heading = FILTERING)]
        exclude: Vec<String>,

        /// Fail on warnings (e.g., unsupported locale)
        #[arg(long, help_heading = BEHAVIOR)]
        strict: bool,

        /// Show progress bar
        #[arg(short, long, help_heading = OUTPUT_FORMAT)]
        progress: bool,

        /// Preview without writing files
        #[arg(long, help_heading = BEHAVIOR)]
        dry_run: bool,

        /// Output results as JSON
        #[arg(long, help_heading = OUTPUT_FORMAT)]
        json: bool,

        /// Validate config only, don't process
        #[arg(long, help_heading = BEHAVIOR)]
        validate: bool,
    },

    /// Generate Entity Relationship Diagram (ERD) from SQL dump
    #[command(visible_alias = "gr")]
    #[command(after_help = "\x1b[1mExamples:\x1b[0m
  sql-splitter graph dump.sql -o schema.html
  sql-splitter graph dump.sql -o schema.mmd --format mermaid
  sql-splitter graph dump.sql -o schema.png --render
  sql-splitter graph dump.sql --cycles-only
  sql-splitter graph dump.sql --table users --transitive")]
    Graph {
        /// Input SQL file (supports .gz, .bz2, .xz, .zst)
        #[arg(value_hint = ValueHint::FilePath, help_heading = INPUT_OUTPUT)]
        file: PathBuf,

        /// Output file (.html, .dot, .mmd, .json, .png, .svg)
        #[arg(short, long, value_hint = ValueHint::FilePath, help_heading = INPUT_OUTPUT)]
        output: Option<PathBuf>,

        /// Output format: html, dot, mermaid, json
        #[arg(short, long, help_heading = OUTPUT_FORMAT)]
        format: Option<String>,

        /// SQL dialect: mysql, postgres, sqlite, mssql (auto-detected if omitted)
        #[arg(short, long, help_heading = INPUT_OUTPUT)]
        dialect: Option<String>,

        /// Layout direction: lr (left-right), tb (top-bottom)
        #[arg(long, default_value = "lr", help_heading = OUTPUT_FORMAT)]
        layout: Option<String>,

        /// Show only tables involved in circular dependencies
        #[arg(long, help_heading = FILTERING)]
        cycles_only: bool,

        /// Focus on a specific table
        #[arg(long, help_heading = FILTERING)]
        table: Option<String>,

        /// Show transitive dependencies (parents of parents)
        #[arg(long, help_heading = FILTERING)]
        transitive: bool,

        /// Show reverse dependencies (who references this table)
        #[arg(long, help_heading = FILTERING)]
        reverse: bool,

        /// Only include these tables (comma-separated, supports globs)
        #[arg(short, long, help_heading = FILTERING)]
        tables: Option<String>,

        /// Exclude these tables (comma-separated, supports globs)
        #[arg(short, long, help_heading = FILTERING)]
        exclude: Option<String>,

        /// Maximum depth for transitive dependencies
        #[arg(long, help_heading = FILTERING)]
        max_depth: Option<usize>,

        /// Render DOT to PNG/SVG using Graphviz
        #[arg(long, help_heading = BEHAVIOR)]
        render: bool,

        /// Show progress bar
        #[arg(short, long, help_heading = OUTPUT_FORMAT)]
        progress: bool,

        /// Output results as JSON
        #[arg(long, help_heading = OUTPUT_FORMAT)]
        json: bool,
    },

    /// Output SQL dump with tables in topological FK order
    #[command(visible_alias = "ord")]
    #[command(after_help = "\x1b[1mExamples:\x1b[0m
  sql-splitter order dump.sql -o ordered.sql
  sql-splitter order dump.sql --check
  sql-splitter order dump.sql --dry-run
  sql-splitter order dump.sql --reverse")]
    Order {
        /// Input SQL file (supports .gz, .bz2, .xz, .zst)
        #[arg(value_hint = ValueHint::FilePath, help_heading = INPUT_OUTPUT)]
        file: PathBuf,

        /// Output file (default: stdout)
        #[arg(short, long, value_hint = ValueHint::FilePath, help_heading = INPUT_OUTPUT)]
        output: Option<PathBuf>,

        /// SQL dialect: mysql, postgres, sqlite, mssql (auto-detected if omitted)
        #[arg(short, long, help_heading = INPUT_OUTPUT)]
        dialect: Option<String>,

        /// Verify ordering without writing output
        #[arg(long, help_heading = BEHAVIOR)]
        check: bool,

        /// Show order without rewriting the file
        #[arg(long, help_heading = BEHAVIOR)]
        dry_run: bool,

        /// Order children before parents (for DROP operations)
        #[arg(long, help_heading = BEHAVIOR)]
        reverse: bool,
    },

    /// Query SQL dumps using DuckDB's analytical engine
    #[command(visible_alias = "qy")]
    #[command(after_help = "\x1b[1mExamples:\x1b[0m
  sql-splitter query dump.sql \"SELECT COUNT(*) FROM users\"
  sql-splitter query dump.sql \"SELECT * FROM orders WHERE total > 100\" -f json
  sql-splitter query dump.sql \"SELECT * FROM users LIMIT 10\" -o results.csv -f csv
  sql-splitter query dump.sql --interactive
  sql-splitter query huge.sql \"SELECT ...\" --disk
  sql-splitter query dump.sql \"SELECT ...\" --cache
  sql-splitter query --list-cache")]
    Query(query::QueryArgs),

    /// Generate JSON schemas for --json output types (developer tool)
    #[command(hide = true)]
    Schema {
        /// Output directory for schema files
        #[arg(short, long, default_value = "schemas", value_hint = ValueHint::DirPath)]
        output: PathBuf,

        /// Generate schema for a specific command only
        #[arg(short, long)]
        command: Option<String>,

        /// Print schemas to stdout instead of writing files
        #[arg(long)]
        stdout: bool,

        /// List available schema names
        #[arg(long)]
        list: bool,
    },

    /// Generate shell completion scripts
    #[command(after_help = "\x1b[1mInstallation:\x1b[0m
  Bash:
    sql-splitter completions bash > /etc/bash_completion.d/sql-splitter
    # or: sql-splitter completions bash >> ~/.bashrc

  Zsh:
    sql-splitter completions zsh > \"${fpath[1]}/_sql-splitter\"
    # or for oh-my-zsh: sql-splitter completions zsh > ~/.oh-my-zsh/completions/_sql-splitter

  Fish:
    sql-splitter completions fish > ~/.config/fish/completions/sql-splitter.fish

  PowerShell:
    sql-splitter completions powershell >> $PROFILE")]
    Completions {
        /// Target shell
        #[arg(value_enum)]
        shell: Shell,
    },
}

pub fn run(cli: Cli) -> anyhow::Result<()> {
    match cli.command {
        Commands::Split {
            file,
            output,
            dialect,
            verbose,
            dry_run,
            progress,
            tables,
            schema_only,
            data_only,
            fail_fast,
            json,
        } => split::run(
            file,
            output,
            dialect,
            verbose,
            dry_run,
            progress,
            tables,
            schema_only,
            data_only,
            fail_fast,
            json,
        ),
        Commands::Analyze {
            file,
            dialect,
            progress,
            fail_fast,
            json,
        } => analyze::run(file, dialect, progress, fail_fast, json),
        Commands::Merge {
            input_dir,
            output,
            dialect,
            tables,
            exclude,
            transaction,
            no_header,
            progress,
            dry_run,
            json,
        } => merge::run(
            input_dir,
            output,
            dialect,
            tables,
            exclude,
            transaction,
            no_header,
            progress,
            dry_run,
            json,
        ),
        Commands::Sample {
            file,
            output,
            dialect,
            percent,
            rows,
            preserve_relations,
            tables,
            exclude,
            root_tables,
            include_global,
            seed,
            config,
            max_total_rows,
            no_limit,
            strict_fk,
            no_schema,
            progress,
            dry_run,
            json,
        } => {
            let effective_limit = if no_limit || max_total_rows == Some(0) {
                None
            } else {
                max_total_rows
            };
            sample::run(
                file,
                output,
                dialect,
                percent,
                rows,
                preserve_relations,
                tables,
                exclude,
                root_tables,
                include_global,
                seed,
                config,
                effective_limit,
                strict_fk,
                no_schema,
                progress,
                dry_run,
                json,
            )
        }
        Commands::Shard {
            file,
            output,
            dialect,
            tenant_column,
            tenant_value,
            tenant_values,
            root_tables,
            include_global,
            config,
            max_selected_rows,
            no_limit,
            strict_fk,
            no_schema,
            progress,
            dry_run,
            json,
        } => {
            let effective_limit = if no_limit || max_selected_rows == Some(0) {
                None
            } else {
                max_selected_rows
            };
            shard::run(
                file,
                output,
                dialect,
                tenant_column,
                tenant_value,
                tenant_values,
                root_tables,
                include_global,
                config,
                effective_limit,
                strict_fk,
                no_schema,
                progress,
                dry_run,
                json,
            )
        }
        Commands::Convert {
            file,
            output,
            from,
            to,
            strict,
            progress,
            dry_run,
            fail_fast,
            json,
        } => convert::run(
            file, output, from, to, strict, progress, dry_run, fail_fast, json,
        ),
        Commands::Validate {
            file,
            dialect,
            progress,
            strict,
            json,
            max_rows_per_table,
            no_limit,
            no_fk_checks,
            fail_fast,
        } => {
            let effective_limit = if no_limit || max_rows_per_table == 0 {
                usize::MAX
            } else {
                max_rows_per_table
            };
            validate::run(
                file,
                dialect,
                progress,
                strict,
                json,
                effective_limit,
                no_fk_checks,
                fail_fast,
            )
        }
        Commands::Diff {
            old_file,
            new_file,
            output,
            tables,
            exclude,
            schema_only,
            data_only,
            format,
            dialect,
            verbose,
            progress,
            max_pk_entries,
            allow_no_pk,
            ignore_order,
            primary_key,
            ignore_columns,
        } => diff::run(
            old_file,
            new_file,
            output,
            tables,
            exclude,
            schema_only,
            data_only,
            format,
            dialect,
            verbose,
            progress,
            max_pk_entries,
            allow_no_pk,
            ignore_order,
            primary_key,
            ignore_columns,
        ),
        Commands::Redact {
            file,
            output,
            dialect,
            config,
            generate_config,
            null,
            hash,
            fake,
            mask,
            constant,
            seed,
            locale,
            tables,
            exclude,
            strict,
            progress,
            dry_run,
            json,
            validate,
        } => redact::run(
            file,
            output,
            dialect,
            config,
            generate_config,
            null,
            hash,
            fake,
            mask,
            constant,
            seed,
            locale,
            tables,
            exclude,
            strict,
            progress,
            dry_run,
            json,
            validate,
        ),
        Commands::Graph {
            file,
            output,
            format,
            dialect,
            layout,
            cycles_only,
            table,
            transitive,
            reverse,
            tables,
            exclude,
            max_depth,
            render,
            progress,
            json,
        } => graph::run(
            file,
            output,
            format,
            dialect,
            layout,
            cycles_only,
            table,
            transitive,
            reverse,
            tables,
            exclude,
            max_depth,
            render,
            progress,
            json,
        ),
        Commands::Order {
            file,
            output,
            dialect,
            check,
            dry_run,
            reverse,
        } => order::run(file, output, dialect, check, dry_run, reverse),
        Commands::Query(args) => query::run(args),
        Commands::Schema {
            output,
            command,
            stdout,
            list,
        } => run_schema(output, command, stdout, list),
        Commands::Completions { shell } => {
            generate(
                shell,
                &mut Cli::command(),
                "sql-splitter",
                &mut io::stdout(),
            );
            Ok(())
        }
    }
}

fn run_schema(
    output_dir: PathBuf,
    command: Option<String>,
    to_stdout: bool,
    list: bool,
) -> anyhow::Result<()> {
    use crate::json_schema;
    use std::fs;

    if list {
        let schemas = json_schema::all_schemas();
        for name in schemas.keys() {
            println!("{}", name);
        }
        return Ok(());
    }

    if let Some(cmd) = command {
        let schema = json_schema::get_schema(&cmd).ok_or_else(|| {
            anyhow::anyhow!(
                "Unknown command: {}. Use --list to see available schemas.",
                cmd
            )
        })?;

        let json = serde_json::to_string_pretty(&schema)?;

        if to_stdout {
            println!("{}", json);
        } else {
            fs::create_dir_all(&output_dir)?;
            let path = output_dir.join(format!("{}.schema.json", cmd));
            fs::write(&path, json)?;
            eprintln!("Wrote: {}", path.display());
        }
    } else if to_stdout {
        let schemas = json_schema::all_schemas();
        for (name, schema) in &schemas {
            let json = serde_json::to_string_pretty(schema)?;
            println!("// {}.schema.json\n{}\n", name, json);
        }
    } else {
        let schemas = json_schema::all_schemas();
        fs::create_dir_all(&output_dir)?;
        for (name, schema) in &schemas {
            let json = serde_json::to_string_pretty(schema)?;
            let path = output_dir.join(format!("{}.schema.json", name));
            fs::write(&path, json)?;
            eprintln!("Wrote: {}", path.display());
        }
    }

    Ok(())
}