dbcli 0.1.0

Convert SQL query results to JSON without struct mapping, supporting MySQL/PostgreSQL/SQLite/Odbc
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
//! # dbcli CLI
//!
//! A command-line tool for executing SQL statements and displaying results
//! as a formatted table (TTY) or JSON (piped/scripted).
//!
//! ## Usage
//!
//! ```text
//! # Single-shot mode
//! dbcli --url <DATABASE_URL> --sql <SQL>
//!
//! # Interactive REPL mode (omit --sql)
//! dbcli --url <DATABASE_URL>
//!
//! # Use DATABASE_URL environment variable
//! DATABASE_URL=postgres://user:pass@localhost/mydb dbcli --sql "SELECT 1"
//! DATABASE_URL=postgres://user:pass@localhost/mydb dbcli
//! ```
//!
//! ## Output Modes
//!
//! - **Table** (default when stdout is a TTY): UTF-8 bordered table with straight corners
//! - **JSON** (default when stdout is piped): pretty-printed JSON array
//!
//! Use `--json` or `--table` to override auto-detection.
//!
//! ## Examples
//!
//! ```text
//! dbcli --url postgres://user:pass@localhost/mydb --sql "SELECT * FROM users"
//! dbcli --url sqlite:///tmp/test.db --sql "SELECT id, name FROM items" --json
//! dbcli --url mysql://root:pass@localhost/app --sql "SHOW TABLES" | jq .
//! dbcli --url postgres://user:pass@localhost/mydb   # enters REPL mode
//! ```

use clap::Parser;
use comfy_table::{Attribute, Cell, Color, ContentArrangement, Table, presets::UTF8_FULL_CONDENSED};
use dbcli::SqlResult;
use dbcli::column_info::ColumnBaseInfo;
use rustyline::DefaultEditor;
use rustyline::error::ReadlineError;
use std::io::IsTerminal;

// ─── CLI Arguments ────────────────────────────────────────────────────────────

/// Execute SQL and output results as a formatted table or JSON.
#[derive(Parser)]
#[command(
    name = "dbcli",
    version,
    about = "Execute SQL and output results as JSON or formatted table",
    long_about = "Execute one or more SQL statements against MySQL, PostgreSQL, or SQLite.\n\
                  Output is auto-detected: table when stdout is a TTY, JSON when piped.\n\
                  Use --json or --table to override.",
    after_help = "EXAMPLES:\n  \
                  dbcli -u postgres://user:pass@localhost/mydb -s \"SELECT * FROM users\"\n  \
                  dbcli --connect  (test database connection only)\n  \
                  dbcli  (enter interactive REPL mode)\n  \
                  echo \"SELECT 1\" | dbcli -u sqlite://test.db --json"
)]
struct Cli {
    /// Database connection URL.
    /// If not provided, reads from DATABASE_URL environment variable.
    ///
    /// Supported schemes:
    ///   postgres://user:pass@host:5432/dbname
    ///   mysql://user:pass@host:3306/dbname
    ///   sqlite:///path/to/file.db (or bare file path)
    ///   odbc://path/to/file.mdb (Access database via ODBC)
    ///   odbc://path/to/file.xlsx (Excel spreadsheet via ODBC)
    ///   Driver={...};DBQ=... (direct ODBC connection string)
    #[arg(short, long, env = "DATABASE_URL")]
    url: String,

    /// SQL statement(s) to execute.
    /// Multiple statements can be separated by `;`.
    /// If omitted, enters interactive REPL mode.
    #[arg(short, long)]
    sql: Option<String>,

    /// Test database connection and exit.
    /// Useful for verifying credentials and network connectivity.
    #[arg(long, visible_alias = "conn", visible_alias = "con")]
    connect: bool,

    /// Force JSON output even when stdout is a TTY.
    #[arg(long)]
    json: bool,

    /// Force table output even when stdout is piped.
    #[arg(long)]
    table: bool,

    /// Maximum rows to display in table mode.
    /// Use 0 for unlimited. JSON mode is never limited.
    /// Default: 1000
    #[arg(short, long, default_value_t = 1000)]
    limit: usize,

