dm_database_parser_sqllog/parser/
api.rs

1//! 便捷 API 函数
2//!
3//! 提供了一组方便使用的高层 API,用于快速解析 SQL 日志。
4
5use crate::error::ParseError;
6use crate::parser::record_parser::RecordParser;
7use crate::sqllog::Sqllog;
8use std::fs::File;
9use std::io::BufReader;
10use std::path::Path;
11
12// SqllogIterator 已移入 record_parser.rs 并非公共导出
13
14/// 从文件读取并返回 Sqllog 迭代器(流式处理)
15///
16/// 这是一个便捷函数,从文件读取日志并返回 `SqllogIterator` 迭代器。
17/// 使用迭代器可以避免一次性加载所有数据到内存,适合处理大文件。
18///
19/// # 参数
20///
21/// * `path` - 日志文件路径
22///
23/// # 返回
24///
25/// * `Iterator<Item = Result<Sqllog, ParseError>>` - 返回一个用于流式解析的迭代器,迭代项可能包含 `ParseError`,例如文件打开失败或解析错误
26///
27/// # 示例
28///
29/// ```no_run
30/// use dm_database_parser_sqllog::iter_records_from_file;
31///
32/// let parser = iter_records_from_file("sqllog.txt");
33///
34/// let mut sqllog_count = 0;
35/// let mut error_count = 0;
36///
37/// for result in parser {
38///     match result {
39///         Ok(sqllog) => {
40///             sqllog_count += 1;
41///             println!("Sqllog {}: 用户={}, SQL={}",
42///                 sqllog_count, sqllog.meta.username, sqllog.body);
43///         }
44///         Err(err) => {
45///             error_count += 1;
46///             eprintln!("错误 {}: {}", error_count, err);
47///         }
48///     }
49/// }
50///
51/// println!("成功: {} 条, 错误: {} 个", sqllog_count, error_count);
52/// # Ok::<(), Box<dyn std::error::Error>>(())
53/// ```
54pub fn iter_records_from_file<P>(path: P) -> Box<dyn Iterator<Item = Result<Sqllog, ParseError>>>
55where
56    P: AsRef<Path>,
57{
58    let path_ref = path.as_ref();
59    match File::open(path_ref) {
60        Ok(file) => {
61            let reader = BufReader::new(file);
62            let record_parser = RecordParser::new(reader);
63            // 返回一个隐藏的具体迭代器实现(crate 内部定义)
64            Box::new(crate::parser::record_parser::SqllogIterator::new(
65                record_parser,
66            ))
67        }
68        Err(e) => Box::new(std::iter::once(Err(ParseError::FileNotFound {
69            path: format!("{}: {}", path_ref.display(), e),
70        }))),
71    }
72}