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
//! 缓存数据库适配器
//!
//! 提供带缓存功能的数据库适配器包装器,在适配器层实现缓存逻辑

use super::DatabaseAdapter;
use crate::cache::CacheManager;
use crate::error::QuickDbResult;
use crate::model::FieldDefinition;
use crate::pool::DatabaseConnection;
use crate::types::*;
use async_trait::async_trait;
use rat_logger::{debug, warn};
use std::collections::HashMap;
use std::sync::Arc;

/// 带缓存功能的数据库适配器包装器
pub struct CachedDatabaseAdapter {
    /// 内部真实的数据库适配器
    inner: Box<dyn DatabaseAdapter>,
    /// 缓存管理器
    cache_manager: Arc<CacheManager>,
}

impl CachedDatabaseAdapter {
    /// 创建新的缓存适配器
    pub fn new(inner: Box<dyn DatabaseAdapter>, cache_manager: Arc<CacheManager>) -> Self {
        Self {
            inner,
            cache_manager,
        }
    }
}

#[async_trait]
impl DatabaseAdapter for CachedDatabaseAdapter {
    /// 创建记录 - 创建成功后智能清理相关缓存
    async fn create(
        &self,
        connection: &DatabaseConnection,
        table: &str,
        data: &HashMap<String, DataValue>,
        id_strategy: &IdStrategy,
        alias: &str,
    ) -> QuickDbResult<DataValue> {
        let result = self
            .inner
            .create(connection, table, data, id_strategy, alias)
            .await;

        // 创建成功后只清理查询缓存,保留记录缓存
        if result.is_ok() {
            if let Err(e) = self.cache_manager.clear_table_query_cache(table).await {
                warn!("清理表查询缓存失败: {}", e);
            }
            debug!("已清理表查询缓存: table={}", table);
        }

        result
    }

    /// 根据ID查找记录 - 先检查缓存,缓存未命中时查询数据库并缓存结果
    async fn find_by_id(
        &self,
        connection: &DatabaseConnection,
        table: &str,
        id: &DataValue,
        alias: &str,
    ) -> QuickDbResult<Option<DataValue>> {
        // 将DataValue转换为IdType
        let id_type = match id {
            DataValue::Int(n) => IdType::Number(*n),
            DataValue::String(s) => IdType::String(s.clone()),
            _ => {
                warn!("无法将DataValue转换为IdType: {:?}", id);
                return self.inner.find_by_id(connection, table, id, alias).await;
            }
        };

        // 先检查缓存
        match self.cache_manager.get_cached_record(table, &id_type).await {
            Ok(Some(cached_result)) => {
                debug!("缓存命中: 表={}, ID={:?}", table, id);
                return Ok(Some(cached_result));
            }
            Ok(None) => {
                debug!("缓存未命中: 表={}, ID={:?}", table, id);
            }
            Err(e) => {
                warn!("缓存查询失败: {}, 继续查询数据库", e);
            }
        }

        // 缓存未命中或查询失败,查询数据库
        let result = self.inner.find_by_id(connection, table, id, alias).await;

        // 查询成功时缓存结果
        if let Ok(Some(ref record)) = result {
            if let Err(e) = self
                .cache_manager
                .cache_record(table, &id_type, record)
                .await
            {
                warn!("缓存记录失败: {}", e);
            }
        }

        result
    }

    /// 查找记录(支持缓存控制)- 内部统一使用 find_with_groups_with_cache_control_and_config 实现
    async fn find_with_cache_control(
        &self,
        connection: &DatabaseConnection,
        table: &str,
        conditions: &[QueryConditionWithConfig],
        options: &QueryOptions,
        alias: &str,
        bypass_cache: bool,
    ) -> QuickDbResult<Vec<DataValue>> {
        // 将简单条件转换为条件组合(AND逻辑)
        let condition_groups = if conditions.is_empty() {
            vec![]
        } else {
            let group_conditions: Vec<QueryConditionGroupWithConfig> = conditions
                .iter()
                .map(|c| QueryConditionGroupWithConfig::Single(c.clone()))
                .collect();
            vec![QueryConditionGroupWithConfig::GroupWithConfig {
                operator: LogicalOperator::And,
                conditions: group_conditions,
            }]
        };

        // 统一使用 find_with_groups_with_cache_control_and_config 实现
        self.find_with_groups_with_cache_control_and_config(connection, table, &condition_groups, options, alias, bypass_cache)
            .await
    }

