dm_database_parser_sqllog/parser/
record.rs

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