rat_quickdb 0.5.2

强大的跨数据库ODM库,支持自动索引创建、统一接口和现代异步架构
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635

//! 查询结果缓存模块
//!
//! 提供查询结果和条件组合查询结果的缓存功能

use crate::types::{DataValue, QueryCondition, QueryConditionGroup, QueryConditionGroupWithConfig, QueryOptions};
use anyhow::{Result, anyhow};
use bytes::Bytes;
use rat_logger::{debug, warn};
use rat_memcache::{CacheOptions, RatMemCache};
use serde_json;
use std::sync::atomic::Ordering;
use std::time::Instant;

// 从 cache_manager.rs 中引入 CacheManager
use super::cache_manager::CacheManager;

impl CacheManager {
    pub async fn cache_query_result(
        &self,
        table: &str,
        options: &QueryOptions,
        results: &[DataValue],
    ) -> Result<()> {
        if !self.config.enabled {
            return Ok(());
        }

        let start_time = Instant::now();
        let key = self.generate_query_cache_key(table, &options.conditions, options);

        debug!(
            "尝试缓存查询结果: table={}, key={}, options={:?}, 结果数量={}",
            table,
            key,
            options,
            results.len()
        );

        // 修复:允许缓存空结果,使用特殊标记区分"无缓存"和"空结果"
        // 空结果也需要缓存,避免TTL过期后的死循环问题

        // 限制缓存结果大小,避免内存浪费
        if results.len() > 1000 {
            debug!(
                "跳过缓存过大查询结果: table={}, count={}",
                table,
                results.len()
            );
            return Ok(());
        }

        // 修复:正确序列化所有类型的DataValue
        let json_results: Vec<serde_json::Value> = results
            .iter()
            .map(|dv| {
                match dv {
                    DataValue::Json(json_val) => json_val.clone(),
                    DataValue::String(s) => serde_json::Value::String(s.clone()),
                    DataValue::Int(i) => serde_json::Value::Number(serde_json::Number::from(*i)),
                    DataValue::UInt(u) => serde_json::Value::Number(serde_json::Number::from(*u)),
                    DataValue::Float(f) => serde_json::Value::Number(serde_json::Number::from_f64(*f).unwrap_or(serde_json::Number::from(0))),
                    DataValue::Bool(b) => serde_json::Value::Bool(*b),
                    DataValue::DateTime(dt) => serde_json::Value::String(dt.to_rfc3339()),
                    DataValue::DateTimeUTC(dt) => serde_json::Value::String(dt.to_rfc3339()),
                    DataValue::Null => serde_json::Value::Null,
                    DataValue::Bytes(bytes) => serde_json::Value::String(base64::encode(bytes)),
                    DataValue::Uuid(uuid) => serde_json::Value::String(uuid.to_string()),
                    DataValue::Array(arr) => {
                        let json_array: Vec<serde_json::Value> = arr.iter().map(|item| {
                            // 递归处理数组元素
                            match item {
                                DataValue::Json(json_val) => json_val.clone(),
                                DataValue::String(s) => serde_json::Value::String(s.clone()),
                                DataValue::Int(i) => serde_json::Value::Number(serde_json::Number::from(*i)),
                                DataValue::UInt(u) => serde_json::Value::Number(serde_json::Number::from(*u)),
                                DataValue::Float(f) => serde_json::Value::Number(serde_json::Number::from_f64(*f).unwrap_or(serde_json::Number::from(0))),
                                DataValue::Bool(b) => serde_json::Value::Bool(*b),
                                DataValue::DateTime(dt) => serde_json::Value::String(dt.to_rfc3339()),
                                DataValue::DateTimeUTC(dt) => serde_json::Value::String(dt.to_rfc3339()),
                                DataValue::Null => serde_json::Value::Null,
                                DataValue::Bytes(bytes) => serde_json::Value::String(base64::encode(bytes)),
                                DataValue::Uuid(uuid) => serde_json::Value::String(uuid.to_string()),
                                _ => serde_json::Value::String(format!("{:?}", item)), // 其他复杂类型转为字符串
                            }
                        }).collect();
                        serde_json::Value::Array(json_array)
                    }
                    DataValue::Object(obj) => {
                        let mut json_obj = serde_json::Map::new();
                        for (key, value) in obj {
                            let json_value = match value {
                                DataValue::Json(json_val) => json_val.clone(),
                                DataValue::String(s) => serde_json::Value::String(s.clone()),
                              DataValue::Int(i) => serde_json::Value::Number(serde_json::Number::from(*i)),
                                DataValue::UInt(u) => serde_json::Value::Number(serde_json::Number::from(*u)),
                                DataValue::Float(f) => serde_json::Value::Number(serde_json::Number::from_f64(*f).unwrap_or(serde_json::Number::from(0))),
                                DataValue::Bool(b) => serde_json::Value::Bool(*b),
                                DataValue::DateTime(dt) => {
                                    serde_json::Value::String(dt.to_rfc3339())
                                }
                                DataValue::DateTimeUTC(dt) => {
                                    serde_json::Value::String(dt.to_rfc3339())
                                }
                                DataValue::Null => serde_json::Value::Null,
                                DataValue::Bytes(bytes) => {
                                    serde_json::Value::String(base64::encode(bytes))
                                }
                                DataValue::Uuid(uuid) => {
                                    serde_json::Value::String(uuid.to_string())
                                }
                                _ => serde_json::Value::String(format!("{:?}", value)), // 其他复杂类型转为字符串
                            };
                            json_obj.insert(key.clone(), json_value);
                        }
                        serde_json::Value::Object(json_obj)
                    }
                }
            })
            .collect();

        let serialized = serde_json::to_vec(&json_results)
            .map_err(|e| anyhow!("Failed to serialize query results: {}", e))?;

        let cache_options = CacheOptions {
            ttl_seconds: Some(self.config.ttl_config.default_ttl_secs),
            ..Default::default()
        };

        self.cache
            .set_with_options(key.clone(), Bytes::from(serialized), &cache_options)
            .await
            .map_err(|e| anyhow!("Failed to cache query results: {}", e))?;

        // 记录缓存键
        self.track_cache_key(table, key.clone()).await;

        // 更新统计信息
        let elapsed = start_time.elapsed();
        self.writes_counter.fetch_add(1, Ordering::Relaxed);
        {
            let mut stats = self.stats.write().await;
            stats.writes += 1;
            stats.write_count += 1;
            stats.total_write_latency_ns += elapsed.as_nanos() as u64;
        }

        debug!(
            "已缓存查询结果: table={}, key={}, count={}",
            table,
            key,
            results.len()
        );
        Ok(())
    }