    /// 使用条件组合查找记录(支持缓存控制)- 简化版,转换为完整版后调用
    async fn find_with_groups_with_cache_control(
        &self,
        connection: &DatabaseConnection,
        table: &str,
        condition_groups: &[QueryConditionGroup],
        options: &QueryOptions,
        alias: &str,
        bypass_cache: bool,
    ) -> QuickDbResult<Vec<DataValue>> {
        // 转换为完整版
        let condition_groups_with_config: Vec<QueryConditionGroupWithConfig> = condition_groups
            .iter()
            .map(|g| g.clone().into())
            .collect();
        self.find_with_groups_with_cache_control_and_config(
            connection,
            table,
            &condition_groups_with_config,
            options,
            alias,
            bypass_cache,
        )
        .await
    }

    /// 使用条件组合查找记录(支持缓存控制和完整配置)- 完整版实现
    async fn find_with_groups_with_cache_control_and_config(
        &self,
        connection: &DatabaseConnection,
        table: &str,
        condition_groups: &[QueryConditionGroupWithConfig],
        options: &QueryOptions,
        alias: &str,
        bypass_cache: bool,
    ) -> QuickDbResult<Vec<DataValue>> {
        // 生成条件组合查询缓存键
        let cache_key = self.cache_manager.generate_condition_groups_with_config_cache_key(
            table,
            condition_groups,
            options,
        );

        // 如果不跳过缓存,先检查缓存
        if !bypass_cache {
            match self
                .cache_manager
                .get_cached_condition_groups_with_config_result(table, condition_groups, options)
                .await
            {
                Ok(Some(cached_result)) => {
                    debug!("条件组合查询缓存命中: 表={}, 键={}", table, cache_key);
                    return Ok(cached_result);
                }
                Ok(None) => {
                    debug!("条件组合查询缓存未命中: 表={}, 键={}", table, cache_key);
                }
                Err(e) => {
                    warn!("获取条件组合查询缓存失败: {}", e);
                }
            }
        } else {
            debug!("强制跳过缓存: 表={}, 键={}", table, cache_key);
        }

        // 查询数据库(缓存未命中或强制跳过缓存)
        let result = self
            .inner
            .find_with_groups_with_config(connection, table, condition_groups, options, alias)
            .await?;

        // 缓存查询结果(仅在不跳过缓存时)
        if !bypass_cache {
            if let Err(e) = self
                .cache_manager
                .cache_condition_groups_with_config_result(table, condition_groups, options, &result)
                .await
            {
                warn!("缓存条件组合查询结果失败: {}", e);
            } else {
                debug!(
                    "已缓存条件组合查询结果: 表={}, 键={}, 结果数量={}",
                    table,
                    cache_key,
                    result.len()
                );
            }
        }

        Ok(result)
    }

    /// 更新记录 - 更新成功后智能清理相关缓存
    async fn update(
        &self,
        connection: &DatabaseConnection,
        table: &str,
        conditions: &[QueryConditionWithConfig],
        data: &HashMap<String, DataValue>,
        alias: &str,
    ) -> QuickDbResult<u64> {
        // 直接调用内部适配器更新记录
        let result = self
            .inner
            .update(connection, table, conditions, data, alias)
            .await;

        // 更新成功后只清理查询缓存,避免过度清理
        if let Ok(updated_count) = result {
            if updated_count > 0 {
                if let Err(e) = self.cache_manager.clear_table_query_cache(table).await {
                    warn!("清理表查询缓存失败: {}", e);
                }
                debug!(
                    "已清理表查询缓存: table={}, updated_count={}",
                    table, updated_count
                );
            }
        }

        result
    }