    /// Maximum character width per column in table mode.
    /// Content exceeding this width is truncated with "...".
    /// Default: 0 (auto-detect from terminal width).
    /// Set a specific value to override, e.g. 80.
    #[arg(long, visible_alias = "mcw", default_value_t = 0)]
    max_col_width: usize,
}

// ─── Output Mode ──────────────────────────────────────────────────────────────

enum OutputMode {
    /// Column-aligned ASCII table, suitable for interactive terminal use.
    Table,
    /// Pretty-printed JSON array, suitable for piping or scripting.
    Json,
}

/// Detect the appropriate output mode based on CLI flags and stdout TTY status.
///
/// Priority:
/// 1. `--json` flag → JSON
/// 2. `--table` flag → Table
/// 3. stdout is a TTY → Table
/// 4. stdout is piped → JSON
fn detect_output_mode(cli: &Cli) -> OutputMode {
    if cli.json {
        OutputMode::Json
    } else if cli.table {
        OutputMode::Table
    } else if std::io::stdout().is_terminal() {
        OutputMode::Table
    } else {
        OutputMode::Json
    }
}

// ─── Locale Detection ─────────────────────────────────────────────────────────

/// Detect whether the current locale is Chinese.
/// Checks LC_ALL, LANG, and LANGUAGE environment variables in order.
fn is_chinese_locale() -> bool {
    for var in &["LC_ALL", "LANG", "LANGUAGE"] {
        if let Ok(val) = std::env::var(var) {
            let lower = val.to_lowercase();
            if lower.starts_with("zh") {
                return true;
            }
        }
    }
    false
}

// ─── Localized Messages ───────────────────────────────────────────────────────

/// Runtime message strings that adapt to the detected locale.
/// Help text and clap metadata always remain in English.
struct Messages {
    chinese: bool,
}

impl Messages {
    fn new() -> Self {
        Self { chinese: is_chinese_locale() }
    }

    fn connection_successful(&self) -> &str {
        if self.chinese { "连接成功。" } else { "Connection successful." }
    }

    fn backend_label(&self) -> &str {
        if self.chinese { "数据库后端" } else { "Backend" }
    }

    fn repl_welcome(&self) -> &str {
        if self.chinese {
            "dbcli 交互模式。输入 SQL 语句以 `;` 结尾执行。"
        } else {
            "dbcli interactive mode. Type SQL followed by `;` to execute."
        }
    }

    fn repl_quit_hint(&self) -> &str {
        if self.chinese {
            "输入 exit、quit 或 \\q 退出。"
        } else {
            "Commands: exit, quit, \\q to quit."
        }
    }

    fn supported_backends(&self) -> &str {
        if self.chinese { "支持的后端" } else { "Supported backends" }
    }

    fn no_backend_warning(&self) -> &str {
        if self.chinese {
            "警告:未启用任何数据库后端。请在编译时启用 mysql、postgres、sqlite 或 odbc feature。"
        } else {
            "Warning: No database backend enabled. Enable mysql, postgres, sqlite, or odbc feature."
        }
    }

    fn affected_rows(&self, n: u64) -> String {
        if self.chinese {
            format!("影响 {}", n)
        } else {
            format!("Affected {} rows", n)
        }
    }

    fn rows_count(&self, n: usize) -> String {
        if self.chinese {
            format!("({} 行)", n)
        } else {
            format!("({} rows)", n)
        }
    }

    fn error_prefix(&self) -> &str {
        if self.chinese { "错误" } else { "Error" }
    }

    fn connecting(&self) -> &str {
        if self.chinese { "正在连接数据库..." } else { "Connecting to database..." }
    }

    fn connection_failed(&self) -> &str {
        if self.chinese { "连接失败" } else { "Connection failed" }
    }

    fn rows_truncated(&self, shown: usize, total: usize) -> String {
        if self.chinese {
            format!("... 已省略 {} 行(共 {} 行,使用 --limit 调整或 --json 获取全部)", total - shown, total)
        } else {
            format!("... {} more rows omitted ({} total, use --limit to adjust or --json for all)", total - shown, total)
        }
    }
}