    /// 缓存条件组合查询结果
    pub async fn cache_condition_groups_result(
        &self,
        table: &str,
        condition_groups: &[QueryConditionGroup],
        options: &QueryOptions,
        results: &[DataValue],
    ) -> Result<()> {
        if !self.config.enabled {
            return Ok(());
        }

        let start_time = Instant::now();
        let key = self.generate_condition_groups_cache_key(table, condition_groups, options);

        debug!(
            "开始缓存条件组合查询结果: table={}, key={}, count={}",
            table,
            key,
            results.len()
        );

        // 检查结果大小限制,避免缓存过大结果
        if results.len() > 1000 {
            debug!("跳过缓存:结果集过大 ({} > 1000)", results.len());
            return Ok(());
        }

        // 将所有DataValue转换为JSON值进行序列化
        let json_results: Vec<serde_json::Value> = results
            .iter()
            .map(|dv| {
                match dv {
                    DataValue::Json(json_val) => json_val.clone(),
                    DataValue::String(s) => serde_json::Value::String(s.clone()),
                    DataValue::Int(i) => serde_json::Value::Number(serde_json::Number::from(*i)),
                    DataValue::UInt(u) => serde_json::Value::Number(serde_json::Number::from(*u)),
                    DataValue::Float(f) => serde_json::Value::Number(serde_json::Number::from_f64(*f).unwrap_or(serde_json::Number::from(0))),
                    DataValue::Bool(b) => serde_json::Value::Bool(*b),
                    DataValue::DateTime(dt) => serde_json::Value::String(dt.to_rfc3339()),
                    DataValue::DateTimeUTC(dt) => serde_json::Value::String(dt.to_rfc3339()),
                    DataValue::Null => serde_json::Value::Null,
                    DataValue::Bytes(bytes) => serde_json::Value::String(base64::encode(bytes)),
                    DataValue::Uuid(uuid) => serde_json::Value::String(uuid.to_string()),
                    DataValue::Array(arr) => {
                        let json_array: Vec<serde_json::Value> = arr.iter().map(|item| {
                            match item {
                                DataValue::Json(json_val) => json_val.clone(),
                                DataValue::String(s) => serde_json::Value::String(s.clone()),
                                DataValue::Int(i) => serde_json::Value::Number(serde_json::Number::from(*i)),
                                DataValue::UInt(u) => serde_json::Value::Number(serde_json::Number::from(*u)),
                                DataValue::Float(f) => serde_json::Value::Number(serde_json::Number::from_f64(*f).unwrap_or(serde_json::Number::from(0))),
                                DataValue::Bool(b) => serde_json::Value::Bool(*b),
                                DataValue::DateTime(dt) => serde_json::Value::String(dt.to_rfc3339()),
                                DataValue::DateTimeUTC(dt) => serde_json::Value::String(dt.to_rfc3339()),
                                DataValue::Null => serde_json::Value::Null,
                                DataValue::Bytes(bytes) => serde_json::Value::String(base64::encode(bytes)),
                                DataValue::Uuid(uuid) => serde_json::Value::String(uuid.to_string()),
                                _ => serde_json::Value::String(format!("{:?}", item)), // 其他复杂类型转为字符串
                            }
                        }).collect();
                        serde_json::Value::Array(json_array)
                    }
                    DataValue::Object(obj) => {
                        let mut json_obj = serde_json::Map::new();
                        for (key, value) in obj {
                            let json_value = match value {
                                DataValue::Json(json_val) => json_val.clone(),
                                DataValue::String(s) => serde_json::Value::String(s.clone()),
                              DataValue::Int(i) => serde_json::Value::Number(serde_json::Number::from(*i)),
                                DataValue::UInt(u) => serde_json::Value::Number(serde_json::Number::from(*u)),
                                DataValue::Float(f) => serde_json::Value::Number(serde_json::Number::from_f64(*f).unwrap_or(serde_json::Number::from(0))),
                                DataValue::Bool(b) => serde_json::Value::Bool(*b),
                                DataValue::DateTime(dt) => {
                                    serde_json::Value::String(dt.to_rfc3339())
                                }
                                DataValue::DateTimeUTC(dt) => {
                                    serde_json::Value::String(dt.to_rfc3339())
                                }
                                DataValue::Null => serde_json::Value::Null,
                                DataValue::Bytes(bytes) => {
                                    serde_json::Value::String(base64::encode(bytes))
                                }
                                DataValue::Uuid(uuid) => {
                                    serde_json::Value::String(uuid.to_string())
                                }
                                _ => serde_json::Value::String(format!("{:?}", value)), // 其他复杂类型转为字符串
                            };
                            json_obj.insert(key.clone(), json_value);
                        }
                        serde_json::Value::Object(json_obj)
                    }
                }
            })
            .collect();

        let serialized = serde_json::to_vec(&json_results)
            .map_err(|e| anyhow!("Failed to serialize condition groups query results: {}", e))?;

        let cache_options = CacheOptions {
            ttl_seconds: Some(self.config.ttl_config.default_ttl_secs),
            ..Default::default()
        };

        self.cache
            .set_with_options(key.clone(), Bytes::from(serialized), &cache_options)
            .await
            .map_err(|e| anyhow!("Failed to cache condition groups query results: {}", e))?;

        // 记录缓存键
        self.track_cache_key(table, key.clone()).await;

        // 更新统计信息
        let elapsed = start_time.elapsed();
        self.writes_counter.fetch_add(1, Ordering::Relaxed);
        {
            let mut stats = self.stats.write().await;
            stats.writes += 1;
            stats.write_count += 1;
            stats.total_write_latency_ns += elapsed.as_nanos() as u64;
        }

        debug!(
            "已缓存条件组合查询结果: table={}, key={}, count={}",
            table,
            key,
            results.len()
        );
        Ok(())
    }

