sql-export 0.0.1

一个用于导出SQL数据的Rust库
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,
}

/// SQL 导出工具 — 将查询结果导出为 CSV 或 XLSX 文件
#[derive(Parser)]
#[command(name = "sql-export")]
struct Cli {
    /// 数据库类型: sqlite | mysql | postgres
    #[arg(long, value_enum)]
    db_type: DbType,

    /// 连接信息(SQLite 文件路径 或 MySQL/PG 连接 URL)
    #[arg(long)]
    conn: String,

    /// SQL 查询语句
    #[arg(long, short)]
    query: String,

    /// 输出文件路径(.csv 或 .xlsx)
    #[arg(long, short)]
    output: String,

    /// 输出格式(csv | xlsx,默认根据文件扩展名判断)
    #[arg(long, value_enum)]
    format: Option<OutputFormat>,

    /// 自定义表头,逗号分隔(不传则使用数据库列名)
    #[arg(long)]
    headers: Option<String>,

    /// 批处理大小(1-1000,默认 500)
    #[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(())
}