// ─── Argument Normalization ───────────────────────────────────────────────────

/// Pre-process command-line arguments to normalize flag names to lowercase.
/// This allows case-insensitive flags like --JSON, --Table, --Url, etc.
/// Value arguments (the argument after a flag) are left untouched.
fn normalize_args() -> Vec<String> {
    let mut args: Vec<String> = std::env::args().collect();
    let mut i = 1; // skip argv[0]
    while i < args.len() {
        if args[i].starts_with('-') {
            // Handle --flag=value format: only lowercase the flag part.
            if let Some(eq_pos) = args[i].find('=') {
                let (flag_part, value_part) = args[i].split_at(eq_pos);
                args[i] = format!("{}{}", flag_part.to_lowercase(), value_part);
            } else {
                args[i] = args[i].to_lowercase();
            }
            // Map -v to -V so that clap recognizes it as --version.
            // clap built-in version flag is uppercase -V; our normalize lowercases it.
            if args[i] == "-v" {
                args[i] = "-V".to_string();
            }
            // If this is a flag that takes a value (not a boolean flag),
            // skip the next arg to preserve value case.
            // Known value flags: -u/--url, -s/--sql, -l/--limit
            let lower = args[i].as_str();
            if matches!(lower, "-u" | "--url" | "-s" | "--sql" | "-l" | "--limit" | "--max-col-width" | "--mcw") {
                i += 1; // skip the value argument
            }
        }
        i += 1;
    }
    args
}

// ─── Terminal Width Detection ───────────────────────────────────────────────

/// Calculate the maximum width allowed for a single cell.
///
/// When `max_col_width > 0`: use the user-specified value.
/// When `max_col_width == 0` (auto): use half the terminal width as the upper bound.
/// This prevents any single cell from being so wide that comfy-table wraps it
/// into multiple lines, while letting comfy-table handle optimal column sizing.
fn max_cell_width(max_col_width: usize) -> usize {
    if max_col_width > 0 {
        return max_col_width;
    }
    let term_width = crossterm::terminal::size()
        .map(|(w, _)| w as usize)
        .unwrap_or(120);
    // Use half terminal width as the max for any single cell.
    // This ensures no single column dominates the entire table width.
    (term_width / 2).max(30)
}

// ─── Table Rendering ──────────────────────────────────────────────────────────

/// Format a single cell value as a display string.
///
/// - `NULL` / missing → `"NULL"`
/// - strings → value as-is
/// - numbers / booleans → `to_string()`
/// - nested JSON → compact JSON string
fn format_cell(value: Option<&serde_json::Value>) -> String {
    match value {
        None => "NULL".to_string(),
        Some(serde_json::Value::Null) => "NULL".to_string(),
        Some(serde_json::Value::String(s)) => s.clone(),
        Some(serde_json::Value::Number(n)) => n.to_string(),
        Some(serde_json::Value::Bool(b)) => b.to_string(),
        Some(v) => v.to_string(),
    }
}

/// Truncate a string to at most `max_width` characters.
/// If the string exceeds `max_width`, it is cut and "..." is appended.
/// Uses `chars()` to correctly handle multi-byte characters (e.g. CJK).
/// `max_width == 0` means unlimited (no truncation).
fn truncate_cell(s: &str, max_width: usize) -> String {
    if max_width == 0 || s.chars().count() <= max_width {
        s.to_string()
    } else {
        let truncated: String = s.chars().take(max_width.saturating_sub(3)).collect();
        format!("{}...", truncated)
    }
}