    /// 获取缓存的查询结果 - 优化版本
    pub async fn get_cached_query_result(
        &self,
        table: &str,
        options: &QueryOptions,
    ) -> Result<Option<Vec<DataValue>>> {
        if !self.config.enabled {
            return Ok(None);
        }

        let start_time = Instant::now();
        let key = self.generate_query_cache_key(table, &options.conditions, options);

        debug!(
            "尝试获取查询缓存: table={}, key={}, options={:?}",
            table, key, options
        );

        self.get_cached_result_by_key(&key, table, start_time).await
    }

    /// 获取缓存的条件组合查询结果
    pub async fn get_cached_condition_groups_result(
        &self,
        table: &str,
        condition_groups: &[QueryConditionGroup],
        options: &QueryOptions,
    ) -> Result<Option<Vec<DataValue>>> {
        if !self.config.enabled {
            return Ok(None);
        }

        let start_time = Instant::now();
        let key = self.generate_condition_groups_cache_key(table, condition_groups, options);

        debug!(
            "尝试获取条件组合查询缓存: table={}, key={}, options={:?}",
            table, key, options
        );

        self.get_cached_result_by_key(&key, table, start_time).await
    }

    /// 获取缓存的条件组合查询结果(完整版)
    pub async fn get_cached_condition_groups_with_config_result(
        &self,
        table: &str,
        condition_groups: &[QueryConditionGroupWithConfig],
        options: &QueryOptions,
    ) -> Result<Option<Vec<DataValue>>> {
        if !self.config.enabled {
            return Ok(None);
        }

        let start_time = Instant::now();
        let key = self.generate_condition_groups_with_config_cache_key(table, condition_groups, options);

        debug!(
            "尝试获取条件组合查询缓存(完整版): table={}, key={}, options={:?}",
            table, key, options
        );

        self.get_cached_result_by_key(&key, table, start_time).await
    }

