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
//! Model trait 定义模块
//!
//! 定义模型的核心接口和操作特征

use crate::error::{QuickDbError, QuickDbResult};
use crate::model::conversion::ToDataValue;
use crate::model::field_types::{FieldDefinition, FieldType, ModelMeta};
use crate::types::*;
use async_trait::async_trait;
use base64;
use rat_logger::{debug, error, info, warn};
use serde::{Deserialize, Serialize};
use serde_json::Value as JsonValue;
use std::collections::HashMap;
use std::marker::PhantomData;

/// 模型特征
///
/// 所有模型都必须实现这个特征
pub trait Model: Serialize + for<'de> Deserialize<'de> + Send + Sync {
    /// 获取模型元数据
    fn meta() -> ModelMeta;

    /// 获取集合/表名
    fn collection_name() -> String {
        Self::meta().collection_name
    }

    /// 获取数据库别名
    fn database_alias() -> Option<String> {
        Self::meta().database_alias
    }

    /// 验证模型数据
    fn validate(&self) -> QuickDbResult<()> {
        let meta = Self::meta();
        let data = self.to_data_map()?;

        // 调试信息:打印序列化后的数据
        debug!("🔍 验证数据映射: {:?}", data);

        for (field_name, field_def) in &meta.fields {
            let field_value = data.get(field_name).unwrap_or(&DataValue::Null);
            debug!("🔍 验证字段 {}: {:?}", field_name, field_value);
            field_def.validate_with_field_name(field_value, field_name)?;
        }

        Ok(())
    }

    /// 转换为数据映射(直接转换,避免 JSON 序列化开销)
    /// 子类应该重写此方法以提供高性能的直接转换
    fn to_data_map_direct(&self) -> QuickDbResult<HashMap<String, DataValue>> {
        // 默认回退到 JSON 序列化方式,但建议子类重写
        warn!("使用默认的 JSON 序列化方式,建议重写 to_data_map_direct 方法以提高性能");
        self.to_data_map_legacy()
    }

    /// 转换为数据映射(传统 JSON 序列化方式)
    /// 保留此方法用于向后兼容和调试
    fn to_data_map_legacy(&self) -> QuickDbResult<HashMap<String, DataValue>> {
        let json_str =
            serde_json::to_string(self).map_err(|e| QuickDbError::SerializationError {
                message: format!("序列化失败: {}", e),
            })?;
        debug!("🔍 序列化后的JSON字符串: {}", json_str);

        let json_value: JsonValue =
            serde_json::from_str(&json_str).map_err(|e| QuickDbError::SerializationError {
                message: format!("解析JSON失败: {}", e),
            })?;
        debug!("🔍 解析后的JsonValue: {:?}", json_value);

        let mut data_map = HashMap::new();
        if let JsonValue::Object(obj) = json_value {
            for (key, value) in obj {
                let data_value = DataValue::from_json(value.clone());
                debug!("🔍 字段 {} 转换: {:?} -> {:?}", key, value, data_value);
                data_map.insert(key, data_value);
            }
        }

        Ok(data_map)
    }

    /// 将模型转换为数据映射(高性能版本)
    fn to_data_map(&self) -> QuickDbResult<HashMap<String, DataValue>> {
        self.to_data_map_direct()
    }

    /// 将模型转换为带类型信息的数据映射(专门用于 PyO3 兼容序列化)
    /// 对于 None 值,会根据字段类型生成带类型标签的 DataValue
    fn to_data_map_with_types(&self) -> QuickDbResult<HashMap<String, DataValue>> {
        let json_map = self.to_data_map_with_types_json()?;
        // 将 HashMap<String, JsonValue> 转换为 HashMap<String, DataValue>
        let mut data_map = HashMap::new();
        for (key, json_value) in json_map {
            data_map.insert(key, DataValue::Json(json_value));
        }
        Ok(data_map)
    }