/// Print query results as a UTF-8 bordered table using comfy-table.
///
/// Output format:
/// ```text
/// ┌───┬────┬───────┬────────────────────┐
/// │ # │ id │ name  │ email              │
/// ├───┼────┼───────┼────────────────────┤
/// │ 1 │ 1  │ Alice │ alice@example.com  │
/// │ 2 │ 2  │ Bob   │ bob@example.com    │
/// └───┴────┴───────┴────────────────────┘
/// (2 rows)
/// ```
///
/// Color scheme:
/// - `#` header and row numbers → DarkGrey
/// - Column name headers → Cyan + Bold
/// - NULL values → DarkGrey
/// - Normal data → default color
fn print_table(data: &[serde_json::Value], columns: &[ColumnBaseInfo], msg: &Messages, limit: usize, max_col_width: usize) {
    if columns.is_empty() {
        println!("{}", msg.rows_count(0));
        return;
    }

    let display_data = if limit > 0 && data.len() > limit {
        &data[..limit]
    } else {
        data
    };

    // Get terminal width for table sizing.
    let term_width = crossterm::terminal::size()
        .map(|(w, _)| w as usize)
        .unwrap_or(120);

    // Max width per cell: prevents any single cell from causing line wrapping.
    let cell_max = max_cell_width(max_col_width);

    let mut table = Table::new();
    table
        .load_preset(UTF8_FULL_CONDENSED)
        .set_content_arrangement(ContentArrangement::Dynamic)
        .set_width(term_width as u16); // Fill the terminal width

    // Build header row: # column (dark grey) + column names (cyan + bold).
    let mut header_cells = vec![
        Cell::new("#")
            .fg(Color::DarkGrey)
            .add_attribute(Attribute::Bold)
    ];
    for col in columns {
        header_cells.push(
            Cell::new(&col.name)
                .fg(Color::Cyan)
                .add_attribute(Attribute::Bold)
        );
    }
    table.set_header(header_cells);

    // Add data rows — only truncate cells that exceed cell_max.
    for (idx, row) in display_data.iter().enumerate() {
        if let Some(obj) = row.as_object() {
            let mut cells = vec![
                Cell::new(idx + 1).fg(Color::DarkGrey)
            ];
            for col in columns.iter() {
                let val = format_cell(obj.get(&col.name));
                let is_null = val == "NULL";
                let val = truncate_cell(&val, cell_max);
                // Render NULL values in dark grey to distinguish from real data.
                let cell = if is_null {
                    Cell::new(val).fg(Color::DarkGrey)
                } else {
                    Cell::new(val)
                };
                cells.push(cell);
            }
            table.add_row(cells);
        }
    }

    println!("{table}");

    // Show truncation notice if data was limited (output to stderr to avoid polluting pipes).
    if limit > 0 && data.len() > limit {
        eprintln!("{}", msg.rows_truncated(limit, data.len()));
    }
    // Always show total row count.
    println!("{}", msg.rows_count(data.len()));
}

// ─── JSON Output ──────────────────────────────────────────────────────────────

/// Print all SQL results as a pretty-printed JSON array.
fn print_json(results: &[SqlResult]) {
    println!("{}", serde_json::to_string_pretty(results).unwrap_or_else(|e| {
        format!("{{\"error\": \"{}\"}}", e)
    }));
}

// ─── Result Printing ──────────────────────────────────────────────────────────

/// Print SQL results in the appropriate output mode.
///
/// Used by both single-shot mode and REPL mode to ensure consistent output.
fn print_results(results: &[SqlResult], mode: &OutputMode, msg: &Messages, limit: usize, max_col_width: usize) {
    match mode {
        OutputMode::Json => {
            // JSON output is never row-limited.
            print_json(results);
        }
        OutputMode::Table => {
            for (i, result) in results.iter().enumerate() {
                if i > 0 {
                    println!();
                }
                match result {
                    SqlResult::Query { data, columns } => {
                        print_table(data, columns, msg, limit, max_col_width);
                    }
                    SqlResult::Execute { rows_affected } => {
                        println!("{}", msg.affected_rows(*rows_affected));
                    }
                }
            }
        }
    }
}

// ─── ODBC Detection ──────────────────────────────────────────────────────────

