rat_quickdb/cache/
key_generator.rs

1
2//! 缓存键生成模块
3//!
4//! 提供各种缓存键的生成策略和实现
5
6use crate::types::{
7    CacheConfig, DataValue, IdType, QueryCondition, QueryConditionGroup, QueryOptions,
8    SortDirection,
9};
10use rat_logger::debug;
11use std::vec::Vec;
12
13// 从 cache_manager.rs 中引入 CACHE_KEY_PREFIX 和 CacheManager
14use super::cache_manager::{CACHE_KEY_PREFIX, CacheManager};
15
16impl CacheManager {
17    /// 生成缓存键
18    pub(crate) fn generate_cache_key(&self, table: &str, id: &IdType, operation: &str) -> String {
19        let id_str = match id {
20            IdType::Number(n) => n.to_string(),
21            IdType::String(s) => s.clone(),
22        };
23        format!("{}:{}:{}:{}", CACHE_KEY_PREFIX, table, operation, id_str)
24    }
25
26    /// 生成查询缓存键 - 优化版本,避免复杂序列化
27    pub fn generate_query_cache_key(
28        &self,
29        table: &str,
30        conditions: &[QueryCondition],
31        options: &QueryOptions,
32    ) -> String {
33        let query_signature = self.build_query_signature(options);
34        let conditions_signature = self.build_conditions_signature(conditions);
35        // 添加版本标识避免脏数据问题
36        let key = format!(
37            "{}:{}:query:{}:{}:{}",
38            CACHE_KEY_PREFIX, table, conditions_signature, query_signature, self.config.version
39        );
40        debug!("生成查询缓存键: table={}, key={}", table, key);
41        key
42    }
43
44    /// 生成条件组合查询缓存键
45    pub fn generate_condition_groups_cache_key(
46        &self,
47        table: &str,
48        condition_groups: &[QueryConditionGroup],
49        options: &QueryOptions,
50    ) -> String {
51        let query_signature = self.build_query_signature(options);
52        let groups_signature = self.build_condition_groups_signature(condition_groups);
53        let key = format!(
54            "{}:{}:groups:{}:{}",
55            CACHE_KEY_PREFIX, table, groups_signature, query_signature
56        );
57        debug!("生成条件组合查询缓存键: table={}, key={}", table, key);
58        key
59    }
60
61    /// 构建查询签名 - 高效版本,避免JSON序列化
62    fn build_query_signature(&self, options: &QueryOptions) -> String {
63        let mut parts = Vec::new();
64
65        // 分页信息
66        if let Some(pagination) = &options.pagination {
67            parts.push(format!("p{}_{}", pagination.skip, pagination.limit));
68        }
69
70        // 排序信息
71        if !options.sort.is_empty() {
72            let sort_str = options
73                .sort
74                .iter()
75                .map(|s| {
76                    format!(
77                        "{}{}",
78                        s.field,
79                        match s.direction {
80                            SortDirection::Asc => "a",
81                            SortDirection::Desc => "d",
82                        }
83                    )
84                })
85                .collect::<Vec<_>>()
86                .join(",");
87            parts.push(format!("s{}", sort_str));
88        }
89
90        // 投影信息
91        if !options.fields.is_empty() {
92            let proj_str = options.fields.join(",");
93            parts.push(format!("f{}", proj_str));
94        }
95
96        // 连接部分生成最终签名
97        if parts.is_empty() {
98            "default".to_string()
99        } else {
100            parts.join("_")
101        }
102    }
103
104    /// 构建条件签名
105    fn build_conditions_signature(&self, conditions: &[QueryCondition]) -> String {
106        if conditions.is_empty() {
107            return "no_cond".to_string();
108        }
109
110        let mut signature = String::new();
111        for (i, condition) in conditions.iter().enumerate() {
112            if i > 0 {
113                signature.push('_');
114            }
115            signature.push_str(&format!(
116                "{}{:?}{}",
117                condition.field,
118                condition.operator,
119                match &condition.value {
120                    DataValue::String(s) => s.clone(), // 修复:不截断字符串,使用完整值
121                    DataValue::Int(n) => n.to_string(),
122                    DataValue::Float(f) => f.to_string(),
123                    DataValue::Bool(b) => b.to_string(),
124                    _ => "val".to_string(),
125                }
126            ));
127        }
128        signature
129    }
130
131    /// 构建条件组合签名
132    fn build_condition_groups_signature(&self, condition_groups: &[QueryConditionGroup]) -> String {
133        if condition_groups.is_empty() {
134            return "no_groups".to_string();
135        }
136
137        let mut signature = String::new();
138        for (i, group) in condition_groups.iter().enumerate() {
139            if i > 0 {
140                signature.push('_');
141            }
142            match group {
143                QueryConditionGroup::Single(condition) => {
144                    signature.push_str(&format!(
145                        "s{}{:?}{}",
146                        condition.field,
147                        condition.operator,
148                        match &condition.value {
149                            DataValue::String(s) => s.clone(), // 修复:不截断字符串,使用完整值
150                            DataValue::Int(n) => n.to_string(),
151                            DataValue::Float(f) => f.to_string(),
152                            DataValue::Bool(b) => b.to_string(),
153                            _ => "val".to_string(),
154                        }
155                    ));
156                }
157                QueryConditionGroup::Group {
158                    conditions,
159                    operator,
160                } => {
161                    signature.push_str(&format!("g{:?}_", operator));
162                    for (j, condition) in conditions.iter().enumerate() {
163                        if j > 0 {
164                            signature.push('|');
165                        }
166                        match condition {
167                            QueryConditionGroup::Single(cond) => {
168                                signature.push_str(&format!(
169                                    "{}{:?}{}",
170                                    cond.field,
171                                    cond.operator,
172                                    match &cond.value {
173                                        DataValue::String(s) => s.clone(),
174                                        DataValue::Int(n) => n.to_string(),
175                                        DataValue::Float(f) => f.to_string(),
176                                        DataValue::Bool(b) => b.to_string(),
177                                        _ => "val".to_string(),
178                                    }
179                                ));
180                            }
181                            QueryConditionGroup::Group { .. } => {
182                                // 递归处理嵌套组合(简化处理)
183                                signature.push_str("nested");
184                            }
185                        }
186                    }
187                }
188            }
189        }
190        signature
191    }
192}