    /// 将模型转换为带类型信息的 JSON 映射(专门用于 PyO3 兼容序列化)
    /// 对于 None 值,会根据字段类型生成带类型标签的 JsonValue
    /// 这个方法直接返回 JsonValue,避免 DataValue 的额外嵌套
    fn to_data_map_with_types_json(&self) -> QuickDbResult<HashMap<String, JsonValue>> {
        let meta = Self::meta();
        let mut data_map = HashMap::new();

        // 遍历模型的所有字段
        let json_str =
            serde_json::to_string(self).map_err(|e| QuickDbError::SerializationError {
                message: format!("序列化失败: {}", e),
            })?;

        debug!("🔍 to_data_map_with_types_json 序列化的JSON: {}", json_str);

        let json_value: JsonValue =
            serde_json::from_str(&json_str).map_err(|e| QuickDbError::SerializationError {
                message: format!("解析JSON失败: {}", e),
            })?;

        debug!(
            "🔍 to_data_map_with_types_json 解析后的JSON: {:?}",
            json_value
        );

        if let JsonValue::Object(obj) = json_value {
            for (key, value) in obj {
                // 检查字段是否在元数据中定义
                if let Some(field_def) = meta.fields.get(&key) {
                    // 对所有字段都生成带类型标签的 JsonValue
                    let type_name = match &field_def.field_type {
                        FieldType::String { .. } => "String",
                        FieldType::Integer { .. } => "Int",
                        FieldType::Float { .. } => "Float",
                        FieldType::BigInteger => "Int",
                        FieldType::Double => "Float",
                        FieldType::Text => "String",
                        FieldType::Boolean => "Bool",
                        FieldType::DateTime => "DateTime",
                        FieldType::DateTimeWithTz { .. } => "DateTime", // 带时区的DateTime
                        FieldType::Date => "DateTime",
                        FieldType::Time => "DateTime",
                        FieldType::Uuid => "Uuid",
                        FieldType::Json => "Json",
                        FieldType::Binary => "Bytes",
                        FieldType::Decimal { .. } => "Float",
                        FieldType::Array { .. } => "Array",
                        FieldType::Object { .. } => "Object",
                        FieldType::Reference { .. } => "String",
                    };

                    // 直接创建带类型标签的 JsonValue,避免嵌套
                    let typed_json = match value {
                        JsonValue::Null => {
                            // 对于 null 值,创建 {类型名: null}
                            let mut type_obj = serde_json::Map::new();
                            type_obj.insert(type_name.to_string(), JsonValue::Null);
                            JsonValue::Object(type_obj)
                        }
                        JsonValue::String(s) => {
                            // 对于字符串值,创建 {类型名: "value"}
                            let mut type_obj = serde_json::Map::new();
                            type_obj.insert(type_name.to_string(), JsonValue::String(s));
                            JsonValue::Object(type_obj)
                        }
                        JsonValue::Number(n) => {
                            // 对于数字值,根据类型包装
                            let mut type_obj = serde_json::Map::new();
                            type_obj.insert(type_name.to_string(), JsonValue::Number(n));
                            JsonValue::Object(type_obj)
                        }
                        JsonValue::Bool(b) => {
                            // 对于布尔值,创建 {类型名: boolean}
                            let mut type_obj = serde_json::Map::new();
                            type_obj.insert(type_name.to_string(), JsonValue::Bool(b));
                            JsonValue::Object(type_obj)
                        }
                        JsonValue::Array(arr) => {
                            // 对于数组,需要根据字段类型为每个元素添加类型标记
                            if let FieldType::Array { item_type, .. } = &field_def.field_type {
                                let item_type_name = match &**item_type {
                                    FieldType::String { .. } => "String",
                                    FieldType::Integer { .. } => "Int",
                                    FieldType::Float { .. } => "Float",
                                    FieldType::BigInteger => "Int",
                                    FieldType::Double => "Float",
                                    FieldType::Text => "String",
                                    FieldType::Boolean => "Bool",
                                    FieldType::DateTime => "DateTime",
                                    FieldType::DateTimeWithTz { .. } => "DateTime", // 带时区的DateTime
                                    FieldType::Date => "DateTime",
                                    FieldType::Time => "DateTime",
                                    FieldType::Uuid => "Uuid",
                                    FieldType::Json => "Json",
                                    FieldType::Binary => "Bytes",
                                    FieldType::Decimal { .. } => "Float",
                                    FieldType::Array { .. } => "Array",
                                    FieldType::Object { .. } => "Object",
                                    FieldType::Reference { .. } => "String",
                                };

                                let processed_array: Vec<JsonValue> = arr
                                    .into_iter()
                                    .map(|v| {
                                        // 为每个数组元素添加类型标记
                                        let mut item_type_obj = serde_json::Map::new();
                                        match v {
                                            JsonValue::String(s) => {
                                                item_type_obj.insert(
                                                    item_type_name.to_string(),
                                                    JsonValue::String(s),
                                                );
                                            }
                                            JsonValue::Number(n) => {
                                                item_type_obj.insert(
                                                    item_type_name.to_string(),
                                                    JsonValue::Number(n),
                                                );
                                            }
                                            JsonValue::Bool(b) => {
                                                item_type_obj.insert(
                                                    item_type_name.to_string(),
                                                    JsonValue::Bool(b),
                                                );
                                            }
                                            JsonValue::Null => {
                                                item_type_obj.insert(
                                                    item_type_name.to_string(),
                                                    JsonValue::Null,
                                                );
                                            }
                                            JsonValue::Array(nested_arr) => {
                                                // 嵌套数组暂时保持原样,实际使用中应该递归处理
                                                item_type_obj.insert(
                                                    item_type_name.to_string(),
                                                    JsonValue::Array(nested_arr),
                                                );
                                            }
                                            JsonValue::Object(nested_obj) => {
                                                // 嵌套对象暂时保持原样,实际使用中应该递归处理
                                                item_type_obj.insert(
                                                    item_type_name.to_string(),
                                                    JsonValue::Object(nested_obj),
                                                );
                                            }
                                        }
                                        JsonValue::Object(item_type_obj)
                                    })
                                    .collect();
                                let mut type_obj = serde_json::Map::new();
                                type_obj.insert(
                                    type_name.to_string(),
                                    JsonValue::Array(processed_array),
                                );
                                JsonValue::Object(type_obj)
                            } else {
                                // 如果不是数组类型,保持原有逻辑
                                let processed_array: Vec<JsonValue> = arr
                                    .into_iter()
                                    .map(|v| match v {
                                        JsonValue::String(s) => JsonValue::String(s),
                                        JsonValue::Number(n) => JsonValue::Number(n),
                                        JsonValue::Bool(b) => JsonValue::Bool(b),
                                        JsonValue::Null => JsonValue::Null,
                                        JsonValue::Array(_) => v,
                                        JsonValue::Object(_) => v,
                                    })
                                    .collect();
                                let mut type_obj = serde_json::Map::new();
                                type_obj.insert(
                                    type_name.to_string(),
                                    JsonValue::Array(processed_array),
                                );
                                JsonValue::Object(type_obj)
                            }
                        }
                        JsonValue::Object(obj) => {
                            // 对于对象,递归处理每个字段,然后包装类型
                            let processed_obj: serde_json::Map<String, JsonValue> = obj
                                .into_iter()
                                .map(|(k, v)| {
                                    let processed_value = match v {
                                        JsonValue::String(s) => JsonValue::String(s),
                                        JsonValue::Number(n) => JsonValue::Number(n),
                                        JsonValue::Bool(b) => JsonValue::Bool(b),
                                        JsonValue::Null => JsonValue::Null,
                                        JsonValue::Array(_) => v,
                                        JsonValue::Object(_) => v,
                                    };
                                    (k, processed_value)
                                })
                                .collect();
                            let mut type_obj = serde_json::Map::new();
                            type_obj
                                .insert(type_name.to_string(), JsonValue::Object(processed_obj));
                            JsonValue::Object(type_obj)
                        }
                    };

                    data_map.insert(key, typed_json);
                } else {
                    // 字段不在元数据中 - 这在 v0.3.0 中不应该发生,报错退出
                    return Err(QuickDbError::ValidationError {
                        field: key.clone(),
                        message: format!(
                            "字段 '{}' 未在模型元数据中定义,这在 v0.3.0 中是不允许的",
                            key
                        ),
                    });
                }
            }
        }

        Ok(data_map)
    }