/// Detect whether a URL refers to an ODBC data source and return the
/// corresponding ODBC connection string, or `None` if the URL is not ODBC.
///
/// Detection rules (case-insensitive):
/// - URL contains `Driver=`  → use as-is (direct ODBC connection string)
/// - URL starts with `odbc://`:
///   - If the remainder contains `Driver=` → strip prefix and use as-is
///   - Otherwise treat as a file path and auto-detect driver from extension:
///     - `.mdb` / `.accdb` → `Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=<path>`
///     - `.xls` / `.xlsx` / `.xlsb` / `.xlsm` → `Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=<path>;ReadOnly=0`
///     - Other extensions → default to Access driver (use full `Driver=` string for other sources)
#[cfg(feature = "odbc")]
fn detect_odbc_connection_string(url: &str) -> Option<String> {
    let url_lower = url.to_lowercase();

    // Direct ODBC connection string: contains Driver= keyword.
    if url_lower.contains("driver=") {
        return Some(url.to_owned());
    }

    // odbc:// scheme.
    if url_lower.starts_with("odbc://") {
        let remainder = &url["odbc://".len()..];
        if remainder.to_lowercase().contains("driver=") {
            return Some(remainder.to_owned());
        }
        // Auto-detect driver from file extension.
        let conn_str = odbc_connection_string_from_path(remainder);
        return Some(conn_str);
    }

    None
}

/// Generate an ODBC connection string from a file path by detecting the file extension.
///
/// Supported extensions:
/// - `.mdb` / `.accdb` → Microsoft Access Driver
/// - `.xls` / `.xlsx` / `.xlsb` / `.xlsm` → Microsoft Excel Driver
/// - Other → default to Access driver (user must use `Driver=` explicitly for other sources)
#[cfg(feature = "odbc")]
fn odbc_connection_string_from_path(path: &str) -> String {
    let path_lower = path.to_lowercase();
    if path_lower.ends_with(".mdb") || path_lower.ends_with(".accdb") {
        format!(
            "Driver={{Microsoft Access Driver (*.mdb, *.accdb)}};DBQ={};",
            path
        )
    } else if path_lower.ends_with(".xls")
        || path_lower.ends_with(".xlsx")
        || path_lower.ends_with(".xlsb")
        || path_lower.ends_with(".xlsm")
    {
        format!(
            "Driver={{Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)}};DBQ={};ReadOnly=0;",
            path
        )
    } else {
        // Fallback: default to Access driver.
        // The user should use a full connection string with Driver= for unsupported extensions.
        format!(
            "Driver={{Microsoft Access Driver (*.mdb, *.accdb)}};DBQ={};",
            path
        )
    }
}

// ─── ODBC REPL ────────────────────────────────────────────────────────────────

/// Run interactive REPL mode for ODBC data sources.
///
/// Mirrors the structure of [`run_repl`] but uses
/// [`dbcli::execute::odbc::execute_raw_sql`] instead of a pooled backend.
#[cfg(feature = "odbc")]
async fn run_repl_odbc(
    connection_string: &str,
    mode: &OutputMode,
    msg: &Messages,
    limit: usize,
    max_col_width: usize,
) -> anyhow::Result<()> {
    let mut rl = DefaultEditor::new()?;

    let history_file = history_file_path();
    let _ = rl.load_history(&history_file);

    eprintln!("{}", msg.repl_welcome());
    eprintln!("{}", msg.repl_quit_hint());

    let mut backends = Vec::new();
    backends.push("ODBC");
    eprintln!("{}: {}", msg.supported_backends(), backends.join(", "));
    eprintln!();

    let mut sql_buffer = String::new();

    loop {
        let prompt = if sql_buffer.is_empty() {
            "dbcli> "
        } else {
            "      -> "
        };

        match rl.readline(prompt) {
            Ok(line) => {
                let trimmed = line.trim();

                if sql_buffer.is_empty() {
                    match trimmed.to_lowercase().as_str() {
                        "exit" | "quit" | "\\q" | "exit;" | "quit;" => break,
                        "" => continue,
                        _ => {}
                    }
                }

                sql_buffer.push_str(trimmed);
                sql_buffer.push('\n');

                if trimmed.ends_with(';') {
                    let sql = sql_buffer.trim().to_string();
                    sql_buffer.clear();

                    let _ = rl.add_history_entry(&sql);

                    match dbcli::execute::odbc::execute_raw_sql(connection_string, &sql).await {
                        Ok(results) => {
                            print_results(&results, mode, msg, limit, max_col_width);
                            eprintln!();
                        }
                        Err(e) => {
                            eprintln!("{}: {}", msg.error_prefix(), e);
                            eprintln!();
                        }
                    }
                }
            }
            Err(ReadlineError::Interrupted) => {
                if !sql_buffer.is_empty() {
                    sql_buffer.clear();
                    eprintln!();
                } else {
                    break;
                }
            }
            Err(ReadlineError::Eof) => {
                eprintln!();
                break;
            }
            Err(err) => {
                eprintln!("{}: {}", msg.error_prefix(), err);
                break;
            }
        }
    }

    let _ = rl.save_history(&history_file);

    Ok(())
}