    /// 缓存条件组合查询结果(完整版)
    pub async fn cache_condition_groups_with_config_result(
        &self,
        table: &str,
        condition_groups: &[QueryConditionGroupWithConfig],
        options: &QueryOptions,
        results: &[DataValue],
    ) -> Result<()> {
        if !self.config.enabled {
            return Ok(());
        }

        let start_time = Instant::now();
        let key = self.generate_condition_groups_with_config_cache_key(table, condition_groups, options);

        debug!(
            "开始缓存条件组合查询结果(完整版): table={}, key={}, count={}",
            table,
            key,
            results.len()
        );

        // 检查结果大小限制,避免缓存过大结果
        if results.len() > 1000 {
            debug!("跳过缓存:结果集过大 ({} > 1000)", results.len());
            return Ok(());
        }

        // 将所有DataValue转换为JSON值进行序列化
        let json_results: Vec<serde_json::Value> = results
            .iter()
            .map(|dv| {
                match dv {
                    DataValue::Json(json_val) => json_val.clone(),
                    DataValue::String(s) => serde_json::Value::String(s.clone()),
                    DataValue::Int(i) => serde_json::Value::Number(serde_json::Number::from(*i)),
                    DataValue::UInt(u) => serde_json::Value::Number(serde_json::Number::from(*u)),
                    DataValue::Float(f) => serde_json::Value::Number(serde_json::Number::from_f64(*f).unwrap_or(serde_json::Number::from(0))),
                    DataValue::Bool(b) => serde_json::Value::Bool(*b),
                    DataValue::DateTime(dt) => serde_json::Value::String(dt.to_rfc3339()),
                    DataValue::DateTimeUTC(dt) => serde_json::Value::String(dt.to_rfc3339()),
                    DataValue::Null => serde_json::Value::Null,
                    DataValue::Bytes(bytes) => serde_json::Value::String(base64::encode(bytes)),
                    DataValue::Uuid(uuid) => serde_json::Value::String(uuid.to_string()),
                    DataValue::Array(arr) => {
                        let json_array: Vec<serde_json::Value> = arr.iter().map(|item| {
                            match item {
                                DataValue::Json(json_val) => json_val.clone(),
                                DataValue::String(s) => serde_json::Value::String(s.clone()),
                                DataValue::Int(i) => serde_json::Value::Number(serde_json::Number::from(*i)),
                                DataValue::UInt(u) => serde_json::Value::Number(serde_json::Number::from(*u)),
                                DataValue::Float(f) => serde_json::Value::Number(serde_json::Number::from_f64(*f).unwrap_or(serde_json::Number::from(0))),
                                DataValue::Bool(b) => serde_json::Value::Bool(*b),
                                DataValue::DateTime(dt) => serde_json::Value::String(dt.to_rfc3339()),
                                DataValue::DateTimeUTC(dt) => serde_json::Value::String(dt.to_rfc3339()),
                                DataValue::Null => serde_json::Value::Null,
                                DataValue::Bytes(bytes) => serde_json::Value::String(base64::encode(bytes)),
                                DataValue::Uuid(uuid) => serde_json::Value::String(uuid.to_string()),
                                _ => serde_json::Value::String(format!("{:?}", item)),
                            }
                        }).collect();
                        serde_json::Value::Array(json_array)
                    }
                    DataValue::Object(obj) => {
                        let mut json_obj = serde_json::Map::new();
                        for (key, value) in obj {
                            let json_value = match value {
                                DataValue::Json(json_val) => json_val.clone(),
                                DataValue::String(s) => serde_json::Value::String(s.clone()),
                                DataValue::Int(i) => serde_json::Value::Number(serde_json::Number::from(*i)),
                                DataValue::UInt(u) => serde_json::Value::Number(serde_json::Number::from(*u)),
                                DataValue::Float(f) => serde_json::Value::Number(serde_json::Number::from_f64(*f).unwrap_or(serde_json::Number::from(0))),
                                DataValue::Bool(b) => serde_json::Value::Bool(*b),
                                DataValue::DateTime(dt) => serde_json::Value::String(dt.to_rfc3339()),
                                DataValue::DateTimeUTC(dt) => serde_json::Value::String(dt.to_rfc3339()),
                                DataValue::Null => serde_json::Value::Null,
                                DataValue::Bytes(bytes) => serde_json::Value::String(base64::encode(bytes)),
                                DataValue::Uuid(uuid) => serde_json::Value::String(uuid.to_string()),
                                _ => serde_json::Value::String(format!("{:?}", value)),
                            };
                            json_obj.insert(key.clone(), json_value);
                        }
                        serde_json::Value::Object(json_obj)
                    }
                }
            })
            .collect();

        let serialized = serde_json::to_vec(&json_results)
            .map_err(|e| anyhow!("Failed to serialize condition groups query results: {}", e))?;

        let cache_options = CacheOptions {
            ttl_seconds: Some(self.config.ttl_config.default_ttl_secs),
            ..Default::default()
        };

        self.cache
            .set_with_options(key.clone(), Bytes::from(serialized), &cache_options)
            .await
            .map_err(|e| anyhow!("Failed to cache condition groups query results: {}", e))?;

        // 记录缓存键
        self.track_cache_key(table, key.clone()).await;

        // 更新统计信息
        let elapsed = start_time.elapsed();
        self.writes_counter.fetch_add(1, Ordering::Relaxed);
        {
            let mut stats = self.stats.write().await;
            stats.writes += 1;
            stats.write_count += 1;
            stats.total_write_latency_ns += elapsed.as_nanos() as u64;
        }

        debug!(
            "已缓存条件组合查询结果(完整版): table={}, key={}, count={}",
            table,
            key,
            results.len()
        );
        Ok(())
    }

