dm-database-sqllog2db 1.16.0

高性能 CLI 工具:流式解析达梦数据库 SQL 日志并导出到 CSV 或 SQLite
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
mod cli;
mod config;
mod error;
mod exporter;
mod logging;
mod parser;
mod pipeline;
mod preflight;
mod scanner;
mod stats;

use config::Config;
use error::{Error, ErrorStats, Result};
use log::{info, warn};
use std::path::Path;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};

// 退出码约定:
// 0 = 全部成功,零错误
// 1 = 处理完成但有非致命错误(部分成功)
// 2 = 致命错误,无法完成处理
// 130 = 被用户中断(Ctrl+C),遵循 Unix 128+SIGINT(2) 惯例
const EXIT_PARTIAL: i32 = 1;
const EXIT_FATAL: i32 = 2;
const EXIT_INTERRUPTED: i32 = 130;

/// Initialize simple console logging for non-run commands.
/// verbose flag is intentionally ignored: non-Run commands (init/validate)
/// only support quiet suppression; debug verbosity requires the full logging
/// stack initialized in the Run path.
fn init_simple_logging(quiet: bool) {
    let filter = if quiet {
        log::LevelFilter::Error
    } else {
        log::LevelFilter::Info
    };
    let _ = env_logger::Builder::from_default_env()
        .filter_level(filter)
        .try_init();
}

/// Apply CLI verbosity flags to configuration.
/// Sets the file logging level to match the CLI verbosity:
/// - verbose=true → "debug" (more detail in log file)
/// - quiet=true   → "error" (suppress most log output)
/// - neither      → leave the config value unchanged
fn apply_verbosity_to_config(cfg: &mut Config, verbose: bool, quiet: bool) {
    if verbose {
        cfg.logging.level = "debug".to_string();
    } else if quiet {
        cfg.logging.level = "error".to_string();
    }
}

/// Apply CLI --input overrides to configuration.
/// Per D-05: CLI inputs completely replace config inputs when Some and non-empty.
/// Some(empty vec) keeps the config value and emits a warning.
fn apply_cli_inputs_to_config(cfg: &mut Config, cli_inputs: Option<Vec<String>>) {
    if let Some(inputs) = cli_inputs {
        if inputs.is_empty() {
            log::warn!("--input provided but empty; using config inputs");
            return;
        }
        cfg.sqllog.inputs = inputs;
    }
}

/// Format a fatal error into a multi-line string for stderr output.
/// First line: `[SEVERITY] display_text`
/// Second line (if hint non-empty): `  hint: suggestion_text`
fn format_error_output(error: &Error) -> String {
    let severity = error.severity();
    let hint = error.suggestion();
    if hint.is_empty() {
        format!("[{severity}] {error}")
    } else {
        format!("[{severity}] {error}\n  hint: {hint}")
    }
}

/// Format a validation error into a multi-line string for stderr output.
/// Uses `[FAIL]` label (distinct from severity-based labels) to signal
/// config validation failure rather than a fatal runtime error.
/// Second line (if hint non-empty): `  hint: suggestion_text`
fn format_validate_error(error: &Error) -> String {
    let hint = error.suggestion();
    if hint.is_empty() {
        format!("[FAIL] {error}")
    } else {
        format!("[FAIL] {error}\n  hint: {hint}")
    }
}

fn main() {
    match run() {
        Ok(Some((stats, quiet))) => {
            if stats.has_fatal() {
                std::process::exit(EXIT_FATAL);
            }
            if stats.has_errors() {
                if !quiet {
                    eprintln!(
                        "Completed with {} error(s) ({} parse, {} export).",
                        stats.total_errors, stats.parse_errors, stats.export_errors
                    );
                }
                std::process::exit(EXIT_PARTIAL);
            }
            // EXIT_CLEAN (0) is default
        }
        Ok(None) => {} // non-Run commands: normal exit
        Err(e) => {
            if matches!(e, Error::Interrupted) {
                std::process::exit(EXIT_INTERRUPTED);
            }
            eprintln!("{}", format_error_output(&e));
            std::process::exit(EXIT_FATAL);
        }
    }
}

