Skip to main content

sql_splitter/cmd/
mod.rs

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