    /// 通用的缓存结果获取方法
    async fn get_cached_result_by_key(
        &self,
        key: &str,
        table: &str,
        start_time: Instant,
    ) -> Result<Option<Vec<DataValue>>> {
        match self.cache.get(&key).await {
            Ok(Some(data)) => {
                // 修复:正确反序列化为对应的DataValue类型
                let json_results: Vec<serde_json::Value> = serde_json::from_slice(&data)
                    .map_err(|e| anyhow!("Failed to deserialize cached query results: {}", e))?;

                let data_values: Vec<DataValue> = json_results
                    .into_iter()
                    .map(|json_val| {
                        match json_val {
                            serde_json::Value::String(s) => {
                                // 尝试解析为UUID
                                if let Ok(uuid) = uuid::Uuid::parse_str(&s) {
                                    DataValue::Uuid(uuid)
                                }
                                // 尝试解析为DateTime
                                else if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(&s) {
                                    DataValue::DateTime(
                                        dt.with_timezone(&chrono::FixedOffset::east(0)),
                                    )
                                }
                                // 尝试解析为base64编码的字节数据
                                else if s.starts_with("data:")
                                    || (s.len() % 4 == 0
                                        && s.chars().all(|c| {
                                            c.is_ascii_alphanumeric()
                                                || c == '+'
                                                || c == '/'
                                                || c == '='
                                        }))
                                {
                                    if let Ok(bytes) = base64::decode(&s) {
                                        DataValue::Bytes(bytes)
                                    } else {
                                        DataValue::String(s)
                                    }
                                } else {
                                    DataValue::String(s)
                                }
                            }
                            serde_json::Value::Number(n) => {
                                if let Some(i) = n.as_i64() {
                                    DataValue::Int(i)
                                } else if let Some(f) = n.as_f64() {
                                    DataValue::Float(f)
                                } else {
                                    DataValue::Int(0) // 默认值
                                }
                            }
                            serde_json::Value::Bool(b) => DataValue::Bool(b),
                            serde_json::Value::Null => DataValue::Null,
                            serde_json::Value::Array(arr) => {
                                let data_array: Vec<DataValue> = arr
                                    .into_iter()
                                    .map(|item| {
                                        // 递归处理数组元素
                                        match item {
                                            serde_json::Value::String(s) => DataValue::String(s),
                                            serde_json::Value::Number(n) => {
                                                if let Some(i) = n.as_i64() {
                                                    DataValue::Int(i)
                                                } else if let Some(f) = n.as_f64() {
                                                    DataValue::Float(f)
                                                } else {
                                                    DataValue::Int(0)
                                                }
                                            }
                                            serde_json::Value::Bool(b) => DataValue::Bool(b),
                                            serde_json::Value::Null => DataValue::Null,
                                            other => DataValue::Json(other),
                                        }
                                    })
                                    .collect();
                                DataValue::Array(data_array)
                            }
                            serde_json::Value::Object(obj) => {
                                let mut data_obj = std::collections::HashMap::new();
                                for (key, value) in obj {
                                    let data_value = match value {
                                        serde_json::Value::String(s) => DataValue::String(s),
                                        serde_json::Value::Number(n) => {
                                            if let Some(i) = n.as_i64() {
                                                DataValue::Int(i)
                                            } else if let Some(f) = n.as_f64() {
                                                DataValue::Float(f)
                                            } else {
                                                DataValue::Int(0)
                                            }
                                        }
                                        serde_json::Value::Bool(b) => DataValue::Bool(b),
                                        serde_json::Value::Null => DataValue::Null,
                                        other => DataValue::Json(other),
                                    };
                                    data_obj.insert(key, data_value);
                                }
                                DataValue::Object(data_obj)
                            }
                        }
                    })
                    .collect();

                // 更新命中统计
                let elapsed = start_time.elapsed();
                self.hits_counter.fetch_add(1, Ordering::Relaxed);
                {
                    let mut stats = self.stats.write().await;
                    stats.hits += 1;
                    stats.query_count += 1;
                    stats.total_query_latency_ns += elapsed.as_nanos() as u64;
                }

                debug!(
                    "查询缓存命中: table={}, key={}, count={}",
                    table,
                    key,
                    data_values.len()
                );
                Ok(Some(data_values))
            }
            Ok(None) => {
                // 更新未命中统计
                let elapsed = start_time.elapsed();
                self.misses_counter.fetch_add(1, Ordering::Relaxed);
                {
                    let mut stats = self.stats.write().await;
                    stats.misses += 1;
                    stats.query_count += 1;
                    stats.total_query_latency_ns += elapsed.as_nanos() as u64;
                }

                debug!("查询缓存未命中: table={}, key={}", table, key);
                Ok(None)
            }
            Err(e) => {
                // 错误也算作未命中
                let elapsed = start_time.elapsed();
                self.misses_counter.fetch_add(1, Ordering::Relaxed);
                {
                    let mut stats = self.stats.write().await;
                    stats.misses += 1;
                    stats.query_count += 1;
                    stats.total_query_latency_ns += elapsed.as_nanos() as u64;
                }

                warn!(
                    "查询缓存读取失败: table={}, key={}, error={}",
                    table, key, e
                );
                Ok(None)
            }
        }
    }
}