// ─── Database Connection Pool ─────────────────────────────────────────────────

/// Unified database pool enum covering all supported backends.
/// Each variant is guarded by its corresponding feature flag.
/// The entire enum is only compiled when at least one sqlx backend is enabled.
#[cfg(any(feature = "postgres", feature = "mysql", feature = "sqlite"))]
enum DbPool {
    #[cfg(feature = "postgres")]
    Postgres(sqlx::postgres::PgPool),
    #[cfg(feature = "mysql")]
    Mysql(sqlx::mysql::MySqlPool),
    #[cfg(feature = "sqlite")]
    Sqlite(sqlx::sqlite::SqlitePool),
}

/// Create a database connection pool from a URL.
///
/// Detects the database backend from the URL scheme:
/// - `postgres://` / `postgresql://` → PostgreSQL  (requires `postgres` feature)
/// - `mysql://` → MySQL                             (requires `mysql` feature)
/// - `sqlite://` / bare file path → SQLite          (requires `sqlite` feature)
#[cfg(any(feature = "postgres", feature = "mysql", feature = "sqlite"))]
async fn connect(url: &str) -> anyhow::Result<DbPool> {
    #[cfg(feature = "postgres")]
    if url.starts_with("postgres://") || url.starts_with("postgresql://") {
        let pool = sqlx::postgres::PgPoolOptions::new()
            .max_connections(1)
            .connect(url)
            .await?;
        return Ok(DbPool::Postgres(pool));
    }

    #[cfg(feature = "mysql")]
    if url.starts_with("mysql://") {
        let pool = sqlx::mysql::MySqlPoolOptions::new()
            .max_connections(1)
            .connect(url)
            .await?;
        return Ok(DbPool::Mysql(pool));
    }

    #[cfg(feature = "sqlite")]
    {
        // SQLite: accept sqlite:// URLs or bare file paths.
        let sqlite_url = if url.starts_with("sqlite://") {
            url.to_string()
        } else if !url.contains("://") {
            format!("sqlite://{}", url)
        } else {
            anyhow::bail!("Unsupported database URL scheme: {}", url);
        };
        let pool = sqlx::sqlite::SqlitePoolOptions::new()
            .max_connections(1)
            .connect(&sqlite_url)
            .await?;
        return Ok(DbPool::Sqlite(pool));
    }

    #[allow(unreachable_code)]
    {
        anyhow::bail!(
            "Unsupported or not compiled database URL: {}. \
             Enable the corresponding feature (mysql, postgres, sqlite) when building.",
            url
        );
    }
}

/// Execute a SQL string against an already-connected pool.
///
/// Dispatches to the appropriate backend execute function based on the pool variant.
#[cfg(any(feature = "postgres", feature = "mysql", feature = "sqlite"))]
async fn execute_sql(pool: &DbPool, sql: &str) -> anyhow::Result<Vec<SqlResult>> {
    match pool {
        #[cfg(feature = "postgres")]
        DbPool::Postgres(p) => dbcli::execute::postgres::execute_raw_sql(p, sql).await,
        #[cfg(feature = "mysql")]
        DbPool::Mysql(p) => dbcli::execute::mysql::execute_raw_sql(p, sql).await,
        #[cfg(feature = "sqlite")]
        DbPool::Sqlite(p) => dbcli::execute::sqlite::execute_raw_sql(p, sql).await,
    }
}

// ─── History File Path ────────────────────────────────────────────────────────

