Skip to main content

sql_splitter/cmd/
mod.rs

1pub(crate) mod analyze;
2pub(crate) mod convert;
3mod diff;
4mod glob_util;
5pub(crate) mod graph;
6pub(crate) mod merge;
7mod order;
8#[cfg(feature = "duckdb-query")]
9mod query;
10pub(crate) mod redact;
11pub(crate) mod sample;
12pub(crate) mod shard;
13pub(crate) mod split;
14pub(crate) mod validate;
15
16use clap::{CommandFactory, Parser, Subcommand, ValueHint};
17use clap_complete::{generate, Shell};
18use std::io;
19use std::path::PathBuf;
20
21const AFTER_HELP: &str = "\x1b[1mCommon workflows:\x1b[0m
22  Split a dump into per-table files:
23    sql-splitter split dump.sql -o tables/
24
25  Create a 10% sample for development:
26    sql-splitter sample dump.sql -o dev.sql --percent 10 --preserve-relations
27
28  Convert MySQL to PostgreSQL:
29    sql-splitter convert mysql.sql --to postgres -o pg.sql
30
31  Compare two dumps for changes:
32    sql-splitter diff old.sql new.sql --format sql -o migration.sql
33
34\x1b[1mMore info:\x1b[0m
35  Run 'sql-splitter <command> --help' for command-specific options.
36  Documentation: https://github.com/helgesverre/sql-splitter
37  Enable completions: sql-splitter completions <shell>";
38
39#[derive(Parser)]
40#[command(name = "sql-splitter")]
41#[command(author = "Helge Sverre <helge.sverre@gmail.com>")]
42#[command(version)]
43#[command(
44    about = "High-performance CLI for splitting, merging, converting, and analyzing SQL dump files"
45)]
46#[command(after_help = AFTER_HELP)]
47#[command(arg_required_else_help = true)]
48#[command(max_term_width = 100)]
49pub struct Cli {
50    #[command(subcommand)]
51    pub command: Commands,
52}
53
54// Help heading constants for consistency
55const INPUT_OUTPUT: &str = "Input/Output";
56const FILTERING: &str = "Filtering";
57const MODE: &str = "Mode";
58const BEHAVIOR: &str = "Behavior";
59const LIMITS: &str = "Limits";
60const OUTPUT_FORMAT: &str = "Output";
61
62#[derive(Subcommand)]
63pub enum Commands {
64    /// Split a SQL dump into individual table files
65    #[command(visible_alias = "sp")]
66    #[command(after_help = "\x1b[1mExamples:\x1b[0m
67  sql-splitter split dump.sql -o tables/
68  sql-splitter split dump.sql.gz -o tables/ --tables users,orders
69  sql-splitter split dump.sql -o schema/ --schema-only
70  sql-splitter split dump.sql -o tables/ --compress zstd
71  sql-splitter split dump.sql -o dump.tar.gz
72  sql-splitter split \"backups/*.sql\" -o out/ --fail-fast")]
73    Split {
74        /// Input SQL file or glob pattern (e.g., *.sql, dumps/**/*.sql)
75        #[arg(value_hint = ValueHint::FilePath, help_heading = INPUT_OUTPUT)]
76        file: PathBuf,
77
78        /// Output directory, or archive path (.tar.gz/.tgz/.tar.zst/.tar.bz2/.tar.xz/.tar/.zip)
79        #[arg(short, long, default_value = "output", value_hint = ValueHint::DirPath, help_heading = INPUT_OUTPUT)]
80        output: PathBuf,
81
82        /// SQL dialect: mysql, postgres, sqlite, mssql (auto-detected if omitted)
83        #[arg(short, long, help_heading = INPUT_OUTPUT)]
84        dialect: Option<String>,
85
86        /// Only split specific tables (comma-separated)
87        #[arg(short, long, help_heading = FILTERING)]
88        tables: Option<String>,
89
90        /// Only include schema statements (CREATE, ALTER, DROP)
91        #[arg(long, conflicts_with = "data_only", help_heading = FILTERING)]
92        schema_only: bool,
93
94        /// Only include data statements (INSERT, COPY)
95        #[arg(long, conflicts_with = "schema_only", help_heading = FILTERING)]
96        data_only: bool,
97
98        /// Show verbose output
99        #[arg(short, long, help_heading = OUTPUT_FORMAT)]
100        verbose: bool,
101
102        /// Show progress bar
103        #[arg(short, long, help_heading = OUTPUT_FORMAT)]
104        progress: bool,
105
106        /// Output results as JSON
107        #[arg(long, help_heading = OUTPUT_FORMAT)]
108        json: bool,
109
110        /// Compress each output file: none, gzip, zstd, bzip2, xz
111        #[arg(long, default_value = "none", value_name = "FORMAT", help_heading = INPUT_OUTPUT)]
112        compress: String,
113
114        /// Preview without writing files
115        #[arg(long, help_heading = BEHAVIOR)]
116        dry_run: bool,
117
118        /// Stop on first error (for glob patterns)
119        #[arg(long, help_heading = BEHAVIOR)]
120        fail_fast: bool,
121    },
122
123    /// Analyze a SQL dump and display table statistics
124    #[command(visible_alias = "an")]
125    #[command(after_help = "\x1b[1mExamples:\x1b[0m
126  sql-splitter analyze dump.sql
127  sql-splitter analyze dump.sql.gz --progress
128  sql-splitter analyze \"dumps/*.sql\" --json")]
129    Analyze {
130        /// Input SQL file or glob pattern
131        #[arg(value_hint = ValueHint::FilePath, help_heading = INPUT_OUTPUT)]
132        file: PathBuf,
133
134        /// SQL dialect: mysql, postgres, sqlite, mssql (auto-detected if omitted)
135        #[arg(short, long, help_heading = INPUT_OUTPUT)]
136        dialect: Option<String>,
137
138        /// Show progress bar
139        #[arg(short, long, help_heading = OUTPUT_FORMAT)]
140        progress: bool,
141
142        /// Output results as JSON
143        #[arg(long, help_heading = OUTPUT_FORMAT)]
144        json: bool,
145
146        /// Stop on first error (for glob patterns)
147        #[arg(long, help_heading = BEHAVIOR)]
148        fail_fast: bool,
149    },
150
151    /// Merge split SQL files back into a single dump
152    #[command(visible_alias = "mg")]
153    #[command(after_help = "\x1b[1mExamples:\x1b[0m
154  sql-splitter merge tables/ -o restored.sql
155  sql-splitter merge tables/ -o restored.sql --transaction
156  sql-splitter merge tables/ -o partial.sql --tables users,orders
157  sql-splitter merge tables/ -o clean.sql --exclude logs,cache")]
158    Merge {
159        /// Directory containing split SQL files
160        #[arg(value_hint = ValueHint::DirPath, help_heading = INPUT_OUTPUT)]
161        input_dir: PathBuf,
162
163        /// Output SQL file (default: stdout)
164        #[arg(short, long, value_hint = ValueHint::FilePath, help_heading = INPUT_OUTPUT)]
165        output: Option<PathBuf>,
166
167        /// SQL dialect for output formatting
168        #[arg(short, long, default_value = "mysql", help_heading = INPUT_OUTPUT)]
169        dialect: Option<String>,
170
171        /// Only merge specific tables (comma-separated)
172        #[arg(short, long, help_heading = FILTERING)]
173        tables: Option<String>,
174
175        /// Exclude specific tables (comma-separated)
176        #[arg(short, long, help_heading = FILTERING)]
177        exclude: Option<String>,
178
179        /// Wrap output in BEGIN/COMMIT transaction
180        #[arg(long, help_heading = BEHAVIOR)]
181        transaction: bool,
182
183        /// Omit header comments
184        #[arg(long, help_heading = BEHAVIOR)]
185        no_header: bool,
186
187        /// Show progress bar
188        #[arg(short, long, help_heading = OUTPUT_FORMAT)]
189        progress: bool,
190
191        /// Output results as JSON
192        #[arg(long, help_heading = OUTPUT_FORMAT)]
193        json: bool,
194
195        /// Preview without writing files
196        #[arg(long, help_heading = BEHAVIOR)]
197        dry_run: bool,
198    },
199
200    /// Create a reduced dataset preserving FK relationships
201    #[command(visible_alias = "sa")]
202    #[command(after_help = "\x1b[1mExamples:\x1b[0m
203  sql-splitter sample dump.sql -o dev.sql --percent 10
204  sql-splitter sample dump.sql -o dev.sql --rows 1000 --preserve-relations
205  sql-splitter sample dump.sql -o dev.sql --percent 5 --seed 42
206  sql-splitter sample dump.sql -o dev.sql --tables users,orders --percent 20")]
207    Sample {
208        /// Input SQL file (supports .gz, .bz2, .xz, .zst)
209        #[arg(value_hint = ValueHint::FilePath, help_heading = INPUT_OUTPUT)]
210        file: PathBuf,
211
212        /// Output SQL file (default: stdout)
213        #[arg(short, long, value_hint = ValueHint::FilePath, help_heading = INPUT_OUTPUT)]
214        output: Option<PathBuf>,
215
216        /// SQL dialect: mysql, postgres, sqlite, mssql (auto-detected if omitted)
217        #[arg(short, long, help_heading = INPUT_OUTPUT)]
218        dialect: Option<String>,
219
220        /// YAML config file for per-table settings
221        #[arg(short, long, value_hint = ValueHint::FilePath, help_heading = INPUT_OUTPUT)]
222        config: Option<PathBuf>,
223
224        /// Sample percentage of rows (1-100)
225        #[arg(long, conflicts_with = "rows", help_heading = MODE)]
226        percent: Option<u32>,
227
228        /// Sample fixed number of rows per table
229        #[arg(long, conflicts_with = "percent", help_heading = MODE)]
230        rows: Option<usize>,
231
232        /// Random seed for reproducible sampling
233        #[arg(long, help_heading = MODE)]
234        seed: Option<u64>,
235
236        /// Only sample specific tables (comma-separated)
237        #[arg(short, long, help_heading = FILTERING)]
238        tables: Option<String>,
239
240        /// Exclude specific tables (comma-separated)
241        #[arg(short, long, help_heading = FILTERING)]
242        exclude: Option<String>,
243
244        /// Tables to start sampling from (comma-separated)
245        #[arg(long, help_heading = FILTERING)]
246        root_tables: Option<String>,
247
248        /// Handle lookup tables: none, lookups, all
249        #[arg(long, default_value = "lookups", help_heading = FILTERING)]
250        include_global: Option<String>,
251
252        /// Maintain FK integrity by including referenced rows
253        #[arg(long, help_heading = BEHAVIOR)]
254        preserve_relations: bool,
255
256        /// Fail on FK integrity violations
257        #[arg(long, help_heading = BEHAVIOR)]
258        strict_fk: bool,
259
260        /// Exclude CREATE TABLE statements from output
261        #[arg(long, help_heading = BEHAVIOR)]
262        no_schema: bool,
263
264        /// Max total rows to sample (0 = unlimited)
265        #[arg(long, help_heading = LIMITS)]
266        max_total_rows: Option<usize>,
267
268        /// Disable row limit
269        #[arg(long, help_heading = LIMITS)]
270        no_limit: bool,
271
272        /// Show progress bar
273        #[arg(short, long, help_heading = OUTPUT_FORMAT)]
274        progress: bool,
275
276        /// Output results as JSON
277        #[arg(long, help_heading = OUTPUT_FORMAT)]
278        json: bool,
279
280        /// Preview without writing files
281        #[arg(long, help_heading = BEHAVIOR)]
282        dry_run: bool,
283    },
284
285    /// Extract tenant-specific data from a multi-tenant dump
286    #[command(visible_alias = "sh")]
287    #[command(after_help = "\x1b[1mExamples:\x1b[0m
288  sql-splitter shard dump.sql -o tenant.sql --tenant-value 123
289  sql-splitter shard dump.sql -o tenant.sql --tenant-column company_id --tenant-value 42
290  sql-splitter shard dump.sql -o shards/ --tenant-values \"1,2,3\"")]
291    Shard {
292        /// Input SQL file (supports .gz, .bz2, .xz, .zst)
293        #[arg(value_hint = ValueHint::FilePath, help_heading = INPUT_OUTPUT)]
294        file: PathBuf,
295
296        /// Output SQL file or directory (default: stdout)
297        #[arg(short, long, value_hint = ValueHint::FilePath, help_heading = INPUT_OUTPUT)]
298        output: Option<PathBuf>,
299
300        /// SQL dialect: mysql, postgres, sqlite, mssql (auto-detected if omitted)
301        #[arg(short, long, help_heading = INPUT_OUTPUT)]
302        dialect: Option<String>,
303
304        /// YAML config file for table classification
305        #[arg(short, long, value_hint = ValueHint::FilePath, help_heading = INPUT_OUTPUT)]
306        config: Option<PathBuf>,
307
308        /// Column containing tenant ID (auto-detected if omitted)
309        #[arg(long, help_heading = MODE)]
310        tenant_column: Option<String>,
311
312        /// Single tenant value to extract
313        #[arg(long, conflicts_with = "tenant_values", help_heading = MODE)]
314        tenant_value: Option<String>,
315
316        /// Multiple tenant values (comma-separated, outputs to directory)
317        #[arg(long, conflicts_with = "tenant_value", help_heading = MODE)]
318        tenant_values: Option<String>,
319
320        /// Tables containing tenant column (comma-separated)
321        #[arg(long, help_heading = FILTERING)]
322        root_tables: Option<String>,
323
324        /// Handle lookup tables: none, lookups, all
325        #[arg(long, default_value = "lookups", help_heading = FILTERING)]
326        include_global: Option<String>,
327
328        /// Fail on FK integrity violations
329        #[arg(long, help_heading = BEHAVIOR)]
330        strict_fk: bool,
331
332        /// Exclude CREATE TABLE statements from output
333        #[arg(long, help_heading = BEHAVIOR)]
334        no_schema: bool,
335
336        /// Max rows to select (0 = unlimited)
337        #[arg(long, help_heading = LIMITS)]
338        max_selected_rows: Option<usize>,
339
340        /// Disable row limit
341        #[arg(long, help_heading = LIMITS)]
342        no_limit: bool,
343
344        /// Show progress bar
345        #[arg(short, long, help_heading = OUTPUT_FORMAT)]
346        progress: bool,
347
348        /// Output results as JSON
349        #[arg(long, help_heading = OUTPUT_FORMAT)]
350        json: bool,
351
352        /// Preview without writing files
353        #[arg(long, help_heading = BEHAVIOR)]
354        dry_run: bool,
355    },
356
357    /// Convert a SQL dump between MySQL, PostgreSQL, SQLite, and MSSQL
358    #[command(visible_alias = "cv")]
359    #[command(after_help = "\x1b[1mExamples:\x1b[0m
360  sql-splitter convert mysql.sql --to postgres -o pg.sql
361  sql-splitter convert pg_dump.sql --to mysql -o mysql.sql
362  sql-splitter convert dump.sql --from mysql --to sqlite -o sqlite.sql
363  sql-splitter convert mysql.sql --to postgres | psql mydb")]
364    Convert {
365        /// Input SQL file or glob pattern
366        #[arg(value_hint = ValueHint::FilePath, help_heading = INPUT_OUTPUT)]
367        file: PathBuf,
368
369        /// Output SQL file or directory (default: stdout)
370        #[arg(short, long, value_hint = ValueHint::FilePath, help_heading = INPUT_OUTPUT)]
371        output: Option<PathBuf>,
372
373        /// Source dialect (auto-detected if omitted)
374        #[arg(long, help_heading = MODE)]
375        from: Option<String>,
376
377        /// Target dialect (required)
378        #[arg(long, help_heading = MODE)]
379        to: String,
380
381        /// Fail on unsupported features instead of warning
382        #[arg(long, help_heading = BEHAVIOR)]
383        strict: bool,
384
385        /// Show progress bar
386        #[arg(short, long, help_heading = OUTPUT_FORMAT)]
387        progress: bool,
388
389        /// Output results as JSON
390        #[arg(long, help_heading = OUTPUT_FORMAT)]
391        json: bool,
392
393        /// Preview without writing files
394        #[arg(long, help_heading = BEHAVIOR)]
395        dry_run: bool,
396
397        /// Stop on first error (for glob patterns)
398        #[arg(long, help_heading = BEHAVIOR)]
399        fail_fast: bool,
400    },
401
402    /// Validate SQL dump syntax, encoding, and data integrity
403    #[command(visible_alias = "val")]
404    #[command(after_help = "\x1b[1mExamples:\x1b[0m
405  sql-splitter validate dump.sql
406  sql-splitter validate dump.sql --strict
407  sql-splitter validate \"dumps/*.sql\" --json --fail-fast
408  sql-splitter validate dump.sql --no-fk-checks")]
409    Validate {
410        /// Input SQL file or glob pattern
411        #[arg(value_hint = ValueHint::FilePath, help_heading = INPUT_OUTPUT)]
412        file: PathBuf,
413
414        /// SQL dialect: mysql, postgres, sqlite, mssql (auto-detected if omitted)
415        #[arg(short, long, help_heading = INPUT_OUTPUT)]
416        dialect: Option<String>,
417
418        /// Treat warnings as errors (exit code 1)
419        #[arg(long, help_heading = BEHAVIOR)]
420        strict: bool,
421
422        /// Skip PK/FK data integrity checks
423        #[arg(long, help_heading = BEHAVIOR)]
424        no_fk_checks: bool,
425
426        /// Stop on first error (for glob patterns)
427        #[arg(long, help_heading = BEHAVIOR)]
428        fail_fast: bool,
429
430        /// Max rows per table for PK/FK checks (0 = unlimited)
431        #[arg(long, default_value = "1000000", help_heading = LIMITS)]
432        max_rows_per_table: usize,
433
434        /// Disable row limit for PK/FK checks
435        #[arg(long, help_heading = LIMITS)]
436        no_limit: bool,
437
438        /// Show progress bar
439        #[arg(short, long, help_heading = OUTPUT_FORMAT)]
440        progress: bool,
441
442        /// Output results as JSON
443        #[arg(long, help_heading = OUTPUT_FORMAT)]
444        json: bool,
445    },
446
447    /// Compare two SQL dumps and report schema + data differences
448    #[command(visible_alias = "df")]
449    #[command(after_help = "\x1b[1mExamples:\x1b[0m
450  sql-splitter diff old.sql new.sql
451  sql-splitter diff old.sql new.sql --schema-only
452  sql-splitter diff old.sql new.sql --format sql -o migration.sql
453  sql-splitter diff old.sql new.sql --verbose --ignore-columns \"*.updated_at\"
454  sql-splitter diff old.sql new.sql --primary-key logs:timestamp+message")]
455    Diff {
456        /// Original SQL dump file
457        #[arg(value_hint = ValueHint::FilePath, help_heading = INPUT_OUTPUT)]
458        old_file: PathBuf,
459
460        /// Updated SQL dump file
461        #[arg(value_hint = ValueHint::FilePath, help_heading = INPUT_OUTPUT)]
462        new_file: PathBuf,
463
464        /// Output file (default: stdout)
465        #[arg(short, long, value_hint = ValueHint::FilePath, help_heading = INPUT_OUTPUT)]
466        output: Option<PathBuf>,
467
468        /// SQL dialect: mysql, postgres, sqlite, mssql (auto-detected if omitted)
469        #[arg(short, long, help_heading = INPUT_OUTPUT)]
470        dialect: Option<String>,
471
472        /// Only compare these tables (comma-separated)
473        #[arg(short, long, help_heading = FILTERING)]
474        tables: Option<String>,
475
476        /// Exclude these tables (comma-separated)
477        #[arg(short, long, help_heading = FILTERING)]
478        exclude: Option<String>,
479
480        /// Ignore columns matching glob patterns (e.g., *.updated_at)
481        #[arg(long, help_heading = FILTERING)]
482        ignore_columns: Option<String>,
483
484        /// Compare schema only, skip data
485        #[arg(long, conflicts_with = "data_only", help_heading = MODE)]
486        schema_only: bool,
487
488        /// Compare data only, skip schema
489        #[arg(long, conflicts_with = "schema_only", help_heading = MODE)]
490        data_only: bool,
491
492        /// Override primary key (format: table:col1+col2,table2:col)
493        #[arg(long, help_heading = MODE)]
494        primary_key: Option<String>,
495
496        /// Compare tables without PK using all columns as key
497        #[arg(long, help_heading = BEHAVIOR)]
498        allow_no_pk: bool,
499
500        /// Ignore column order differences in schema
501        #[arg(long, help_heading = BEHAVIOR)]
502        ignore_order: bool,
503
504        /// Max PK entries per table (limits memory)
505        #[arg(long, default_value = "10000000", help_heading = LIMITS)]
506        max_pk_entries: usize,
507
508        /// Output format: text, json, sql
509        #[arg(short, long, default_value = "text", help_heading = OUTPUT_FORMAT)]
510        format: Option<String>,
511
512        /// Show sample PK values for changes
513        #[arg(short, long, help_heading = OUTPUT_FORMAT)]
514        verbose: bool,
515
516        /// Show progress bar
517        #[arg(short, long, help_heading = OUTPUT_FORMAT)]
518        progress: bool,
519    },
520
521    /// Redact sensitive data (PII) from SQL dumps
522    #[command(visible_alias = "rd")]
523    #[command(after_help = "\x1b[1mExamples:\x1b[0m
524  sql-splitter redact dump.sql -o safe.sql --config redact.yaml
525  sql-splitter redact dump.sql -o safe.sql --null \"*.ssn\" --hash \"*.email\"
526  sql-splitter redact dump.sql --generate-config -o redact.yaml
527  sql-splitter redact dump.sql -o safe.sql --config redact.yaml --seed 42")]
528    Redact {
529        /// Input SQL file (supports .gz, .bz2, .xz, .zst)
530        #[arg(value_hint = ValueHint::FilePath, help_heading = INPUT_OUTPUT)]
531        file: PathBuf,
532
533        /// Output file (default: stdout)
534        #[arg(short, long, value_hint = ValueHint::FilePath, help_heading = INPUT_OUTPUT)]
535        output: Option<PathBuf>,
536
537        /// SQL dialect: mysql, postgres, sqlite, mssql (auto-detected if omitted)
538        #[arg(short, long, help_heading = INPUT_OUTPUT)]
539        dialect: Option<String>,
540
541        /// YAML config file for redaction rules
542        #[arg(short, long, value_hint = ValueHint::FilePath, help_heading = INPUT_OUTPUT)]
543        config: Option<PathBuf>,
544
545        /// Generate annotated YAML config by analyzing input file
546        #[arg(long, help_heading = MODE)]
547        generate_config: bool,
548
549        /// Columns to set to NULL (glob patterns, comma-separated)
550        #[arg(long, value_delimiter = ',', help_heading = "Inline Strategies")]
551        null: Vec<String>,
552
553        /// Columns to hash with SHA256 (glob patterns)
554        #[arg(long, value_delimiter = ',', help_heading = "Inline Strategies")]
555        hash: Vec<String>,
556
557        /// Columns to replace with fake data (glob patterns)
558        #[arg(long, value_delimiter = ',', help_heading = "Inline Strategies")]
559        fake: Vec<String>,
560
561        /// Columns to mask (format: pattern=column, e.g., "****-XXXX=*.credit_card")
562        #[arg(long, value_delimiter = ',', help_heading = "Inline Strategies")]
563        mask: Vec<String>,
564
565        /// Column=value pairs for constant replacement
566        #[arg(long, value_delimiter = ',', help_heading = "Inline Strategies")]
567        constant: Vec<String>,
568
569        /// Random seed for reproducible redaction
570        #[arg(long, help_heading = MODE)]
571        seed: Option<u64>,
572
573        /// Locale for fake data generation (default: en)
574        #[arg(long, default_value = "en", help_heading = MODE)]
575        locale: String,
576
577        /// Only redact specific tables (comma-separated)
578        #[arg(short, long, value_delimiter = ',', help_heading = FILTERING)]
579        tables: Vec<String>,
580
581        /// Exclude specific tables (comma-separated)
582        #[arg(short = 'x', long, value_delimiter = ',', help_heading = FILTERING)]
583        exclude: Vec<String>,
584
585        /// Fail on warnings (e.g., unsupported locale)
586        #[arg(long, help_heading = BEHAVIOR)]
587        strict: bool,
588
589        /// Show progress bar
590        #[arg(short, long, help_heading = OUTPUT_FORMAT)]
591        progress: bool,
592
593        /// Preview without writing files
594        #[arg(long, help_heading = BEHAVIOR)]
595        dry_run: bool,
596
597        /// Output results as JSON
598        #[arg(long, help_heading = OUTPUT_FORMAT)]
599        json: bool,
600
601        /// Validate config only, don't process
602        #[arg(long, help_heading = BEHAVIOR)]
603        validate: bool,
604    },
605
606    /// Generate Entity Relationship Diagram (ERD) from SQL dump
607    #[command(visible_alias = "gr")]
608    #[command(after_help = "\x1b[1mExamples:\x1b[0m
609  sql-splitter graph dump.sql -o schema.html
610  sql-splitter graph dump.sql -o schema.mmd --format mermaid
611  sql-splitter graph dump.sql -o schema.png --render
612  sql-splitter graph dump.sql --cycles-only
613  sql-splitter graph dump.sql --table users --transitive")]
614    Graph {
615        /// Input SQL file (supports .gz, .bz2, .xz, .zst)
616        #[arg(value_hint = ValueHint::FilePath, help_heading = INPUT_OUTPUT)]
617        file: PathBuf,
618
619        /// Output file (.html, .dot, .mmd, .json, .png, .svg)
620        #[arg(short, long, value_hint = ValueHint::FilePath, help_heading = INPUT_OUTPUT)]
621        output: Option<PathBuf>,
622
623        /// Output format: html, dot, mermaid, json
624        #[arg(short, long, help_heading = OUTPUT_FORMAT)]
625        format: Option<String>,
626
627        /// SQL dialect: mysql, postgres, sqlite, mssql (auto-detected if omitted)
628        #[arg(short, long, help_heading = INPUT_OUTPUT)]
629        dialect: Option<String>,
630
631        /// Layout direction: lr (left-right), tb (top-bottom)
632        #[arg(long, default_value = "lr", help_heading = OUTPUT_FORMAT)]
633        layout: Option<String>,
634
635        /// Show only tables involved in circular dependencies
636        #[arg(long, help_heading = FILTERING)]
637        cycles_only: bool,
638
639        /// Focus on a specific table
640        #[arg(long, help_heading = FILTERING)]
641        table: Option<String>,
642
643        /// Show transitive dependencies (parents of parents)
644        #[arg(long, help_heading = FILTERING)]
645        transitive: bool,
646
647        /// Show reverse dependencies (who references this table)
648        #[arg(long, help_heading = FILTERING)]
649        reverse: bool,
650
651        /// Only include these tables (comma-separated, supports globs)
652        #[arg(short, long, help_heading = FILTERING)]
653        tables: Option<String>,
654
655        /// Exclude these tables (comma-separated, supports globs)
656        #[arg(short, long, help_heading = FILTERING)]
657        exclude: Option<String>,
658
659        /// Maximum depth for transitive dependencies
660        #[arg(long, help_heading = FILTERING)]
661        max_depth: Option<usize>,
662
663        /// Render DOT to PNG/SVG using Graphviz
664        #[arg(long, help_heading = BEHAVIOR)]
665        render: bool,
666
667        /// Show progress bar
668        #[arg(short, long, help_heading = OUTPUT_FORMAT)]
669        progress: bool,
670
671        /// Output results as JSON
672        #[arg(long, help_heading = OUTPUT_FORMAT)]
673        json: bool,
674    },
675
676    /// Output SQL dump with tables in topological FK order
677    #[command(visible_alias = "ord")]
678    #[command(after_help = "\x1b[1mExamples:\x1b[0m
679  sql-splitter order dump.sql -o ordered.sql
680  sql-splitter order dump.sql --check
681  sql-splitter order dump.sql --dry-run
682  sql-splitter order dump.sql --reverse")]
683    Order {
684        /// Input SQL file (supports .gz, .bz2, .xz, .zst)
685        #[arg(value_hint = ValueHint::FilePath, help_heading = INPUT_OUTPUT)]
686        file: PathBuf,
687
688        /// Output file (default: stdout)
689        #[arg(short, long, value_hint = ValueHint::FilePath, help_heading = INPUT_OUTPUT)]
690        output: Option<PathBuf>,
691
692        /// SQL dialect: mysql, postgres, sqlite, mssql (auto-detected if omitted)
693        #[arg(short, long, help_heading = INPUT_OUTPUT)]
694        dialect: Option<String>,
695
696        /// Verify ordering without writing output
697        #[arg(long, help_heading = BEHAVIOR)]
698        check: bool,
699
700        /// Show order without rewriting the file
701        #[arg(long, help_heading = BEHAVIOR)]
702        dry_run: bool,
703
704        /// Order children before parents (for DROP operations)
705        #[arg(long, help_heading = BEHAVIOR)]
706        reverse: bool,
707    },
708
709    /// Query SQL dumps using DuckDB's analytical engine
710    #[cfg(feature = "duckdb-query")]
711    #[command(visible_alias = "qy")]
712    #[command(after_help = "\x1b[1mExamples:\x1b[0m
713  sql-splitter query dump.sql \"SELECT COUNT(*) FROM users\"
714  sql-splitter query dump.sql \"SELECT * FROM orders WHERE total > 100\" -f json
715  sql-splitter query dump.sql \"SELECT * FROM users LIMIT 10\" -o results.csv -f csv
716  sql-splitter query dump.sql --interactive
717  sql-splitter query huge.sql \"SELECT ...\" --disk
718  sql-splitter query dump.sql \"SELECT ...\" --cache
719  sql-splitter query --list-cache")]
720    Query(query::QueryArgs),
721
722    /// Generate JSON schemas for --json output types (developer tool)
723    #[command(hide = true)]
724    Schema {
725        /// Output directory for schema files
726        #[arg(short, long, default_value = "schemas", value_hint = ValueHint::DirPath)]
727        output: PathBuf,
728
729        /// Generate schema for a specific command only
730        #[arg(short, long)]
731        command: Option<String>,
732
733        /// Print schemas to stdout instead of writing files
734        #[arg(long)]
735        stdout: bool,
736
737        /// List available schema names
738        #[arg(long)]
739        list: bool,
740    },
741
742    /// Generate shell completion scripts
743    #[command(after_help = "\x1b[1mInstallation:\x1b[0m
744  Bash:
745    sql-splitter completions bash > /etc/bash_completion.d/sql-splitter
746    # or: sql-splitter completions bash >> ~/.bashrc
747
748  Zsh:
749    sql-splitter completions zsh > \"${fpath[1]}/_sql-splitter\"
750    # or for oh-my-zsh: sql-splitter completions zsh > ~/.oh-my-zsh/completions/_sql-splitter
751
752  Fish:
753    sql-splitter completions fish > ~/.config/fish/completions/sql-splitter.fish
754
755  PowerShell:
756    sql-splitter completions powershell >> $PROFILE")]
757    Completions {
758        /// Target shell
759        #[arg(value_enum)]
760        shell: Shell,
761    },
762}
763
764/// Treat an output path of `-` as "write to stdout" (Unix convention).
765fn dash_is_stdout(output: Option<PathBuf>) -> Option<PathBuf> {
766    output.filter(|p| p.as_os_str() != "-")
767}
768
769pub fn run(cli: Cli) -> anyhow::Result<()> {
770    match cli.command {
771        Commands::Split {
772            file,
773            output,
774            dialect,
775            verbose,
776            dry_run,
777            progress,
778            tables,
779            schema_only,
780            data_only,
781            fail_fast,
782            json,
783            compress,
784        } => split::run(
785            file,
786            output,
787            dialect,
788            verbose,
789            dry_run,
790            progress,
791            tables,
792            schema_only,
793            data_only,
794            fail_fast,
795            json,
796            compress,
797        ),
798        Commands::Analyze {
799            file,
800            dialect,
801            progress,
802            fail_fast,
803            json,
804        } => analyze::run(file, dialect, progress, fail_fast, json),
805        Commands::Merge {
806            input_dir,
807            output,
808            dialect,
809            tables,
810            exclude,
811            transaction,
812            no_header,
813            progress,
814            dry_run,
815            json,
816        } => merge::run(
817            input_dir,
818            dash_is_stdout(output),
819            dialect,
820            tables,
821            exclude,
822            transaction,
823            no_header,
824            progress,
825            dry_run,
826            json,
827        ),
828        Commands::Sample {
829            file,
830            output,
831            dialect,
832            percent,
833            rows,
834            preserve_relations,
835            tables,
836            exclude,
837            root_tables,
838            include_global,
839            seed,
840            config,
841            max_total_rows,
842            no_limit,
843            strict_fk,
844            no_schema,
845            progress,
846            dry_run,
847            json,
848        } => {
849            let effective_limit = if no_limit || max_total_rows == Some(0) {
850                None
851            } else {
852                max_total_rows
853            };
854            sample::run(
855                file,
856                dash_is_stdout(output),
857                dialect,
858                percent,
859                rows,
860                preserve_relations,
861                tables,
862                exclude,
863                root_tables,
864                include_global,
865                seed,
866                config,
867                effective_limit,
868                strict_fk,
869                no_schema,
870                progress,
871                dry_run,
872                json,
873            )
874        }
875        Commands::Shard {
876            file,
877            output,
878            dialect,
879            tenant_column,
880            tenant_value,
881            tenant_values,
882            root_tables,
883            include_global,
884            config,
885            max_selected_rows,
886            no_limit,
887            strict_fk,
888            no_schema,
889            progress,
890            dry_run,
891            json,
892        } => {
893            let effective_limit = if no_limit || max_selected_rows == Some(0) {
894                None
895            } else {
896                max_selected_rows
897            };
898            shard::run(
899                file,
900                dash_is_stdout(output),
901                dialect,
902                tenant_column,
903                tenant_value,
904                tenant_values,
905                root_tables,
906                include_global,
907                config,
908                effective_limit,
909                strict_fk,
910                no_schema,
911                progress,
912                dry_run,
913                json,
914            )
915        }
916        Commands::Convert {
917            file,
918            output,
919            from,
920            to,
921            strict,
922            progress,
923            dry_run,
924            fail_fast,
925            json,
926        } => convert::run(
927            file,
928            dash_is_stdout(output),
929            from,
930            to,
931            strict,
932            progress,
933            dry_run,
934            fail_fast,
935            json,
936        ),
937        Commands::Validate {
938            file,
939            dialect,
940            progress,
941            strict,
942            json,
943            max_rows_per_table,
944            no_limit,
945            no_fk_checks,
946            fail_fast,
947        } => {
948            let effective_limit = if no_limit || max_rows_per_table == 0 {
949                usize::MAX
950            } else {
951                max_rows_per_table
952            };
953            validate::run(
954                file,
955                dialect,
956                progress,
957                strict,
958                json,
959                effective_limit,
960                no_fk_checks,
961                fail_fast,
962            )
963        }
964        Commands::Diff {
965            old_file,
966            new_file,
967            output,
968            tables,
969            exclude,
970            schema_only,
971            data_only,
972            format,
973            dialect,
974            verbose,
975            progress,
976            max_pk_entries,
977            allow_no_pk,
978            ignore_order,
979            primary_key,
980            ignore_columns,
981        } => diff::run(
982            old_file,
983            new_file,
984            output,
985            tables,
986            exclude,
987            schema_only,
988            data_only,
989            format,
990            dialect,
991            verbose,
992            progress,
993            max_pk_entries,
994            allow_no_pk,
995            ignore_order,
996            primary_key,
997            ignore_columns,
998        ),
999        Commands::Redact {
1000            file,
1001            output,
1002            dialect,
1003            config,
1004            generate_config,
1005            null,
1006            hash,
1007            fake,
1008            mask,
1009            constant,
1010            seed,
1011            locale,
1012            tables,
1013            exclude,
1014            strict,
1015            progress,
1016            dry_run,
1017            json,
1018            validate,
1019        } => redact::run(
1020            file,
1021            dash_is_stdout(output),
1022            dialect,
1023            config,
1024            generate_config,
1025            null,
1026            hash,
1027            fake,
1028            mask,
1029            constant,
1030            seed,
1031            locale,
1032            tables,
1033            exclude,
1034            strict,
1035            progress,
1036            dry_run,
1037            json,
1038            validate,
1039        ),
1040        Commands::Graph {
1041            file,
1042            output,
1043            format,
1044            dialect,
1045            layout,
1046            cycles_only,
1047            table,
1048            transitive,
1049            reverse,
1050            tables,
1051            exclude,
1052            max_depth,
1053            render,
1054            progress,
1055            json,
1056        } => graph::run(
1057            file,
1058            output,
1059            format,
1060            dialect,
1061            layout,
1062            cycles_only,
1063            table,
1064            transitive,
1065            reverse,
1066            tables,
1067            exclude,
1068            max_depth,
1069            render,
1070            progress,
1071            json,
1072        ),
1073        Commands::Order {
1074            file,
1075            output,
1076            dialect,
1077            check,
1078            dry_run,
1079            reverse,
1080        } => order::run(
1081            file,
1082            dash_is_stdout(output),
1083            dialect,
1084            check,
1085            dry_run,
1086            reverse,
1087        ),
1088        #[cfg(feature = "duckdb-query")]
1089        Commands::Query(args) => query::run(args),
1090        Commands::Schema {
1091            output,
1092            command,
1093            stdout,
1094            list,
1095        } => run_schema(output, command, stdout, list),
1096        Commands::Completions { shell } => {
1097            generate(
1098                shell,
1099                &mut Cli::command(),
1100                "sql-splitter",
1101                &mut io::stdout(),
1102            );
1103            Ok(())
1104        }
1105    }
1106}
1107
1108fn run_schema(
1109    output_dir: PathBuf,
1110    command: Option<String>,
1111    to_stdout: bool,
1112    list: bool,
1113) -> anyhow::Result<()> {
1114    use crate::json_schema;
1115    use std::fs;
1116
1117    if list {
1118        let schemas = json_schema::all_schemas();
1119        for name in schemas.keys() {
1120            println!("{}", name);
1121        }
1122        return Ok(());
1123    }
1124
1125    if let Some(cmd) = command {
1126        let schema = json_schema::get_schema(&cmd).ok_or_else(|| {
1127            anyhow::anyhow!(
1128                "Unknown command: {}. Use --list to see available schemas.",
1129                cmd
1130            )
1131        })?;
1132
1133        let json = serde_json::to_string_pretty(&schema)?;
1134
1135        if to_stdout {
1136            println!("{}", json);
1137        } else {
1138            fs::create_dir_all(&output_dir)?;
1139            let path = output_dir.join(format!("{}.schema.json", cmd));
1140            fs::write(&path, json)?;
1141            eprintln!("Wrote: {}", path.display());
1142        }
1143    } else if to_stdout {
1144        let schemas = json_schema::all_schemas();
1145        for (name, schema) in &schemas {
1146            let json = serde_json::to_string_pretty(schema)?;
1147            println!("// {}.schema.json\n{}\n", name, json);
1148        }
1149    } else {
1150        let schemas = json_schema::all_schemas();
1151        fs::create_dir_all(&output_dir)?;
1152        for (name, schema) in &schemas {
1153            let json = serde_json::to_string_pretty(schema)?;
1154            let path = output_dir.join(format!("{}.schema.json", name));
1155            fs::write(&path, json)?;
1156            eprintln!("Wrote: {}", path.display());
1157        }
1158    }
1159
1160    Ok(())
1161}