mod db;
use anyhow::bail;
use clap::{Parser, ValueEnum};
use std::path::Path;
#[derive(ValueEnum, Clone)]
enum DbType {
Sqlite,
Mysql,
Postgres,
}
#[derive(ValueEnum, Clone)]
enum OutputFormat {
Csv,
Xlsx,
}
#[derive(Parser)]
#[command(name = "sql-export")]
struct Cli {
#[arg(long, value_enum)]
db_type: DbType,
#[arg(long)]
conn: String,
#[arg(long, short)]
query: String,
#[arg(long, short)]
output: String,
#[arg(long, value_enum)]
format: Option<OutputFormat>,
#[arg(long)]
headers: Option<String>,
#[arg(long, default_value = "500")]
batch_size: usize,
}
fn detect_format(path: &str) -> OutputFormat {
let ext = Path::new(path)
.extension()
.and_then(|e| e.to_str())
.unwrap_or("");
match ext.to_lowercase().as_str() {
"xlsx" => OutputFormat::Xlsx,
_ => OutputFormat::Csv,
}
}
fn parse_headers(raw: &str) -> Vec<String> {
raw.split(',').map(|s| s.trim().to_string()).collect()
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let cli = Cli::parse();
if cli.batch_size < 1 || cli.batch_size > 1000 {
bail!(
"--batch-size 必须在 1-1000 之间,当前值: {}",
cli.batch_size
);
}
let format = cli.format.unwrap_or_else(|| detect_format(&cli.output));
let custom_headers: Option<Vec<String>> = cli.headers.as_ref().map(|h| parse_headers(h));
let bs = cli.batch_size;
let row_count = match (&cli.db_type, &format) {
(DbType::Sqlite, OutputFormat::Csv) => {
db::export_sqlite_to_csv(&cli.conn, &cli.query, custom_headers, &cli.output, bs)?
}
(DbType::Sqlite, OutputFormat::Xlsx) => {
db::export_sqlite_to_xlsx(&cli.conn, &cli.query, custom_headers, &cli.output, bs)?
}
(DbType::Mysql, OutputFormat::Csv) => {
db::export_mysql_to_csv(&cli.conn, &cli.query, custom_headers, &cli.output, bs).await?
}
(DbType::Mysql, OutputFormat::Xlsx) => {
db::export_mysql_to_xlsx(&cli.conn, &cli.query, custom_headers, &cli.output, bs).await?
}
(DbType::Postgres, OutputFormat::Csv) => {
db::export_postgres_to_csv(&cli.conn, &cli.query, custom_headers, &cli.output, bs)
.await?
}
(DbType::Postgres, OutputFormat::Xlsx) => {
db::export_postgres_to_xlsx(&cli.conn, &cli.query, custom_headers, &cli.output, bs)
.await?
}
};
println!("已导出 {row_count} 行数据到 {}", cli.output);
Ok(())
}