/// Get the history file path for REPL command history.
fn history_file_path() -> std::path::PathBuf {
    let home = std::env::var("HOME")
        .or_else(|_| std::env::var("USERPROFILE")) // Windows fallback
        .unwrap_or_else(|_| ".".to_string());
    std::path::PathBuf::from(home).join(".db-json_history")
}

// ─── Interactive REPL ─────────────────────────────────────────────────────────

/// Run interactive REPL mode with rustyline for line editing and history.
///
/// Reads SQL from stdin line by line, accumulates multi-line statements,
/// executes each complete statement (terminated by `;`), and displays results
/// in the chosen output mode.
///
/// ## Multi-line SQL
///
/// Lines are accumulated until a line ending with `;` is received. A
/// continuation prompt (`      -> `) is shown while the buffer is non-empty.
/// The complete statement is added to history as a single entry.
///
/// ## Exit commands
///
/// Type `exit`, `quit`, `\q` (or their `;`-suffixed variants) on an empty
/// buffer, Ctrl+C on an empty buffer, or Ctrl+D to quit.
///
/// ## Keyboard shortcuts
///
/// - Up/Down arrows: navigate command history
/// - Ctrl+C: clear current multi-line buffer (or exit if buffer is empty)
/// - Ctrl+D: exit immediately
/// - Standard readline line-editing keybindings
///
/// ## History persistence
///
/// History is loaded from `~/.db-json_history` on startup and saved on exit.
#[cfg(any(feature = "postgres", feature = "mysql", feature = "sqlite"))]
async fn run_repl(pool: &DbPool, mode: &OutputMode, msg: &Messages, limit: usize, max_col_width: usize) -> anyhow::Result<()> {
    let mut rl = DefaultEditor::new()?;

    // Try to load history from file (ignore errors if file doesn't exist).
    let history_file = history_file_path();
    let _ = rl.load_history(&history_file);

    eprintln!("{}", msg.repl_welcome());
    eprintln!("{}", msg.repl_quit_hint());

    // Show enabled database backends.
    let mut backends = Vec::new();
    #[cfg(feature = "postgres")]
    backends.push("PostgreSQL");
    #[cfg(feature = "mysql")]
    backends.push("MySQL");
    #[cfg(feature = "sqlite")]
    backends.push("SQLite");
    if backends.is_empty() {
        eprintln!("{}", msg.no_backend_warning());
    } else {
        eprintln!("{}: {}", msg.supported_backends(), backends.join(", "));
    }
    eprintln!();

    let mut sql_buffer = String::new();

    loop {
        let prompt = if sql_buffer.is_empty() {
            "dbcli> "
        } else {
            "      -> "
        };

        match rl.readline(prompt) {
            Ok(line) => {
                let trimmed = line.trim();

                // Check exit commands only when buffer is empty.
                if sql_buffer.is_empty() {
                    match trimmed.to_lowercase().as_str() {
                        "exit" | "quit" | "\\q" | "exit;" | "quit;" => break,
                        "" => continue,
                        _ => {}
                    }
                }

                sql_buffer.push_str(trimmed);
                sql_buffer.push('\n');

                // Execute once we have a complete statement (line ends with `;`).
                if trimmed.ends_with(';') {
                    let sql = sql_buffer.trim().to_string();
                    sql_buffer.clear();

                    // Add the complete statement to history as a single entry.
                    let _ = rl.add_history_entry(&sql);

                    match execute_sql(pool, &sql).await {
                        Ok(results) => {
                            print_results(&results, mode, msg, limit, max_col_width);
                            eprintln!();
                        }
                        Err(e) => {
                            eprintln!("{}: {}", msg.error_prefix(), e);
                            eprintln!();
                        }
                    }
                }
            }
            Err(ReadlineError::Interrupted) => {
                // Ctrl+C: clear current multi-line buffer, or exit if already empty.
                if !sql_buffer.is_empty() {
                    sql_buffer.clear();
                    eprintln!();
                } else {
                    break;
                }
            }
            Err(ReadlineError::Eof) => {
                // Ctrl+D: exit immediately.
                eprintln!();
                break;
            }
            Err(err) => {
                eprintln!("{}: {}", msg.error_prefix(), err);
                break;
            }
        }
    }

    // Save history to file for the next session.
    let _ = rl.save_history(&history_file);

    Ok(())
}

