Skip to main content

sql_splitter/cmd/
mod.rs

1pub(crate) mod analyze;
2mod common;
3pub(crate) mod convert;
4mod diff;
5pub(crate) mod generate;
6mod glob_util;
7pub(crate) mod graph;
8pub(crate) mod merge;
9mod order;
10#[cfg(feature = "duckdb-query")]
11mod query;
12pub(crate) mod redact;
13pub(crate) mod sample;
14pub(crate) mod shard;
15pub(crate) mod split;
16pub(crate) mod validate;
17
18use clap::{CommandFactory, Parser, Subcommand, ValueHint};
19use clap_complete::{generate, Shell};
20use std::io;
21use std::path::PathBuf;
22use std::process::ExitCode;
23
24const AFTER_HELP: &str = "\x1b[1mCommon workflows:\x1b[0m
25  Split a dump into per-table files:
26    sql-splitter split dump.sql -o tables/
27
28  Create a 10% sample for development:
29    sql-splitter sample dump.sql -o dev.sql --percent 10 --preserve-relations
30
31  Convert MySQL to PostgreSQL:
32    sql-splitter convert mysql.sql --to postgres -o pg.sql
33
34  Compare two dumps for changes:
35    sql-splitter diff old.sql new.sql --format sql -o migration.sql
36
37\x1b[1mMore info:\x1b[0m
38  Run 'sql-splitter <command> --help' for command-specific options.
39  Documentation: https://github.com/helgesverre/sql-splitter
40  Enable completions: sql-splitter completions <shell>";
41
42#[derive(Parser)]
43#[command(name = "sql-splitter")]
44#[command(author = "Helge Sverre <helge.sverre@gmail.com>")]
45#[command(version)]
46#[command(
47    about = "High-performance CLI for splitting, merging, converting, and analyzing SQL dump files"
48)]
49#[command(after_help = AFTER_HELP)]
50#[command(arg_required_else_help = true)]
51#[command(max_term_width = 100)]
52pub struct Cli {
53    #[command(subcommand)]
54    pub command: Commands,
55}
56
57#[derive(Subcommand)]
58pub enum Commands {
59    /// Split a SQL dump into individual table files
60    #[command(visible_alias = "sp")]
61    #[command(after_help = "\x1b[1mExamples:\x1b[0m
62  sql-splitter split dump.sql -o tables/
63  sql-splitter split dump.sql.gz -o tables/ --tables users,orders
64  sql-splitter split dump.zip -o tables/
65  sql-splitter split dump.sql -o schema/ --schema-only
66  sql-splitter split dump.sql -o tables/ --compress zstd
67  sql-splitter split dump.sql -o dump.tar.gz
68  sql-splitter split dump.sql -o /mnt/usb/tables/ --io-strategy hdd
69  sql-splitter split \"backups/*.sql\" -o out/ --fail-fast")]
70    Split(split::SplitArgs),
71
72    /// Analyze a SQL dump and display table statistics
73    #[command(visible_alias = "an")]
74    #[command(after_help = "\x1b[1mExamples:\x1b[0m
75  sql-splitter analyze dump.sql
76  sql-splitter analyze dump.sql.gz --progress
77  sql-splitter analyze \"dumps/*.sql\" --json")]
78    Analyze(analyze::AnalyzeArgs),
79
80    /// Merge split SQL files back into a single dump
81    #[command(visible_alias = "mg")]
82    #[command(after_help = "\x1b[1mExamples:\x1b[0m
83  sql-splitter merge tables/ -o restored.sql
84  sql-splitter merge tables/ -o restored.sql --transaction
85  sql-splitter merge tables/ -o partial.sql --tables users,orders
86  sql-splitter merge tables/ -o clean.sql --exclude logs,cache")]
87    Merge(merge::MergeArgs),
88
89    /// Create a reduced dataset preserving FK relationships
90    #[command(visible_alias = "sa")]
91    #[command(after_help = "\x1b[1mExamples:\x1b[0m
92  sql-splitter sample dump.sql -o dev.sql --percent 10
93  sql-splitter sample dump.sql -o dev.sql --rows 1000 --preserve-relations
94  sql-splitter sample dump.sql -o dev.sql --percent 5 --seed 42
95  sql-splitter sample dump.sql -o dev.sql --tables users,orders --percent 20")]
96    Sample(sample::SampleArgs),
97
98    /// Extract tenant-specific data from a multi-tenant dump
99    #[command(visible_alias = "sh")]
100    #[command(after_help = "\x1b[1mExamples:\x1b[0m
101  sql-splitter shard dump.sql -o tenant.sql --tenant-value 123
102  sql-splitter shard dump.sql -o tenant.sql --tenant-column company_id --tenant-value 42
103  sql-splitter shard dump.sql -o shards/ --tenant-values \"1,2,3\"")]
104    Shard(shard::ShardArgs),
105
106    /// Convert a SQL dump between MySQL, PostgreSQL, SQLite, and MSSQL
107    #[command(visible_alias = "cv")]
108    #[command(after_help = "\x1b[1mExamples:\x1b[0m
109  sql-splitter convert mysql.sql --to postgres -o pg.sql
110  sql-splitter convert pg_dump.sql --to mysql -o mysql.sql
111  sql-splitter convert dump.sql --from mysql --to sqlite -o sqlite.sql
112  sql-splitter convert mysql.sql --to postgres | psql mydb")]
113    Convert(convert::ConvertArgs),
114
115    /// Validate SQL dump syntax, encoding, and data integrity
116    #[command(visible_alias = "val")]
117    #[command(after_help = "\x1b[1mExamples:\x1b[0m
118  sql-splitter validate dump.sql
119  sql-splitter validate dump.sql --strict
120  sql-splitter validate \"dumps/*.sql\" --json --fail-fast
121  sql-splitter validate dump.sql --no-fk-checks")]
122    Validate(validate::ValidateArgs),
123
124    /// Compare two SQL dumps and report schema + data differences
125    #[command(visible_alias = "df")]
126    #[command(after_help = "\x1b[1mExamples:\x1b[0m
127  sql-splitter diff old.sql new.sql
128  sql-splitter diff old.sql new.sql --schema-only
129  sql-splitter diff old.sql new.sql --format sql -o migration.sql
130  sql-splitter diff old.sql new.sql --verbose --ignore-columns \"*.updated_at\"
131  sql-splitter diff old.sql new.sql --primary-key logs:timestamp+message")]
132    Diff(diff::DiffArgs),
133
134    /// Redact sensitive data (PII) from SQL dumps
135    #[command(visible_alias = "rd")]
136    #[command(after_help = "\x1b[1mExamples:\x1b[0m
137  sql-splitter redact dump.sql -o safe.sql --config redact.yaml
138  sql-splitter redact dump.sql -o safe.sql --null \"*.ssn\" --hash \"*.email\"
139  sql-splitter redact dump.sql --generate-config -o redact.yaml
140  sql-splitter redact dump.sql -o safe.sql --config redact.yaml --seed 42")]
141    Redact(redact::RedactArgs),
142
143    /// Generate synthetic SQL data from a model
144    #[command(visible_alias = "gen")]
145    #[command(after_help = "\x1b[1mExamples:\x1b[0m
146  sql-splitter generate --config model.yaml -o synthetic.sql
147  sql-splitter generate --config model.yaml --check
148  sql-splitter generate --config model.yaml --dry-run
149  sql-splitter generate --config model.yaml --seed 42 -o synthetic.sql
150  sql-splitter generate --config model.yaml --json -o synthetic.sql")]
151    Generate(generate::GenerateArgs),
152
153    /// Generate Entity Relationship Diagram (ERD) from SQL dump
154    #[command(visible_alias = "gr")]
155    #[command(after_help = "\x1b[1mExamples:\x1b[0m
156  sql-splitter graph dump.sql -o schema.html
157  sql-splitter graph dump.sql -o schema.mmd --format mermaid
158  sql-splitter graph dump.sql -o schema.png --render
159  sql-splitter graph dump.sql --cycles-only
160  sql-splitter graph dump.sql --table users --transitive")]
161    Graph(graph::GraphArgs),
162
163    /// Output SQL dump with tables in topological FK order
164    #[command(visible_alias = "ord")]
165    #[command(after_help = "\x1b[1mExamples:\x1b[0m
166  sql-splitter order dump.sql -o ordered.sql
167  sql-splitter order dump.sql --check
168  sql-splitter order dump.sql --dry-run
169  sql-splitter order dump.sql --reverse")]
170    Order(order::OrderArgs),
171
172    /// Query SQL dumps using DuckDB's analytical engine
173    #[cfg(feature = "duckdb-query")]
174    #[command(visible_alias = "qy")]
175    #[command(after_help = "\x1b[1mExamples:\x1b[0m
176  sql-splitter query dump.sql \"SELECT COUNT(*) FROM users\"
177  sql-splitter query dump.sql \"SELECT * FROM orders WHERE total > 100\" -f json
178  sql-splitter query dump.sql \"SELECT * FROM users LIMIT 10\" -o results.csv -f csv
179  sql-splitter query dump.sql --interactive
180  sql-splitter query huge.sql \"SELECT ...\" --disk
181  sql-splitter query dump.sql \"SELECT ...\" --cache
182  sql-splitter query --list-cache")]
183    Query(query::QueryArgs),
184
185    /// Generate JSON schemas for --json output types (developer tool)
186    #[command(hide = true)]
187    Schema {
188        /// Output directory for schema files
189        #[arg(short, long, default_value = "schemas", value_hint = ValueHint::DirPath)]
190        output: PathBuf,
191
192        /// Generate schema for a specific command only
193        #[arg(short, long)]
194        command: Option<String>,
195
196        /// Print schemas to stdout instead of writing files
197        #[arg(long)]
198        stdout: bool,
199
200        /// List available schema names
201        #[arg(long)]
202        list: bool,
203    },
204
205    /// Generate man pages (developer tool)
206    #[cfg(feature = "man-pages")]
207    #[command(hide = true)]
208    Man {
209        /// Output directory for man pages
210        #[arg(short, long, default_value = "man", value_hint = ValueHint::DirPath)]
211        output: PathBuf,
212    },
213
214    /// Generate shell completion scripts
215    #[command(after_help = "\x1b[1mInstallation:\x1b[0m
216  Bash:
217    sql-splitter completions bash > /etc/bash_completion.d/sql-splitter
218    # or: sql-splitter completions bash >> ~/.bashrc
219
220  Zsh:
221    sql-splitter completions zsh > \"${fpath[1]}/_sql-splitter\"
222    # or for oh-my-zsh: sql-splitter completions zsh > ~/.oh-my-zsh/completions/_sql-splitter
223
224  Fish:
225    sql-splitter completions fish > ~/.config/fish/completions/sql-splitter.fish
226
227  PowerShell:
228    sql-splitter completions powershell >> $PROFILE")]
229    Completions {
230        /// Target shell
231        #[arg(value_enum)]
232        shell: Shell,
233    },
234}
235
236/// Dispatch to the selected subcommand, returning the process exit code.
237///
238/// Commands that can partially fail (multi-file batches, validation, order
239/// --check) report failure through the returned [`ExitCode`] instead of
240/// calling `std::process::exit`, so destructors (tempdir cleanup, buffered
241/// writers) always run and the cmd layer stays usable as a library.
242pub fn run(cli: Cli) -> anyhow::Result<ExitCode> {
243    match cli.command {
244        Commands::Split(args) => split::run(args),
245        Commands::Analyze(args) => analyze::run(args),
246        Commands::Merge(args) => merge::run(args).map(|()| ExitCode::SUCCESS),
247        Commands::Sample(args) => sample::run(args).map(|()| ExitCode::SUCCESS),
248        Commands::Shard(args) => shard::run(args).map(|()| ExitCode::SUCCESS),
249        Commands::Convert(args) => convert::run(args),
250        Commands::Validate(args) => validate::run(args),
251        Commands::Diff(args) => diff::run(args).map(|()| ExitCode::SUCCESS),
252        Commands::Redact(args) => redact::run(args).map(|()| ExitCode::SUCCESS),
253        Commands::Generate(args) => generate::run(args),
254        Commands::Graph(args) => graph::run(args).map(|()| ExitCode::SUCCESS),
255        Commands::Order(args) => order::run(args),
256        #[cfg(feature = "duckdb-query")]
257        Commands::Query(args) => query::run(args).map(|()| ExitCode::SUCCESS),
258        Commands::Schema {
259            output,
260            command,
261            stdout,
262            list,
263        } => run_schema(output, command, stdout, list).map(|()| ExitCode::SUCCESS),
264        #[cfg(feature = "man-pages")]
265        Commands::Man { output } => crate::man::generate(&output).map(|()| ExitCode::SUCCESS),
266        Commands::Completions { shell } => {
267            generate(
268                shell,
269                &mut Cli::command(),
270                "sql-splitter",
271                &mut io::stdout(),
272            );
273            Ok(ExitCode::SUCCESS)
274        }
275    }
276}
277
278fn run_schema(
279    output_dir: PathBuf,
280    command: Option<String>,
281    to_stdout: bool,
282    list: bool,
283) -> anyhow::Result<()> {
284    use crate::json_schema;
285    use std::fs;
286
287    if list {
288        let schemas = json_schema::all_schemas();
289        for name in schemas.keys() {
290            println!("{}", name);
291        }
292        return Ok(());
293    }
294
295    if let Some(cmd) = command {
296        let schema = json_schema::get_schema(&cmd).ok_or_else(|| {
297            anyhow::anyhow!(
298                "Unknown command: {}. Use --list to see available schemas.",
299                cmd
300            )
301        })?;
302
303        let json = serde_json::to_string_pretty(&schema)?;
304
305        if to_stdout {
306            println!("{}", json);
307        } else {
308            fs::create_dir_all(&output_dir)?;
309            let path = output_dir.join(format!("{}.schema.json", cmd));
310            fs::write(&path, json)?;
311            eprintln!("Wrote: {}", path.display());
312        }
313    } else if to_stdout {
314        let schemas = json_schema::all_schemas();
315        for (name, schema) in &schemas {
316            let json = serde_json::to_string_pretty(schema)?;
317            println!("// {}.schema.json\n{}\n", name, json);
318        }
319    } else {
320        let schemas = json_schema::all_schemas();
321        fs::create_dir_all(&output_dir)?;
322        for (name, schema) in &schemas {
323            let json = serde_json::to_string_pretty(schema)?;
324            let path = output_dir.join(format!("{}.schema.json", name));
325            fs::write(&path, json)?;
326            eprintln!("Wrote: {}", path.display());
327        }
328    }
329
330    Ok(())
331}