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
636
637
638
639
640
641
642
643
644
645
646
647
//! MongoDB查询构建器模块
//!
//! 提供MongoDB查询文档的构建功能,支持基于字段元数据的Contains操作符

use crate::adapter::utils::get_field_type;
use crate::error::{QuickDbError, QuickDbResult};
use crate::types::*;
use mongodb::bson::{Bson, Document, Regex, doc};
use rat_logger::debug;

/// 映射字段名(适配MongoDB命名约定)
/// 将通用的字段名映射为MongoDB特定的字段名
fn map_field_name(field_name: &str) -> &str {
    // MongoDB使用_id作为主键,而不是id
    if field_name == "id" {
        "_id"
    } else {
        field_name
    }
}

/// MongoDB查询构建器
pub struct MongoQueryBuilder {
    conditions: Vec<QueryConditionWithConfig>,
    condition_groups: Vec<QueryConditionGroup>,
    condition_groups_with_config: Vec<QueryConditionGroupWithConfig>,
}

impl MongoQueryBuilder {
    /// 创建新的MongoDB查询构建器
    pub fn new() -> Self {
        Self {
            conditions: Vec::new(),
            condition_groups: Vec::new(),
            condition_groups_with_config: Vec::new(),
        }
    }

    /// 添加WHERE条件
    pub fn where_condition(mut self, condition: QueryConditionWithConfig) -> Self {
        self.conditions.push(condition);
        self
    }

    /// 添加多个WHERE条件
    pub fn where_conditions(mut self, conditions: &[QueryConditionWithConfig]) -> Self {
        self.conditions.extend_from_slice(conditions);
        self
    }

    /// 添加条件组合
    pub fn where_condition_groups(mut self, groups: &[QueryConditionGroup]) -> Self {
        self.condition_groups.extend_from_slice(groups);
        self
    }

    /// 添加条件组合(完整版)
    pub fn where_condition_groups_with_config(mut self, groups: &[QueryConditionGroupWithConfig]) -> Self {
        self.condition_groups_with_config.extend_from_slice(groups);
        self
    }

    /// 构建MongoDB查询文档
    pub fn build(self, table: &str, alias: &str) -> QuickDbResult<Document> {
        debug!(
            "[MongoDB] 开始构建查询文档,条件数量: {},表: {},别名: {}",
            self.conditions.len(),
            table,
            alias
        );
        let mut query_doc = Document::new();

        // 优先使用条件组合(完整版)
        if !self.condition_groups_with_config.is_empty() {
            let groups_doc = self.build_condition_groups_with_config_document(table, alias)?;
            if !groups_doc.is_empty() {
                query_doc.extend(groups_doc);
            }
        } else if !self.condition_groups.is_empty() {
            let groups_doc = self.build_condition_groups_document(table, alias)?;
            if !groups_doc.is_empty() {
                query_doc.extend(groups_doc);
            }
        } else if !self.conditions.is_empty() {
            let conditions_doc = self.build_conditions_document(table, alias)?;
            if !conditions_doc.is_empty() {
                query_doc.extend(conditions_doc);
            }
        }

        debug!("[MongoDB] 完成查询文档构建: {:?}", query_doc);
        Ok(query_doc)
    }

    /// 构建条件文档
    fn build_conditions_document(&self, table: &str, alias: &str) -> QuickDbResult<Document> {
        let mut query_doc = Document::new();

        for condition in &self.conditions {
            let condition_doc = self.build_single_condition_document(table, alias, condition)?;

            if !condition_doc.is_empty() {
                query_doc.extend(condition_doc);
            }
        }

        Ok(query_doc)
    }

    /// 构建条件组合文档
    fn build_condition_groups_document(&self, table: &str, alias: &str) -> QuickDbResult<Document> {
        let mut group_docs = Vec::new();

        for group in &self.condition_groups {
            let group_doc = self.build_single_condition_group_document(table, alias, group)?;
            if !group_doc.is_empty() {
                group_docs.push(group_doc);
            }
        }

        if group_docs.len() == 1 {
            Ok(group_docs.into_iter().next().unwrap())
        } else {
            Ok(doc! { "$and": group_docs })
        }
    }