fn run() -> Result<Option<(ErrorStats, bool)>> {
    use clap::{CommandFactory, FromArgMatches};

    let cmd = cli::opts::Cli::command();
    let matches = cmd.get_matches();
    let cli = cli::opts::Cli::from_arg_matches(&matches).unwrap_or_else(|e| e.exit());

    let needs_simple_logging = !matches!(
        &cli.command,
        Some(
            cli::opts::Commands::Run { .. }
                | cli::opts::Commands::Stats { .. }
                | cli::opts::Commands::Watch { .. }
        )
    );
    if needs_simple_logging {
        init_simple_logging(cli.quiet);
    }

    match &cli.command {
        Some(cli::opts::Commands::Init {
            output,
            force,
            interactive,
        }) => {
            if *interactive {
                cli::init::handle_init_interactive(output, *force)?;
            } else {
                cli::init::handle_init(output, *force)?;
            }
            Ok(None)
        }
        Some(cli::opts::Commands::Run { config, input }) => {
            let mut cfg = load_config(config)?;
            apply_cli_inputs_to_config(&mut cfg, input.clone());
            cfg.validate()?;

            apply_verbosity_to_config(&mut cfg, cli.verbose, cli.quiet);
            logging::init_logging(&cfg.logging, false)?;
            info!("Application started");
            info!("Configuration validation passed");

            let pf = preflight::check(&cfg);
            if pf.print_and_check() {
                std::process::exit(EXIT_FATAL);
            }

            let interrupted = Arc::new(AtomicBool::new(false));
            let interrupted_flag = Arc::clone(&interrupted);
            ctrlc::set_handler(move || {
                interrupted_flag.store(true, Ordering::Release);
            })
            .ok();

            let stats = cli::run::handle_run(&cfg, cli.quiet, cli.verbose, &interrupted, None)?;
            Ok(Some((stats, cli.quiet)))
        }
        Some(cli::opts::Commands::Validate { config }) => {
            let cfg = Config::from_file(Path::new(config))?;
            if let Err(e) = cfg.validate() {
                eprintln!("{}", format_validate_error(&e));
                std::process::exit(EXIT_FATAL);
            }
            cli::validate::handle_validate(&cfg);
            Ok(None)
        }
        Some(cli::opts::Commands::Stats {
            config,
            top,
            from,
            to,
        }) => {
            let mut cfg = Config::from_file(Path::new(config))?;
            cfg.validate()?;
            apply_verbosity_to_config(&mut cfg, cli.verbose, cli.quiet);
            logging::init_logging(&cfg.logging, false)?;
            cli::stats::handle_stats(&cfg, *top, from.clone(), to.clone())?;
            Ok(None)
        }
        Some(cli::opts::Commands::Watch { config }) => {
            let mut cfg = load_config(config)?;
            cfg.validate()?;
            apply_verbosity_to_config(&mut cfg, cli.verbose, cli.quiet);
            logging::init_logging(&cfg.logging, false)?;
            info!("Application started (watch mode)");
            info!("Configuration validation passed");

            let pf = preflight::check(&cfg);
            if pf.print_and_check() {
                std::process::exit(EXIT_FATAL);
            }

            let interrupted = Arc::new(AtomicBool::new(false));
            let interrupted_flag = Arc::clone(&interrupted);
            ctrlc::set_handler(move || {
                interrupted_flag.store(true, Ordering::Release);
            })
            .ok();

            cli::watch::handle_watch(&cfg, cli.quiet, cli.verbose, &interrupted)?;
            Ok(None)
        }
        None => {
            cli::opts::Cli::command().print_help().ok();
            std::process::exit(0);
        }
    }
}