// ─── Entry Point ──────────────────────────────────────────────────────────────

/// sqlx 路径的核心逻辑,仅在至少启用一个 sqlx 后端时编译。
#[cfg(any(feature = "postgres", feature = "mysql", feature = "sqlite"))]
async fn run_sqlx(cli: &Cli, mode: &OutputMode, msg: &Messages) -> anyhow::Result<()> {
    eprintln!("{}", msg.connecting());
    let pool = match connect(&cli.url).await {
        Ok(pool) => {
            eprintln!("{}", msg.connection_successful());
            // Report the active backend type.
            let backend = match &pool {
                #[cfg(feature = "postgres")]
                DbPool::Postgres(_) => "PostgreSQL",
                #[cfg(feature = "mysql")]
                DbPool::Mysql(_) => "MySQL",
                #[cfg(feature = "sqlite")]
                DbPool::Sqlite(_) => "SQLite",
            };
            eprintln!("{}: {}", msg.backend_label(), backend);
            pool
        }
        Err(e) => {
            eprintln!("{}: {}", msg.connection_failed(), e);
            std::process::exit(1);
        }
    };

    // --connect: verify connection and exit immediately.
    if cli.connect {
        return Ok(());
    }

    if let Some(sql) = &cli.sql {
        // Single-shot mode: execute the given SQL and exit.
        let results = execute_sql(&pool, sql).await?;
        print_results(&results, mode, msg, cli.limit, cli.max_col_width);
    } else {
        // Interactive REPL mode: read SQL from stdin until EOF or quit command.
        run_repl(&pool, mode, msg, cli.limit, cli.max_col_width).await?;
    }

    Ok(())
}

/// Core program logic, separated from main() to enable clean error handling.
async fn run(msg: &Messages) -> anyhow::Result<()> {
    let args = normalize_args();
    let cli = Cli::parse_from(args);
    let mode = detect_output_mode(&cli);

    // ── ODBC path (must be checked before connect(), which cannot handle ODBC URLs) ──
    #[cfg(feature = "odbc")]
    if let Some(odbc_conn_str) = detect_odbc_connection_string(&cli.url) {
        eprintln!("{}", msg.connecting());
        eprintln!("{}", msg.connection_successful());
        eprintln!("{}: ODBC", msg.backend_label());

        if cli.connect {
            // Test connection: attempt to create environment and open connection.
            let conn_str = odbc_conn_str.clone();
            tokio::task::spawn_blocking(move || -> anyhow::Result<()> {
                let env = odbc_api::Environment::new().map_err(|e| anyhow::anyhow!("{}", e))?;
                let _conn = env
                    .connect_with_connection_string(&conn_str, odbc_api::ConnectionOptions::default())
                    .map_err(|e| anyhow::anyhow!("{}", e))?;
                Ok(())
            })
            .await??;
            return Ok(());
        }

        if let Some(sql) = &cli.sql {
            // Single-shot mode.
            let results = dbcli::execute::odbc::execute_raw_sql(&odbc_conn_str, sql).await?;
            print_results(&results, &mode, msg, cli.limit, cli.max_col_width);
        } else {
            // Interactive REPL mode.
            run_repl_odbc(&odbc_conn_str, &mode, msg, cli.limit, cli.max_col_width).await?;
        }
        return Ok(());
    }

    // ── sqlx-based backends ──
    #[cfg(any(feature = "postgres", feature = "mysql", feature = "sqlite"))]
    {
        return run_sqlx(&cli, &mode, msg).await;
    }

    // No backend enabled at all.
    #[allow(unreachable_code)]
    {
        anyhow::bail!(
            "Unsupported or not compiled database URL: {}. \
             Enable the corresponding feature (mysql, postgres, sqlite, odbc) when building.",
            cli.url
        );
    }
}

#[tokio::main]
async fn main() {
    let msg = Messages::new();

    if let Err(e) = run(&msg).await {
        eprintln!("{}: {}", msg.error_prefix(), e);
        std::process::exit(1);
    }
}