    /// 从数据映射创建模型实例
    fn from_data_map(data: HashMap<String, DataValue>) -> QuickDbResult<Self> {
        // 使用模型元数据后处理数据字段,修复复杂类型字段反序列化问题
        let meta = Self::meta();
        let processed_data = crate::process_data_fields_from_metadata(data, &meta.fields);

        // 直接从HashMap<String, DataValue>转换为模型实例,避免JSON中转
        crate::model::data_conversion::create_model_from_data_map::<Self>(&processed_data)
    }
}

/// 记录操作特征
///
/// 提供记录的CRUD操作
#[async_trait]
pub trait ModelOperations<T: Model> {
    /// 保存记录
    async fn save(&self) -> QuickDbResult<String>;

    /// 根据ID查找记录
    async fn find_by_id(id: &str) -> QuickDbResult<Option<T>>;

    /// 查找多条记录(简化版)
    async fn find(
        conditions: Vec<QueryCondition>,
        options: Option<QueryOptions>,
    ) -> QuickDbResult<Vec<T>> {
        let conditions_with_config: Vec<QueryConditionWithConfig> = conditions
            .into_iter()
            .map(|c| c.into())
            .collect();
        Self::find_with_cache_control(conditions_with_config, options, false).await
    }

    /// 查找多条记录(支持缓存控制)
    async fn find_with_cache_control(
        conditions: Vec<QueryConditionWithConfig>,
        options: Option<QueryOptions>,
        bypass_cache: bool,
    ) -> QuickDbResult<Vec<T>>;