    /// 构建单个条件组合的文档
    fn build_single_condition_group_document(
        &self,
        table: &str,
        alias: &str,
        group: &QueryConditionGroup,
    ) -> QuickDbResult<Document> {
        match group {
            QueryConditionGroup::Single(condition) => {
                // 将简化版转换为完整版
                let condition_with_config = QueryConditionWithConfig {
                    field: condition.field.clone(),
                    operator: condition.operator.clone(),
                    value: condition.value.clone(),
                    case_insensitive: false,
                };
                self.build_single_condition_document(table, alias, &condition_with_config)
            }
            QueryConditionGroup::Group {
                operator,
                conditions,
            } => {
                if conditions.is_empty() {
                    return Ok(Document::new());
                }

                let mut condition_docs = Vec::new();
                for condition in conditions {
                    let doc =
                        self.build_single_condition_group_document(table, alias, condition)?;
                    if !doc.is_empty() {
                        condition_docs.push(doc);
                    }
                }

                if condition_docs.len() == 1 {
                    Ok(condition_docs.into_iter().next().unwrap())
                } else {
                    let operator_key = match operator {
                        LogicalOperator::And => "$and",
                        LogicalOperator::Or => "$or",
                    };
                    Ok(doc! { operator_key: condition_docs })
                }
            }
        }
    }

    /// 构建条件组合文档(完整版)
    fn build_condition_groups_with_config_document(&self, table: &str, alias: &str) -> QuickDbResult<Document> {
        let mut group_docs = Vec::new();

        for group in &self.condition_groups_with_config {
            let group_doc = self.build_single_condition_group_with_config_document(table, alias, group)?;
            if !group_doc.is_empty() {
                group_docs.push(group_doc);
            }
        }

        if group_docs.len() == 1 {
            Ok(group_docs.into_iter().next().unwrap())
        } else {
            Ok(doc! { "$and": group_docs })
        }
    }

    /// 构建单个条件组合的文档(完整版)
    fn build_single_condition_group_with_config_document(
        &self,
        table: &str,
        alias: &str,
        group: &QueryConditionGroupWithConfig,
    ) -> QuickDbResult<Document> {
        match group {
            QueryConditionGroupWithConfig::Single(condition) => {
                self.build_single_condition_document(table, alias, condition)
            }
            QueryConditionGroupWithConfig::GroupWithConfig {
                operator,
                conditions,
            } => {
                if conditions.is_empty() {
                    return Ok(Document::new());
                }

                let mut condition_docs = Vec::new();
                for condition in conditions {
                    let doc =
                        self.build_single_condition_group_with_config_document(table, alias, condition)?;
                    if !doc.is_empty() {
                        condition_docs.push(doc);
                    }
                }

                if condition_docs.len() == 1 {
                    Ok(condition_docs.into_iter().next().unwrap())
                } else {
                    let operator_key = match operator {
                        LogicalOperator::And => "$and",
                        LogicalOperator::Or => "$or",
                    };
                    Ok(doc! { operator_key: condition_docs })
                }
            }
        }
    }