    /// 使用操作数组更新记录 - 更新成功后智能清理相关缓存
    async fn update_with_operations(
        &self,
        connection: &DatabaseConnection,
        table: &str,
        conditions: &[QueryConditionWithConfig],
        operations: &[crate::types::UpdateOperation],
        alias: &str,
    ) -> QuickDbResult<u64> {
        // 直接调用内部适配器更新记录
        let result = self
            .inner
            .update_with_operations(connection, table, conditions, operations, alias)
            .await;

        // 更新成功后只清理查询缓存,避免过度清理
        if let Ok(updated_count) = result {
            if updated_count > 0 {
                if let Err(e) = self.cache_manager.clear_table_query_cache(table).await {
                    warn!("清理表查询缓存失败: {}", e);
                }
                debug!(
                    "已清理表查询缓存: table={}, updated_count={}",
                    table, updated_count
                );
            }
        }

        result
    }

    /// 根据ID更新记录 - 更新成功后精确清理相关缓存
    async fn update_by_id(
        &self,
        connection: &DatabaseConnection,
        table: &str,
        id: &DataValue,
        data: &HashMap<String, DataValue>,
        alias: &str,
    ) -> QuickDbResult<bool> {
        // 直接调用内部适配器更新记录
        let result = self
            .inner
            .update_by_id(connection, table, id, data, alias)
            .await;

        // 更新成功后精确清理相关缓存
        if let Ok(true) = result {
            // 清理特定记录的缓存
            let id_value = match id {
                DataValue::Int(n) => IdType::Number(*n),
                DataValue::String(s) => IdType::String(s.clone()),
                _ => {
                    warn!("无法将DataValue转换为IdType: {:?}", id);
                    return result;
                }
            };

            // 清理记录缓存
            if let Err(e) = self.cache_manager.invalidate_record(table, &id_value).await {
                warn!("清理记录缓存失败: {}", e);
            }

            // 只清理查询缓存,不清理其他记录缓存
            if let Err(e) = self.cache_manager.clear_table_query_cache(table).await {
                warn!("清理表查询缓存失败: {}", e);
            }

            debug!("已清理记录和查询缓存: table={}, id={:?}", table, id);
        }

        result
    }

    /// 删除记录 - 删除成功后智能清理相关缓存
    async fn delete(
        &self,
        connection: &DatabaseConnection,
        table: &str,
        conditions: &[QueryConditionWithConfig],
        alias: &str,
    ) -> QuickDbResult<u64> {
        // 直接调用内部适配器删除记录
        let result = self
            .inner
            .delete(connection, table, conditions, alias)
            .await;

        // 删除成功后智能清理相关缓存
        if let Ok(deleted_count) = result {
            if deleted_count > 0 {
                // 对于批量删除,清理整个表的缓存是合理的
                if let Err(e) = self.cache_manager.clear_table_query_cache(table).await {
                    warn!("清理表查询缓存失败: {}", e);
                }
                if let Err(e) = self.cache_manager.clear_table_record_cache(table).await {
                    warn!("清理表记录缓存失败: {}", e);
                }
                debug!(
                    "已清理表缓存: table={}, deleted_count={}",
                    table, deleted_count
                );
            }
        }

        result
    }

    /// 根据ID删除记录 - 删除成功后精确清理相关缓存
    async fn delete_by_id(
        &self,
        connection: &DatabaseConnection,
        table: &str,
        id: &DataValue,
        alias: &str,
    ) -> QuickDbResult<bool> {
        // 直接调用内部适配器删除记录
        let result = self.inner.delete_by_id(connection, table, id, alias).await;

        // 删除成功后精确清理相关缓存
        if let Ok(true) = result {
            // 清理特定记录的缓存
            let id_value = match id {
                DataValue::Int(n) => IdType::Number(*n),
                DataValue::String(s) => IdType::String(s.clone()),
                _ => {
                    warn!("无法将DataValue转换为IdType: {:?}", id);
                    return result;
                }
            };

            // 清理记录缓存
            if let Err(e) = self.cache_manager.invalidate_record(table, &id_value).await {
                warn!("清理记录缓存失败: {}", e);
            }

            // 只清理查询缓存
            if let Err(e) = self.cache_manager.clear_table_query_cache(table).await {
                warn!("清理表查询缓存失败: {}", e);
            }

            debug!("已清理记录和查询缓存: table={}, id={:?}", table, id);
        }

        result
    }

