dm_database_parser_sqllog/parser/
record.rs

1//! Record 结构定义和相关方法
2//!
3//! Record 表示一条原始的日志记录,可能包含多行(起始行 + 继续行)。
4//!
5//! # 用法说明
6//!
7//! Record 仅作为库内部结构,普通用户无需直接使用。
8//!
9
10use crate::error::ParseError;
11use crate::parser::parse_functions;
12use crate::sqllog::Sqllog;
13
14/// 表示一条完整的日志记录(可能包含多行)
15///
16/// 日志记录由一个起始行和零个或多个继续行组成。起始行包含时间戳和元数据,
17/// 继续行包含多行 SQL 语句的后续部分。
18///
19
20#[derive(Debug, Clone, PartialEq)]
21pub struct Record {
22    /// 记录的所有行(第一行是起始行,后续行是继续行)
23    pub lines: Vec<String>,
24}
25
26impl Record {
27    /// 创建新的记录
28    ///
29    /// # 参数
30    ///
31    /// * `start_line` - 记录的起始行
32    pub fn new(start_line: String) -> Self {
33        Self {
34            lines: vec![start_line],
35        }
36    }
37
38    /// 添加继续行
39    ///
40    /// # 参数
41    ///
42    /// * `line` - 要添加的继续行
43    pub fn add_line(&mut self, line: String) {
44        self.lines.push(line);
45    }
46
47    /// 获取起始行
48    ///
49    /// # 返回
50    ///
51    /// 返回记录的第一行(起始行)
52    pub fn start_line(&self) -> &str {
53        &self.lines[0]
54    }
55
56    /// 获取所有行
57    ///
58    /// # 返回
59    ///
60    /// 返回包含所有行的切片
61    pub fn all_lines(&self) -> &[String] {
62        &self.lines
63    }
64
65    /// 获取完整的记录内容(所有行拼接)
66    ///
67    /// # 返回
68    ///
69    /// 返回所有行用换行符拼接后的字符串
70    pub fn full_content(&self) -> String {
71        self.lines.join("\n")
72    }
73
74    /// 判断是否有继续行
75    ///
76    /// # 返回
77    ///
78    /// 如果记录包含多行(有继续行)返回 `true`,否则返回 `false`
79    pub fn has_continuation_lines(&self) -> bool {
80        self.lines.len() > 1
81    }
82
83    /// 将 Record 解析为 Sqllog
84    ///
85    /// # 返回
86    ///
87    /// * `Ok(Sqllog)` - 解析成功
88    /// * `Err(ParseError)` - 解析失败
89    pub fn parse_to_sqllog(&self) -> Result<Sqllog, ParseError> {
90        let lines: Vec<&str> = self.lines.iter().map(|s| s.as_str()).collect();
91        parse_functions::parse_record(&lines)
92    }
93}