    /// 更新记录
    async fn update(&self, updates: HashMap<String, DataValue>) -> QuickDbResult<bool>;

    /// 删除记录
    async fn delete(&self) -> QuickDbResult<bool>;

    /// 统计记录数量(简化版)
    async fn count(conditions: Vec<QueryCondition>) -> QuickDbResult<u64> {
        let conditions_with_config: Vec<QueryConditionWithConfig> = conditions
            .into_iter()
            .map(|c| c.into())
            .collect();
        Self::count_with_config(conditions_with_config).await
    }

    /// 统计记录数量(完整版)
    async fn count_with_config(conditions: Vec<QueryConditionWithConfig>) -> QuickDbResult<u64>;

    /// 使用条件组统计记录数量(支持复杂的AND/OR逻辑组合)- 简化版
    ///
    /// 接受 `QueryConditionGroup`,自动转换为 `QueryConditionGroupWithConfig`
    async fn count_with_groups(
        condition_groups: Vec<QueryConditionGroup>,
    ) -> QuickDbResult<u64> {
        let condition_groups_with_config: Vec<QueryConditionGroupWithConfig> = condition_groups
            .into_iter()
            .map(|g| g.into())
            .collect();
        Self::count_with_groups_with_config(condition_groups_with_config).await
    }

    /// 使用条件组统计记录数量(支持复杂的AND/OR逻辑组合)- 完整版
    ///
    /// 接受 `QueryConditionGroupWithConfig`,支持大小写不敏感等高级配置
    async fn count_with_groups_with_config(
        condition_groups: Vec<QueryConditionGroupWithConfig>,
    ) -> QuickDbResult<u64>;