    /// 构建单个条件的文档
    fn build_single_condition_document(
        &self,
        table: &str,
        alias: &str,
        condition: &QueryConditionWithConfig,
    ) -> QuickDbResult<Document> {
        let field_name = map_field_name(&condition.field);

        // 检查字段类型,如果是 UUID 类型且传入的是字符串,保持为字符串查询
        // 这是因为 MongoDB/MySQL/SQLite 存储 UUID 为字符串,只有 PostgreSQL 使用原生 UUID 类型
        let field_type = get_field_type(table, alias, &condition.field);
        let is_uuid_field = field_type.as_ref().map(|ft| matches!(ft, crate::model::FieldType::Uuid)).unwrap_or(false);

        debug!("[MongoDB] 字段 '{}' (映射为 '{}') 类型: {:?}, is_uuid: {}",
            condition.field, field_name, field_type.as_ref(), is_uuid_field);

        // 如果是 UUID 字段但传入的是字符串,直接作为字符串处理
        let bson_value = if is_uuid_field {
            if let DataValue::String(ref s) = condition.value {
                // UUID 字段在非 PostgreSQL 数据库中存储为字符串,直接使用字符串值
                debug!("[MongoDB] UUID字段 '{}' 使用字符串查询: {}", field_name, s);
                Bson::String(s.clone())
            } else {
                self.data_value_to_bson(&condition.value)
            }
        } else {
            self.data_value_to_bson(&condition.value)
        };

        debug!(
            "[MongoDB] 处理条件: {} (原始: {}) {:?} {:?}",
            field_name, condition.field, condition.operator, bson_value
        );

        let condition_doc = match condition.operator {
            QueryOperator::Eq => {
                // 处理大小写不敏感的等于操作
                if condition.case_insensitive {
                    match &bson_value {
                        Bson::String(s) => {
                            // 使用正则表达式实现大小写不敏感匹配
                            doc! { field_name: doc! { "$regex": format!("^{}$", &regex::escape(s)), "$options": "i" } }
                        }
                        _ => {
                            // 非字符串类型,使用正常的等于匹配
                            doc! { field_name: bson_value }
                        }
                    }
                } else {
                    doc! { field_name: bson_value }
                }
            }
            QueryOperator::Ne => doc! { field_name: doc! { "$ne": bson_value } },
            QueryOperator::Gt => doc! { field_name: doc! { "$gt": bson_value } },
            QueryOperator::Gte => doc! { field_name: doc! { "$gte": bson_value } },
            QueryOperator::Lt => doc! { field_name: doc! { "$lt": bson_value } },
            QueryOperator::Lte => doc! { field_name: doc! { "$lte": bson_value } },
            QueryOperator::Contains => {
                self.build_contains_condition(field_name, table, alias, bson_value)?
            }
            QueryOperator::JsonContains => {
                // MongoDB JSON字段包含查询 - 简单平铺实现
                match bson_value {
                    Bson::String(s) => {
                        // 如果输入是JSON字符串,解析它并直接平铺为嵌套查询
                        let json_value: serde_json::Value =
                            serde_json::from_str(&s).map_err(|e| {
                                QuickDbError::ValidationError {
                                    field: condition.field.clone(),
                                    message: format!("无效的JSON格式: {}", e),
                                }
                            })?;

                        // 直接平铺JSON对象为MongoDB点标记法
                        self.flatten_json_to_query(field_name, &json_value)
                    }
                    _ => {
                        // 对于其他BSON类型,直接进行查询
                        doc! { field_name: bson_value }
                    }
                }
            }
            QueryOperator::StartsWith => {
                if let Bson::String(s) = bson_value {
                    doc! { field_name: doc! { "$regex": format!("^{}", &s), "$options": "i" } }
                } else {
                    return Err(QuickDbError::ValidationError {
                        field: condition.field.clone(),
                        message: "StartsWith操作符只支持字符串类型".to_string(),
                    });
                }
            }
            QueryOperator::EndsWith => {
                if let Bson::String(s) = bson_value {
                    doc! { field_name: doc! { "$regex": format!("{}$", &s), "$options": "i" } }
                } else {
                    return Err(QuickDbError::ValidationError {
                        field: condition.field.clone(),
                        message: "EndsWith操作符只支持字符串类型".to_string(),
                    });
                }
            }
            QueryOperator::In => {
                // 验证Array字段IN操作的数据类型
                if let Bson::Array(arr) = &bson_value {
                    // 检查字段类型,如果是Array字段,验证数组中元素的数据类型
                    if let Some(field_type) = get_field_type(table, alias, field_name) {
                        if matches!(field_type, crate::model::FieldType::Array { .. }) {
                            // Array字段:验证数组中元素的数据类型
                            for bson_elem in arr {
                                match bson_elem {
                                    Bson::String(_)
                                    | Bson::Int32(_)
                                    | Bson::Int64(_)
                                    | Bson::Double(_) => {
                                        // 支持的类型:String, Int, Float
                                    }
                                    Bson::ObjectId(_) => {
                                        // Uuid类型映射到ObjectId,支持
                                    }
                                    _ => {
                                        return Err(QuickDbError::ValidationError {
                                            field: field_name.to_string(),
                                            message: format!(
                                                "Array字段的IN操作只支持String、Int、Float、Uuid类型,不支持: {:?}",
                                                bson_elem
                                            ),
                                        });
                                    }
                                }
                            }
                        }
                    }
                    doc! { field_name: doc! { "$in": arr.clone() } }
                } else {
                    doc! { field_name: doc! { "$in": [bson_value] } }
                }
            }
            QueryOperator::NotIn => {
                // 验证Array字段NOT IN操作的数据类型
                if let Bson::Array(arr) = &bson_value {
                    // 检查字段类型,如果是Array字段,验证数组中元素的数据类型
                    if let Some(field_type) = get_field_type(table, alias, field_name) {
                        if matches!(field_type, crate::model::FieldType::Array { .. }) {
                            // Array字段:验证数组中元素的数据类型
                            for bson_elem in arr {
                                match bson_elem {
                                    Bson::String(_)
                                    | Bson::Int32(_)
                                    | Bson::Int64(_)
                                    | Bson::Double(_) => {
                                        // 支持的类型:String, Int, Float
                                    }
                                    Bson::ObjectId(_) => {
                                        // Uuid类型映射到ObjectId,支持
                                    }
                                    _ => {
                                        return Err(QuickDbError::ValidationError {
                                            field: field_name.to_string(),
                                            message: format!(
                                                "Array字段的NOT IN操作只支持String、Int、Float、Uuid类型,不支持: {:?}",
                                                bson_elem
                                            ),
                                        });
                                    }
                                }
                            }
                        }
                    }
                    doc! { field_name: doc! { "$nin": arr.clone() } }
                } else {
                    doc! { field_name: doc! { "$nin": [bson_value] } }
                }
            }
            QueryOperator::Regex => {
                if let Bson::String(s) = bson_value {
                    doc! { field_name: doc! { "$regex": s, "$options": "i" } }
                } else {
                    return Err(QuickDbError::ValidationError {
                        field: condition.field.clone(),
                        message: "Regex操作符只支持字符串类型".to_string(),
                    });
                }
            }
            QueryOperator::Exists => {
                doc! { field_name: doc! { "$exists": true } }
            }
            QueryOperator::IsNull => {
                doc! { field_name: doc! { "$eq": null } }
            }
            QueryOperator::IsNotNull => {
                doc! { field_name: doc! { "$ne": null } }
            }
        };

        Ok(condition_doc)
    }

