edm_orm/model/
context.rs

1use edm_core::Uuid;
2use std::time::Instant;
3
4/// 与查询上下文相关的结构体
5#[derive(Debug, Clone)]
6pub struct QueryContext {
7    /// 开始时间
8    start_time: Instant,
9    /// 查询唯一标识 Uuid
10    query_id: Uuid,
11    /// 查询
12    query: String,
13    /// 参数
14    arguments: Vec<String>,
15    /// 最后插入的ID
16    last_insert_id: Option<i64>,
17    /// 受影响的行数
18    rows_affected: Option<u64>,
19    /// 查询是否成功
20    success: bool,
21}
22
23impl QueryContext {
24    /// 创建一个实例
25    #[inline]
26    pub fn new() -> Self {
27        Self {
28            start_time: Instant::now(),
29            query_id: Uuid::new_v4(),
30            query: String::new(),
31            arguments: Vec::new(),
32            last_insert_id: None,
33            rows_affected: None,
34            success: false,
35        }
36    }
37
38    /// 设置 `query`参数
39    #[inline]
40    pub fn set_query(&mut self, query: impl ToString) {
41        self.query = query.to_string();
42    }
43
44    /// 添加参数到 arguments`Vec<String>`
45    #[inline]
46    pub fn add_argument(&mut self, arg: impl ToString) {
47        self.arguments.push(arg.to_string());
48    }
49    /// 追加查询参数
50    #[inline]
51    pub fn append_arguments(&mut self, arguments: &mut Vec<String>) {
52        self.arguments.append(arguments);
53    }
54
55    /// 设置最后的插入ID
56    #[inline]
57    pub fn set_last_insert_id(&mut self, id: i64) {
58        self.last_insert_id = Some(id);
59    }
60
61    /// 设置查询结果
62    #[inline]
63    pub fn set_query_result(&mut self, rows_affected: Option<u64>, success: bool) {
64        self.rows_affected = rows_affected;
65        self.success = success;
66    }
67
68    /// 返回开始时间
69    #[inline]
70    pub fn get_start_time(&self) -> Instant {
71        self.start_time
72    }
73
74    /// 返回查询ID
75    #[inline]
76    pub fn get_query_id(&self) -> Uuid {
77        self.query_id
78    }
79
80    pub fn get_query(&self) -> &str {
81        &self.query
82    }
83
84    pub fn get_arguments(&self) -> &[String] {
85        &self.arguments
86    }
87
88    pub fn get_last_insert_id(&self) -> Option<i64> {
89        self.last_insert_id
90    }
91
92    pub fn get_rows_affected(&self) -> Option<u64> {
93        self.rows_affected
94    }
95
96    pub fn is_success(&self) -> bool {
97        self.success
98    }
99
100    /// 格式化参数. 将所有的参数通过 `, ` 组合成字符串
101    #[inline]
102    pub fn format_arguments(&self) -> String {
103        self.arguments.join(", ")
104    }
105}
106
107impl Default for QueryContext {
108    #[inline]
109    fn default() -> Self {
110        Self::new()
111    }
112}