    /// 统计记录数量 - 直接调用内部适配器,不缓存统计结果
    async fn count(
        &self,
        connection: &DatabaseConnection,
        table: &str,
        conditions: &[QueryConditionWithConfig],
        alias: &str,
    ) -> QuickDbResult<u64> {
        // 统计操作不缓存,直接调用内部适配器
        self.inner.count(connection, table, conditions, alias).await
    }

    /// 使用条件组合统计记录数量 - 直接调用内部适配器,不缓存统计结果
    async fn count_with_groups(
        &self,
        connection: &DatabaseConnection,
        table: &str,
        condition_groups: &[QueryConditionGroupWithConfig],
        alias: &str,
    ) -> QuickDbResult<u64> {
        // 统计操作不缓存,直接调用内部适配器
        self.inner.count_with_groups(connection, table, condition_groups, alias).await
    }

    /// 创建表/集合 - 直接调用内部适配器
    async fn create_table(
        &self,
        connection: &DatabaseConnection,
        table: &str,
        fields: &HashMap<String, FieldDefinition>,
        id_strategy: &IdStrategy,
        alias: &str,
    ) -> QuickDbResult<()> {
        // 表结构操作不缓存,直接调用内部适配器
        self.inner
            .create_table(connection, table, fields, id_strategy, alias)
            .await
    }

    /// 创建索引 - 直接调用内部适配器
    async fn create_index(
        &self,
        connection: &DatabaseConnection,
        table: &str,
        index_name: &str,
        fields: &[String],
        unique: bool,
    ) -> QuickDbResult<()> {
        // 索引操作不缓存,直接调用内部适配器
        self.inner
            .create_index(connection, table, index_name, fields, unique)
            .await
    }

    /// 检查表是否存在 - 直接调用内部适配器
    async fn table_exists(
        &self,
        connection: &DatabaseConnection,
        table: &str,
    ) -> QuickDbResult<bool> {
        self.inner.table_exists(connection, table).await
    }

    /// 删除表 - 删除成功后清理所有相关缓存
    async fn drop_table(&self, connection: &DatabaseConnection, table: &str) -> QuickDbResult<()> {
        let result = self.inner.drop_table(connection, table).await;

        // 删除成功后清理所有相关缓存
        if result.is_ok() {
            if let Err(e) = self.cache_manager.clear_table_query_cache(table).await {
                warn!("清理表缓存失败: {}", e);
            }
            debug!("已清理表缓存: table={}", table);
        }

        result
    }

    async fn get_server_version(&self, connection: &DatabaseConnection) -> QuickDbResult<String> {
        // 版本查询通常不涉及具体数据,直接调用内部适配器
        self.inner.get_server_version(connection).await
    }

    /// 创建存储过程 - 直接调用内部适配器
    async fn create_stored_procedure(
        &self,
        connection: &DatabaseConnection,
        config: &crate::stored_procedure::StoredProcedureConfig,
    ) -> QuickDbResult<crate::stored_procedure::StoredProcedureCreateResult> {
        // 存储过程创建不缓存,直接调用内部适配器
        self.inner.create_stored_procedure(connection, config).await
    }

    /// 执行存储过程 - 直接调用内部适配器
    async fn execute_stored_procedure(
        &self,
        connection: &DatabaseConnection,
        procedure_name: &str,
        database: &str,
        params: Option<std::collections::HashMap<String, crate::types::DataValue>>,
    ) -> QuickDbResult<crate::stored_procedure::StoredProcedureQueryResult> {
        // 存储过程执行不缓存,直接调用内部适配器
        self.inner
            .execute_stored_procedure(connection, procedure_name, database, params)
            .await
    }
}