    /// 构建Contains条件,基于字段元数据
    fn build_contains_condition(
        &self,
        field_name: &str,
        table: &str,
        alias: &str,
        bson_value: Bson,
    ) -> QuickDbResult<Document> {
        // 获取字段类型
        let field_type = get_field_type(table, alias, field_name).ok_or_else(|| {
            QuickDbError::ValidationError {
                field: field_name.to_string(),
                message: format!(
                    "无法确定字段 '{}' 的类型,请确保已正确注册模型元数据 (alias={})",
                    field_name, alias
                ),
            }
        })?;

        debug!(
            "[MongoDB] Contains操作 - 字段类型: {:?}, 值: {:?}",
            field_type, bson_value
        );

        match field_type {
            crate::model::FieldType::String { .. } => {
                // 字符串字段使用正则表达式匹配
                if let Bson::String(s) = bson_value {
                    let regex_doc = doc! { "$regex": format!(".*{}.*", &s), "$options": "i" };
                    debug!(
                        "[MongoDB] Contains操作(字符串): {} = {:?}",
                        field_name, regex_doc
                    );
                    Ok(doc! { field_name: regex_doc })
                } else {
                    return Err(QuickDbError::ValidationError {
                        field: field_name.to_string(),
                        message: "字符串字段的Contains操作符只支持字符串值".to_string(),
                    });
                }
            }
            crate::model::FieldType::Array { .. } => {
                // Array字段使用$in操作符
                debug!(
                    "[MongoDB] Contains操作(Array): {} = {:?}",
                    field_name, bson_value
                );
                Ok(doc! { field_name: doc! { "$in": [bson_value] } })
            }
            crate::model::FieldType::Json => {
                // JSON字段根据类型处理
                match bson_value {
                    Bson::String(s) => {
                        let regex_doc = doc! { "$regex": format!(".*{}.*", &s), "$options": "i" };
                        Ok(doc! { field_name: regex_doc })
                    }
                    _ => Ok(doc! { field_name: doc! { "$in": [bson_value] } }),
                }
            }
            _ => {
                return Err(QuickDbError::ValidationError {
                    field: field_name.to_string(),
                    message: "Contains操作符只支持字符串、Array和JSON字段".to_string(),
                });
            }
        }
    }