fn load_config(config_path: &str) -> Result<Config> {
    let path = Path::new(config_path);
    match Config::from_file(path) {
        Ok(c) => {
            info!("Loaded configuration file: {config_path}");
            Ok(c)
        }
        Err(e) => {
            if let Error::Config(crate::error::ConfigError::NotFound(_)) = &e {
                warn!("Configuration file not found: {config_path}, using default configuration");
                info!("Tip: run 'sqllog2db init' to generate a configuration file");
                Ok(Config::default())
            } else {
                Err(e)
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::{ConfigError, ExportError, ParserError};

    #[test]
    fn test_exit_code_clean() {
        let stats = ErrorStats::default();
        assert!(!stats.has_errors());
        assert!(!stats.has_fatal());
    }

    #[test]
    fn test_exit_code_partial_errors() {
        let mut stats = ErrorStats::default();
        stats.add_parse_error();
        assert!(stats.has_errors());
        assert!(!stats.has_fatal());
    }

    #[test]
    fn test_exit_code_fatal_error() {
        let mut stats = ErrorStats::default();
        stats.set_fatal("test fatal".into());
        assert!(stats.has_fatal());
    }

    #[test]
    fn test_error_is_fatal_for_config() {
        let e = Error::Config(ConfigError::NoExporters);
        assert!(e.is_fatal());
        assert_eq!(e.severity(), crate::error::ErrorSeverity::Critical);
    }

    #[test]
    fn test_error_is_fatal_for_parse_error() {
        let e = Error::Parser(ParserError::PathNotFound {
            path: "/tmp".into(),
        });
        assert!(!e.is_fatal());
        assert_eq!(e.severity(), crate::error::ErrorSeverity::Warning);
    }

    #[test]
    fn test_error_suggestion_for_config_not_found() {
        let e = Error::Config(ConfigError::NotFound("/tmp/config.toml".into()));
        assert!(e.suggestion().contains("sqllog2db init"));
    }

    #[test]
    fn test_error_suggestion_for_config_parse_failed() {
        let e = Error::Config(ConfigError::ParseFailed {
            path: "/tmp/bad.toml".into(),
            reason: "unexpected EOF".into(),
        });
        let s = e.suggestion();
        assert!(
            !s.is_empty(),
            "ParseFailed should have a non-empty suggestion, got empty"
        );
        assert!(
            s.contains("TOML") || s.contains("syntax"),
            "ParseFailed suggestion should mention TOML syntax; got: {s}"
        );
    }

    #[test]
    fn test_error_suggestion_for_export_write_failed() {
        let e = Error::Export(ExportError::WriteFailed {
            path: "/tmp/out.csv".into(),
            reason: "disk full".into(),
        });
        assert!(!e.is_fatal());
        assert!(!e.suggestion().is_empty());
    }

    #[test]
    fn test_apply_verbosity_quiet() {
        let mut cfg = Config::default();
        apply_verbosity_to_config(&mut cfg, false, true);
        assert_eq!(cfg.logging.level, "error");
    }

    #[test]
    fn test_apply_verbosity_not_quiet() {
        let mut cfg = Config::default();
        let original = cfg.logging.level.clone();
        apply_verbosity_to_config(&mut cfg, false, false);
        assert_eq!(cfg.logging.level, original);
    }

    #[test]
    fn test_apply_verbosity_verbose_sets_debug() {
        let mut cfg = Config::default();
        apply_verbosity_to_config(&mut cfg, true, false);
        assert_eq!(cfg.logging.level, "debug");
    }

    #[test]
    fn test_load_config_not_found_returns_default() {
        let result = load_config("/nonexistent/path/config.toml");
        assert!(result.is_ok());
    }

    #[test]
    fn test_load_config_invalid_toml_returns_error() {
        let dir = tempfile::TempDir::new().unwrap();
        let path = dir.path().join("bad.toml");
        std::fs::write(&path, "not valid toml ][[[").unwrap();
        let result = load_config(path.to_str().unwrap());
        assert!(result.is_err());
    }

    #[test]
    fn test_apply_cli_inputs_none_keeps_config() {
        let mut cfg = Config::default();
        // Default inputs = ["sqllogs"]
        assert_eq!(cfg.sqllog.inputs, vec!["sqllogs".to_string()]);
        apply_cli_inputs_to_config(&mut cfg, None);
        assert_eq!(
            cfg.sqllog.inputs,
            vec!["sqllogs".to_string()],
            "None should not change config inputs"
        );
    }

    #[test]
    fn test_apply_cli_inputs_some_replaces() {
        let mut cfg = Config::default();
        cfg.sqllog.inputs = vec!["a".to_string()];
        apply_cli_inputs_to_config(&mut cfg, Some(vec!["b".to_string(), "c".to_string()]));
        assert_eq!(
            cfg.sqllog.inputs,
            vec!["b".to_string(), "c".to_string()],
            "Some(non-empty) should completely replace config inputs"
        );
    }

    #[test]
    fn test_apply_cli_inputs_empty_vec_keeps_config() {
        let mut cfg = Config::default();
        cfg.sqllog.inputs = vec!["x".to_string()];
        apply_cli_inputs_to_config(&mut cfg, Some(vec![]));
        assert_eq!(
            cfg.sqllog.inputs,
            vec!["x".to_string()],
            "Some(empty vec) should not change config inputs"
        );
    }

    #[test]
    fn test_error_io_suggestion_non_empty() {
        let e = Error::Io(std::io::Error::other("disk full"));
        let suggestion = e.suggestion();
        assert!(!suggestion.is_empty(), "Io suggestion should not be empty");
        assert!(
            suggestion.contains("filesystem"),
            "Io suggestion should mention filesystem, got: {suggestion}"
        );
    }

    #[test]
    fn test_error_print_format_uses_hint_prefix() {
        let e = Error::Export(ExportError::WriteFailed {
            path: "/tmp/out.csv".into(),
            reason: "disk full".into(),
        });
        let formatted = format_error_output(&e);
        assert!(
            formatted.contains("\n  hint: "),
            "formatted output should contain hint prefix, got: {formatted}"
        );
        assert!(
            !formatted.contains("Suggestion:"),
            "formatted output should not contain old Suggestion: prefix, got: {formatted}"
        );
        assert!(
            formatted.starts_with("[ERROR]"),
            "first line should start with [ERROR], got: {formatted}"
        );
    }

    // IN-02: Interrupted is excluded from format_error_output by a matches! guard in main().
    // This test documents that the guard fires (i.e. the condition is true for Interrupted)
    // and that if format_error_output were called it would emit a [CRITICAL] hint line —
    // confirming that the guard is necessary to suppress it.
    #[test]
    fn test_interrupted_matches_guard_is_true() {
        let e = Error::Interrupted;
        assert!(
            matches!(e, Error::Interrupted),
            "Interrupted variant must match the guard used in main()"
        );
        // If the guard were bypassed, format_error_output would produce a hint:
        let formatted = format_error_output(&e);
        assert!(
            formatted.starts_with("[CRITICAL]"),
            "format_error_output for Interrupted would produce [CRITICAL], got: {formatted}"
        );
        assert!(
            formatted.contains("\n  hint: "),
            "format_error_output for Interrupted would include hint line, got: {formatted}"
        );
    }

    #[test]
    fn test_format_error_output_config_parse_failed_is_critical() {
        let e = Error::Config(ConfigError::ParseFailed {
            path: "/tmp/bad.toml".into(),
            reason: "unexpected EOF".into(),
        });
        let formatted = format_error_output(&e);
        assert!(
            formatted.starts_with("[CRITICAL]"),
            "ParseFailed should produce [CRITICAL] prefix, got: {formatted}"
        );
        assert!(
            formatted.contains("\n  hint: "),
            "ParseFailed should include hint line, got: {formatted}"
        );
        assert!(
            !formatted.contains("Suggestion:"),
            "should not use old Suggestion: prefix, got: {formatted}"
        );
    }
}