    /// 使用条件组查找多条记录(支持复杂的AND/OR逻辑组合)- 简化版
    ///
    /// 接受 `QueryConditionGroup`,自动转换为 `QueryConditionGroupWithConfig`
    async fn find_with_groups(
        condition_groups: Vec<QueryConditionGroup>,
        options: Option<QueryOptions>,
    ) -> QuickDbResult<Vec<T>> {
        Self::find_with_groups_with_cache_control(condition_groups, options, false).await
    }

    /// 使用条件组查找多条记录(支持缓存控制和复杂的AND/OR逻辑组合)- 简化版
    ///
    /// 接受 `QueryConditionGroup`,自动转换为 `QueryConditionGroupWithConfig`
    async fn find_with_groups_with_cache_control(
        condition_groups: Vec<QueryConditionGroup>,
        options: Option<QueryOptions>,
        bypass_cache: bool,
    ) -> QuickDbResult<Vec<T>> {
        let condition_groups_with_config: Vec<QueryConditionGroupWithConfig> = condition_groups
            .into_iter()
            .map(|g| g.into())
            .collect();
        Self::find_with_groups_with_cache_control_and_config(condition_groups_with_config, options, bypass_cache).await
    }

    /// 使用条件组查找多条记录(支持复杂的AND/OR逻辑组合)- 完整版
    ///
    /// 接受 `QueryConditionGroupWithConfig`,支持大小写不敏感等高级配置
    async fn find_with_groups_with_config(
        condition_groups: Vec<QueryConditionGroupWithConfig>,
        options: Option<QueryOptions>,
    ) -> QuickDbResult<Vec<T>> {
        Self::find_with_groups_with_cache_control_and_config(condition_groups, options, false).await
    }

    /// 使用条件组查找多条记录(支持缓存控制和复杂的AND/OR逻辑组合)- 完整版
    ///
    /// 接受 `QueryConditionGroupWithConfig`,支持大小写不敏感等高级配置
    async fn find_with_groups_with_cache_control_and_config(
        condition_groups: Vec<QueryConditionGroupWithConfig>,
        options: Option<QueryOptions>,
        bypass_cache: bool,
    ) -> QuickDbResult<Vec<T>>;

    /// 批量更新记录
    ///
    /// 根据条件批量更新多条记录,返回受影响的行数
    async fn update_many(
        conditions: Vec<QueryConditionWithConfig>,
        updates: HashMap<String, DataValue>,
    ) -> QuickDbResult<u64>;

    /// 使用操作数组批量更新模型
    ///
    /// 根据条件使用操作数组批量更新多条记录,支持原子性增减操作,返回受影响的行数
    async fn update_many_with_operations(
        conditions: Vec<QueryConditionWithConfig>,
        operations: Vec<crate::types::UpdateOperation>,
    ) -> QuickDbResult<u64>;

    /// 批量删除模型
    ///
    /// 根据条件批量删除多条记录,返回受影响的行数
    async fn delete_many(conditions: Vec<QueryConditionWithConfig>) -> QuickDbResult<u64>;

    /// 创建表
    ///
    /// 使用模型的元数据直接创建表,无需插入数据
    async fn create_table() -> QuickDbResult<()>;

    /// 创建存储过程
    ///
    /// 通过模型管理器创建跨模型的存储过程,以当前模型作为基表
    async fn create_stored_procedure(
        config: crate::stored_procedure::StoredProcedureConfig,
    ) -> QuickDbResult<crate::stored_procedure::StoredProcedureCreateResult>;

    /// 执行存储过程查询
    ///
    /// 通过模型管理器执行存储过程查询,使用当前模型的数据库别名
    async fn execute_stored_procedure(
        procedure_name: &str,
        params: Option<std::collections::HashMap<String, crate::types::DataValue>>,
    ) -> QuickDbResult<crate::stored_procedure::StoredProcedureQueryResult>;
}