    /// 将DataValue转换为BSON值
    fn data_value_to_bson(&self, value: &DataValue) -> Bson {
        match value {
            DataValue::String(s) => Bson::String(s.clone()),
            DataValue::Int(i) => Bson::Int64(*i),
            DataValue::UInt(u) => {
                // MongoDB/BSON 不支持无符号整数,转换为 i64
                if *u <= i64::MAX as u64 {
                    Bson::Int64(*u as i64)
                } else {
                    // 如果超过 i64 范围,使用字符串存储
                    Bson::String(u.to_string())
                }
            }
            DataValue::Float(f) => Bson::Double(*f),
            DataValue::Bool(b) => Bson::Boolean(*b),
            DataValue::DateTime(dt) => {
                // 将DateTime<FixedOffset>转换为DateTime<Utc>,然后转换为MongoDB BSON DateTime
                let utc_dt = chrono::DateTime::<chrono::Utc>::from(*dt);
                Bson::DateTime(mongodb::bson::DateTime::from_system_time(utc_dt.into()))
            }
            DataValue::DateTimeUTC(dt) => {
                // DateTime<Utc>直接转换为MongoDB BSON DateTime
                Bson::DateTime(mongodb::bson::DateTime::from_system_time(dt.clone().into()))
            }
            DataValue::Uuid(uuid) => Bson::String(uuid.to_string()),
            DataValue::Json(json) => {
                // 尝试将JSON转换为BSON文档
                if let Ok(doc) = mongodb::bson::to_document(json) {
                    Bson::Document(doc)
                } else {
                    Bson::String(json.to_string())
                }
            }
            DataValue::Array(arr) => {
                let bson_array: Vec<Bson> =
                    arr.iter().map(|v| self.data_value_to_bson(v)).collect();
                Bson::Array(bson_array)
            }
            DataValue::Object(obj) => {
                let mut bson_doc = Document::new();
                for (key, value) in obj {
                    let bson_value = self.data_value_to_bson(value);
                    bson_doc.insert(key, bson_value);
                }
                Bson::Document(bson_doc)
            }
            DataValue::Null => Bson::Null,
            DataValue::Bytes(bytes) => Bson::Binary(mongodb::bson::Binary {
                bytes: bytes.clone(),
                subtype: mongodb::bson::spec::BinarySubtype::Generic,
            }),
        }
    }

    /// 将JSON对象平铺为MongoDB点标记法查询
    /// 简单实现:只处理键值对,不处理数组等复杂结构
    fn flatten_json_to_query(&self, field_name: &str, json_value: &serde_json::Value) -> Document {
        match json_value {
            serde_json::Value::Object(map) => {
                if map.is_empty() {
                    return Document::new();
                }

                let mut conditions = Vec::new();

                for (key, value) in map {
                    let dot_path = format!("{}.{}", field_name, key);
                    if let serde_json::Value::Object(_) = value {
                        // 嵌套对象,递归平铺
                        let nested_condition = self.flatten_json_to_query(&dot_path, value);
                        // 将嵌套条件合并到当前条件
                        for (k, v) in nested_condition {
                            conditions.push(doc! { k: v });
                        }
                    } else {
                        // 基本值,直接构建查询条件
                        if let Ok(bson_value) = mongodb::bson::to_bson(value) {
                            conditions.push(doc! { dot_path: bson_value });
                        }
                    }
                }

                // 多个条件使用$and组合
                if conditions.len() == 1 {
                    conditions.into_iter().next().unwrap()
                } else {
                    doc! { "$and": conditions }
                }
            }
            _ => {
                // 非对象类型,返回空文档
                Document::new()
            }
        }
    }
}

/// 构建MongoDB查询文档的便捷函数
pub fn build_query_document(
    table: &str,
    alias: &str,
    conditions: &[QueryConditionWithConfig],
) -> QuickDbResult<Document> {
    MongoQueryBuilder::new()
        .where_conditions(conditions)
        .build(table, alias)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::QueryConditionWithConfig;

    #[test]
    fn test_mongo_query_builder_basic() {
        // 这里可以添加单元测试
    }

    #[test]
    fn test_field_name_mapping() {
        // 测试id字段映射到_id
        assert_eq!(map_field_name("id"), "_id");
        // 测试其他字段保持不变
        assert_eq!(map_field_name("name"), "name");
        assert_eq!(map_field_name("email"), "email");
        assert_eq!(map_field_name("_id"), "_id");
    }

    #[test]
    fn test_id_field_in_query_condition() {
        let conditions = vec![QueryCondition {
            field: "id".to_string(),
            operator: crate::types::QueryOperator::Eq,
            value: crate::types::DataValue::String("test_id".to_string()),
        }];

        let result = build_query_document("users", "test", &conditions);
        assert!(result.is_ok());

        let doc = result.unwrap();
        // 验证生成的查询文档中包含_id字段而不是id字段
        assert!(doc.contains_key("_id"));
        assert!(!doc.contains_key("id"));
    }
}