1use crate::error::{QuickDbError, QuickDbResult};
7use crate::types::*;
8use crate::odm::{self, OdmOperations};
9use async_trait::async_trait;
10use serde::{Deserialize, Serialize};
11use serde_json::Value as JsonValue;
12use std::collections::HashMap;
13use std::marker::PhantomData;
14use rat_logger::{debug, error, info, warn};
15use base64;
16
17pub trait ToDataValue {
20 fn to_data_value(&self) -> DataValue;
21}
22
23impl ToDataValue for String {
25 fn to_data_value(&self) -> DataValue {
26 DataValue::String(self.clone())
27 }
28}
29
30impl ToDataValue for &str {
31 fn to_data_value(&self) -> DataValue {
32 DataValue::String(self.to_string())
33 }
34}
35
36impl ToDataValue for i32 {
37 fn to_data_value(&self) -> DataValue {
38 DataValue::Int(*self as i64)
39 }
40}
41
42impl ToDataValue for i64 {
43 fn to_data_value(&self) -> DataValue {
44 DataValue::Int(*self)
45 }
46}
47
48impl ToDataValue for f32 {
49 fn to_data_value(&self) -> DataValue {
50 DataValue::Float(*self as f64)
51 }
52}
53
54impl ToDataValue for f64 {
55 fn to_data_value(&self) -> DataValue {
56 DataValue::Float(*self)
57 }
58}
59
60impl ToDataValue for bool {
61 fn to_data_value(&self) -> DataValue {
62 DataValue::Bool(*self)
63 }
64}
65
66impl ToDataValue for Vec<String> {
68 fn to_data_value(&self) -> DataValue {
69 let data_values: Vec<DataValue> = self.iter()
71 .map(|s| DataValue::String(s.clone()))
72 .collect();
73 DataValue::Array(data_values)
74 }
75}
76
77impl ToDataValue for Vec<i32> {
79 fn to_data_value(&self) -> DataValue {
80 let data_values: Vec<DataValue> = self.iter()
82 .map(|&i| DataValue::Int(i as i64))
83 .collect();
84 DataValue::Array(data_values)
85 }
86}
87
88impl ToDataValue for Vec<i64> {
90 fn to_data_value(&self) -> DataValue {
91 let data_values: Vec<DataValue> = self.iter()
93 .map(|&i| DataValue::Int(i))
94 .collect();
95 DataValue::Array(data_values)
96 }
97}
98
99impl ToDataValue for Vec<f64> {
101 fn to_data_value(&self) -> DataValue {
102 let data_values: Vec<DataValue> = self.iter()
104 .map(|&f| DataValue::Float(f))
105 .collect();
106 DataValue::Array(data_values)
107 }
108}
109
110impl ToDataValue for Vec<bool> {
112 fn to_data_value(&self) -> DataValue {
113 let data_values: Vec<DataValue> = self.iter()
115 .map(|&b| DataValue::Bool(b))
116 .collect();
117 DataValue::Array(data_values)
118 }
119}
120
121impl ToDataValue for HashMap<String, DataValue> {
123 fn to_data_value(&self) -> DataValue {
124 DataValue::Object(self.clone())
126 }
127}
128
129impl ToDataValue for serde_json::Value {
133 fn to_data_value(&self) -> DataValue {
134 DataValue::Json(self.clone())
135 }
136}
137
138impl<T> ToDataValue for Option<T>
139where
140 T: ToDataValue,
141{
142 fn to_data_value(&self) -> DataValue {
143 match self {
144 Some(v) => v.to_data_value(),
145 None => DataValue::Null,
146 }
147 }
148}
149
150#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
152pub enum FieldType {
153 String {
155 max_length: Option<usize>,
156 min_length: Option<usize>,
157 regex: Option<String>,
158 },
159 Integer {
161 min_value: Option<i64>,
162 max_value: Option<i64>,
163 },
164 BigInteger,
166 Float {
168 min_value: Option<f64>,
169 max_value: Option<f64>,
170 },
171 Double,
173 Text,
175 Boolean,
177 DateTime,
179 Date,
181 Time,
183 Uuid,
185 Json,
187 Binary,
189 Decimal {
191 precision: u8,
192 scale: u8,
193 },
194 Array {
196 item_type: Box<FieldType>,
197 max_items: Option<usize>,
198 min_items: Option<usize>,
199 },
200 Object {
202 fields: HashMap<String, FieldDefinition>,
203 },
204 Reference {
206 target_collection: String,
207 },
208}
209
210#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
212pub struct FieldDefinition {
213 pub field_type: FieldType,
215 pub required: bool,
217 pub default: Option<DataValue>,
219 pub unique: bool,
221 pub indexed: bool,
223 pub description: Option<String>,
225 pub validator: Option<String>,
227}
228
229impl FieldDefinition {
230 pub fn new(field_type: FieldType) -> Self {
232 Self {
233 field_type,
234 required: false,
235 default: None,
236 unique: false,
237 indexed: false,
238 description: None,
239 validator: None,
240 }
241 }
242
243 pub fn required(mut self) -> Self {
245 self.required = true;
246 self
247 }
248
249 pub fn default_value(mut self, value: DataValue) -> Self {
251 self.default = Some(value);
252 self
253 }
254
255 pub fn unique(mut self) -> Self {
257 self.unique = true;
258 self
259 }
260
261 pub fn indexed(mut self) -> Self {
263 self.indexed = true;
264 self
265 }
266
267 pub fn description(mut self, desc: &str) -> Self {
269 self.description = Some(desc.to_string());
270 self
271 }
272
273 pub fn validator(mut self, validator_name: &str) -> Self {
275 self.validator = Some(validator_name.to_string());
276 self
277 }
278
279 pub fn validate(&self, value: &DataValue) -> QuickDbResult<()> {
281 self.validate_with_field_name(value, "unknown")
282 }
283
284 pub fn validate_with_field_name(&self, value: &DataValue, field_name: &str) -> QuickDbResult<()> {
285 if self.required && matches!(value, DataValue::Null) {
287 return Err(QuickDbError::ValidationError { field: field_name.to_string(), message: "必填字段不能为空".to_string() });
288 }
289
290 if matches!(value, DataValue::Null) {
292 return Ok(());
293 }
294
295 match &self.field_type {
297 FieldType::String { max_length, min_length, regex } => {
298 if let DataValue::String(s) = value {
299 if let Some(max_len) = max_length {
300 if s.len() > *max_len {
301 return Err(QuickDbError::ValidationError {
302 field: "string_length".to_string(),
303 message: format!("字符串长度不能超过{}", max_len)
304 });
305 }
306 }
307 if let Some(min_len) = min_length {
308 if s.len() < *min_len {
309 return Err(QuickDbError::ValidationError {
310 field: "string_length".to_string(),
311 message: format!("字符串长度不能少于{}", min_len)
312 });
313 }
314 }
315 if let Some(pattern) = regex {
316 let regex = regex::Regex::new(pattern)
317 .map_err(|e| QuickDbError::ValidationError {
318 field: "regex".to_string(),
319 message: format!("正则表达式无效: {}", e)
320 })?;
321 if !regex.is_match(s) {
322 return Err(QuickDbError::ValidationError {
323 field: "regex_match".to_string(),
324 message: "字符串不匹配正则表达式".to_string()
325 });
326 }
327 }
328 } else {
329 return Err(QuickDbError::ValidationError {
330 field: "type_mismatch".to_string(),
331 message: "字段类型不匹配,期望字符串类型".to_string()
332 });
333 }
334 }
335 FieldType::Integer { min_value, max_value } => {
336 if let DataValue::Int(i) = value {
337 if let Some(min_val) = min_value {
338 if *i < *min_val {
339 return Err(QuickDbError::ValidationError {
340 field: "integer_range".to_string(),
341 message: format!("整数值不能小于{}", min_val)
342 });
343 }
344 }
345 if let Some(max_val) = max_value {
346 if *i > *max_val {
347 return Err(QuickDbError::ValidationError {
348 field: "integer_range".to_string(),
349 message: format!("整数值不能大于{}", max_val)
350 });
351 }
352 }
353 } else {
354 return Err(QuickDbError::ValidationError {
355 field: "type_mismatch".to_string(),
356 message: "字段类型不匹配,期望整数类型".to_string()
357 });
358 }
359 }
360 FieldType::Float { min_value, max_value } => {
361 if let DataValue::Float(f) = value {
362 if let Some(min_val) = min_value {
363 if *f < *min_val {
364 return Err(QuickDbError::ValidationError {
365 field: "float_range".to_string(),
366 message: format!("浮点数值不能小于{}", min_val)
367 });
368 }
369 }
370 if let Some(max_val) = max_value {
371 if *f > *max_val {
372 return Err(QuickDbError::ValidationError {
373 field: "float_range".to_string(),
374 message: format!("浮点数值不能大于{}", max_val)
375 });
376 }
377 }
378 } else {
379 return Err(QuickDbError::ValidationError {
380 field: "type_mismatch".to_string(),
381 message: "字段类型不匹配,期望浮点数类型".to_string()
382 });
383 }
384 }
385 FieldType::Boolean => {
386 if !matches!(value, DataValue::Bool(_)) {
387 return Err(QuickDbError::ValidationError {
388 field: "type_mismatch".to_string(),
389 message: "字段类型不匹配,期望布尔类型".to_string()
390 });
391 }
392 }
393 FieldType::DateTime => {
394 if !matches!(value, DataValue::DateTime(_)) {
395 return Err(QuickDbError::ValidationError {
396 field: "type_mismatch".to_string(),
397 message: "字段类型不匹配,期望日期时间类型".to_string()
398 });
399 }
400 }
401 FieldType::Uuid => {
402 if let DataValue::String(s) = value {
403 if uuid::Uuid::parse_str(s).is_err() {
404 return Err(QuickDbError::ValidationError {
405 field: "uuid_format".to_string(),
406 message: "无效的UUID格式".to_string()
407 });
408 }
409 } else {
410 return Err(QuickDbError::ValidationError {
411 field: "type_mismatch".to_string(),
412 message: "字段类型不匹配,期望UUID字符串".to_string()
413 });
414 }
415 }
416 FieldType::Json => {
417 }
419 FieldType::Array { item_type, max_items, min_items } => {
420 match value {
421 DataValue::Array(arr) => {
422 if let Some(max_items) = max_items {
424 if arr.len() > *max_items {
425 return Err(QuickDbError::ValidationError {
426 field: "array_size".to_string(),
427 message: format!("数组元素数量不能超过{}", max_items)
428 });
429 }
430 }
431 if let Some(min_items) = min_items {
432 if arr.len() < *min_items {
433 return Err(QuickDbError::ValidationError {
434 field: "array_size".to_string(),
435 message: format!("数组元素数量不能少于{}", min_items)
436 });
437 }
438 }
439 let item_field = FieldDefinition::new((**item_type).clone());
441 for item in arr {
442 item_field.validate(item)?;
443 }
444 },
445 DataValue::String(json_str) => {
446 if let Ok(json_value) = serde_json::from_str::<serde_json::Value>(json_str) {
448 if let Some(arr) = json_value.as_array() {
449 if let Some(max_items) = max_items {
450 if arr.len() > *max_items {
451 return Err(QuickDbError::ValidationError {
452 field: "array_size".to_string(),
453 message: format!("数组元素数量不能超过{}", max_items)
454 });
455 }
456 }
457 if let Some(min_items) = min_items {
458 if arr.len() < *min_items {
459 return Err(QuickDbError::ValidationError {
460 field: "array_size".to_string(),
461 message: format!("数组元素数量不能少于{}", min_items)
462 });
463 }
464 }
465 let item_field = FieldDefinition::new((**item_type).clone());
467 for item_json in arr {
468 let item_data_value = DataValue::from_json(item_json.clone());
469 item_field.validate(&item_data_value)?;
470 }
471 } else {
472 return Err(QuickDbError::ValidationError {
473 field: "type_mismatch".to_string(),
474 message: "JSON字符串不是有效的数组格式".to_string()
475 });
476 }
477 } else {
478 return Err(QuickDbError::ValidationError {
479 field: "type_mismatch".to_string(),
480 message: "无法解析JSON字符串".to_string()
481 });
482 }
483 },
484 _ => {
485 return Err(QuickDbError::ValidationError {
486 field: "type_mismatch".to_string(),
487 message: "字段类型不匹配,期望数组类型或JSON字符串".to_string()
488 });
489 }
490 }
491 }
492 FieldType::Object { fields } => {
493 if let DataValue::Object(obj) = value {
494 for (field_name, field_def) in fields {
496 let field_value = obj.get(field_name).unwrap_or(&DataValue::Null);
497 field_def.validate(field_value)?;
498 }
499 } else {
500 return Err(QuickDbError::ValidationError {
501 field: "type_mismatch".to_string(),
502 message: "字段类型不匹配,期望对象类型".to_string()
503 });
504 }
505 }
506 FieldType::Reference { target_collection: _ } => {
507 if !matches!(value, DataValue::String(_)) {
509 return Err(QuickDbError::ValidationError {
510 field: "reference_type".to_string(),
511 message: "引用字段必须是字符串ID".to_string()
512 });
513 }
514 }
515 FieldType::BigInteger => {
516 if !matches!(value, DataValue::Int(_)) {
517 return Err(QuickDbError::ValidationError {
518 field: "type_mismatch".to_string(),
519 message: "字段类型不匹配,期望大整数类型".to_string()
520 });
521 }
522 }
523 FieldType::Double => {
524 if !matches!(value, DataValue::Float(_)) {
525 return Err(QuickDbError::ValidationError {
526 field: "type_mismatch".to_string(),
527 message: "字段类型不匹配,期望双精度浮点数类型".to_string()
528 });
529 }
530 }
531 FieldType::Text => {
532 if !matches!(value, DataValue::String(_)) {
533 return Err(QuickDbError::ValidationError {
534 field: "type_mismatch".to_string(),
535 message: "字段类型不匹配,期望文本类型".to_string()
536 });
537 }
538 }
539 FieldType::Date => {
540 if !matches!(value, DataValue::DateTime(_)) {
541 return Err(QuickDbError::ValidationError {
542 field: "type_mismatch".to_string(),
543 message: "字段类型不匹配,期望日期类型".to_string()
544 });
545 }
546 }
547 FieldType::Time => {
548 if !matches!(value, DataValue::DateTime(_)) {
549 return Err(QuickDbError::ValidationError {
550 field: "type_mismatch".to_string(),
551 message: "字段类型不匹配,期望时间类型".to_string()
552 });
553 }
554 }
555 FieldType::Binary => {
556 if !matches!(value, DataValue::String(_)) {
557 return Err(QuickDbError::ValidationError {
558 field: "type_mismatch".to_string(),
559 message: "字段类型不匹配,期望二进制数据(Base64字符串)".to_string()
560 });
561 }
562 }
563 FieldType::Decimal { precision: _, scale: _ } => {
564 if !matches!(value, DataValue::Float(_)) {
565 return Err(QuickDbError::ValidationError {
566 field: "type_mismatch".to_string(),
567 message: "字段类型不匹配,期望十进制数类型".to_string()
568 });
569 }
570 }
571 }
572
573 Ok(())
574 }
575}
576
577#[derive(Debug, Clone, Serialize, Deserialize)]
579pub struct ModelMeta {
580 pub collection_name: String,
582 pub database_alias: Option<String>,
584 pub fields: HashMap<String, FieldDefinition>,
586 pub indexes: Vec<IndexDefinition>,
588 pub description: Option<String>,
590}
591
592#[derive(Debug, Clone, Serialize, Deserialize)]
594pub struct IndexDefinition {
595 pub fields: Vec<String>,
597 pub unique: bool,
599 pub name: Option<String>,
601}
602
603pub trait Model: Serialize + for<'de> Deserialize<'de> + Send + Sync {
607 fn meta() -> ModelMeta;
609
610 fn collection_name() -> String {
612 Self::meta().collection_name
613 }
614
615 fn database_alias() -> Option<String> {
617 Self::meta().database_alias
618 }
619
620 fn validate(&self) -> QuickDbResult<()> {
622 let meta = Self::meta();
623 let data = self.to_data_map()?;
624
625 info!("🔍 验证数据映射: {:?}", data);
627
628 for (field_name, field_def) in &meta.fields {
629 let field_value = data.get(field_name).unwrap_or(&DataValue::Null);
630 info!("🔍 验证字段 {}: {:?}", field_name, field_value);
631 field_def.validate_with_field_name(field_value, field_name)?;
632 }
633
634 Ok(())
635 }
636
637 fn to_data_map_direct(&self) -> QuickDbResult<HashMap<String, DataValue>> {
640 warn!("使用默认的 JSON 序列化方式,建议重写 to_data_map_direct 方法以提高性能");
642 self.to_data_map_legacy()
643 }
644
645 fn to_data_map_legacy(&self) -> QuickDbResult<HashMap<String, DataValue>> {
648 let json_str = serde_json::to_string(self)
649 .map_err(|e| QuickDbError::SerializationError { message: format!("序列化失败: {}", e) })?;
650 info!("🔍 序列化后的JSON字符串: {}", json_str);
651
652 let json_value: JsonValue = serde_json::from_str(&json_str)
653 .map_err(|e| QuickDbError::SerializationError { message: format!("解析JSON失败: {}", e) })?;
654 info!("🔍 解析后的JsonValue: {:?}", json_value);
655
656 let mut data_map = HashMap::new();
657 if let JsonValue::Object(obj) = json_value {
658 for (key, value) in obj {
659 let data_value = DataValue::from_json(value.clone());
660 info!("🔍 字段 {} 转换: {:?} -> {:?}", key, value, data_value);
661 data_map.insert(key, data_value);
662 }
663 }
664
665 Ok(data_map)
666 }
667
668 fn to_data_map(&self) -> QuickDbResult<HashMap<String, DataValue>> {
670 self.to_data_map_direct()
671 }
672
673 fn from_data_map(data: HashMap<String, DataValue>) -> QuickDbResult<Self> {
675 let mut json_map = serde_json::Map::new();
677 for (key, value) in data {
678 let json_value = match value {
679 DataValue::Object(obj_map) => {
681 debug!("字段 {} 的Object类型将转换为JSON字符串", key);
683 let mut nested_map = serde_json::Map::new();
684 for (nested_key, nested_value) in obj_map {
685 nested_map.insert(nested_key, nested_value.to_json_value());
686 }
687 JsonValue::Object(nested_map)
688 },
689 DataValue::Array(arr) => {
690 debug!("转换数组字段,元素数量: {}", arr.len());
692 let json_array: Vec<JsonValue> = arr.iter()
693 .map(|item| {
694 let json_item = item.to_json_value();
695 debug!("数组元素: {:?} -> {}", item, json_item);
696 json_item
697 })
698 .collect();
699 let result = JsonValue::Array(json_array);
700 debug!("数组转换结果: {}", result);
701 result
702 },
703 DataValue::String(s) => {
704 if (s.starts_with('[') && s.ends_with(']')) || (s.starts_with('{') && s.ends_with('}')) {
706 match serde_json::from_str::<serde_json::Value>(&s) {
707 Ok(parsed) => parsed,
708 Err(_) => JsonValue::String(s),
709 }
710 } else {
711 JsonValue::String(s)
712 }
713 },
714 DataValue::Json(j) => {
715 j
717 },
718 DataValue::Bool(b) => JsonValue::Bool(b),
720 DataValue::Int(i) => JsonValue::Number(serde_json::Number::from(i)),
721 DataValue::Float(f) => {
722 serde_json::Number::from_f64(f)
723 .map(JsonValue::Number)
724 .unwrap_or(JsonValue::Null)
725 },
726 DataValue::Null => JsonValue::Null,
727 DataValue::Bytes(b) => {
728 JsonValue::String(base64::encode(&b))
730 },
731 DataValue::DateTime(dt) => JsonValue::String(dt.to_rfc3339()),
732 DataValue::Uuid(u) => JsonValue::String(u.to_string()),
733 };
734 json_map.insert(key, json_value);
735 }
736 let json_value = JsonValue::Object(json_map);
737
738 debug!("准备反序列化的JSON数据: {}", serde_json::to_string_pretty(&json_value).unwrap_or_else(|_| "无法序列化".to_string()));
739
740 match serde_json::from_value(json_value.clone()) {
742 Ok(model) => Ok(model),
743 Err(first_error) => {
744 debug!("直接反序列化失败,尝试兼容模式: {}", first_error);
745
746 debug!("反序列化错误: {}", first_error);
748
749 let mut fixed_map = serde_json::Map::new();
752 for (key, value) in json_value.as_object().unwrap() {
753 let fixed_value = match key.as_str() {
755 "tags" | "profile" => {
756 match value {
758 JsonValue::String(s) if s.starts_with('[') && s.ends_with(']') => {
759 if let Ok(parsed_array) = serde_json::from_str::<Vec<JsonValue>>(&s) {
761 JsonValue::Array(parsed_array)
762 } else {
763 value.clone()
764 }
765 },
766 _ => value.clone()
767 }
768 },
769 "is_active" | "is_featured" => {
770 match value {
772 JsonValue::Number(n) => {
773 if n.as_i64() == Some(1) {
774 JsonValue::Bool(true)
775 } else if n.as_i64() == Some(0) {
776 JsonValue::Bool(false)
777 } else {
778 value.clone()
779 }
780 },
781 _ => value.clone()
782 }
783 },
784 _ => value.clone()
785 };
786 fixed_map.insert(key.clone(), fixed_value);
787 }
788
789 let fixed_json = JsonValue::Object(fixed_map);
790 debug!("修复后的JSON数据: {}", serde_json::to_string_pretty(&fixed_json).unwrap_or_else(|_| "无法序列化".to_string()));
791
792 serde_json::from_value(fixed_json).map_err(|e| {
793 error!("修复后反序列化仍然失败: {}", e);
794 QuickDbError::SerializationError { message: format!("反序列化失败: {}", e) }
795 })
796 }
797 }
798 }
799}
800
801
802
803#[async_trait]
807pub trait ModelOperations<T: Model> {
808 async fn save(&self) -> QuickDbResult<String>;
810
811 async fn find_by_id(id: &str) -> QuickDbResult<Option<T>>;
813
814 async fn find(conditions: Vec<QueryCondition>, options: Option<QueryOptions>) -> QuickDbResult<Vec<T>>;
816
817 async fn update(&self, updates: HashMap<String, DataValue>) -> QuickDbResult<bool>;
819
820 async fn delete(&self) -> QuickDbResult<bool>;
822
823 async fn count(conditions: Vec<QueryCondition>) -> QuickDbResult<u64>;
825
826 async fn exists(conditions: Vec<QueryCondition>) -> QuickDbResult<bool>;
828}
829
830pub struct ModelManager<T: Model> {
834 _phantom: PhantomData<T>,
835}
836
837impl<T: Model> ModelManager<T> {
838 pub fn new() -> Self {
840 Self {
841 _phantom: PhantomData,
842 }
843 }
844}
845
846#[async_trait]
847impl<T: Model> ModelOperations<T> for ModelManager<T> {
848 async fn save(&self) -> QuickDbResult<String> {
849 Err(QuickDbError::ValidationError {
851 field: "save".to_string(),
852 message: "save方法需要在模型实例上调用".to_string()
853 })
854 }
855
856 async fn find_by_id(id: &str) -> QuickDbResult<Option<T>> {
857 let collection_name = T::collection_name();
858 let database_alias = T::database_alias();
859
860 debug!("根据ID查找模型: collection={}, id={}", collection_name, id);
861
862 let result = odm::find_by_id(
863 &collection_name,
864 id,
865 database_alias.as_deref(),
866 ).await?;
867
868 if let Some(data_value) = result {
869 match data_value {
871 DataValue::Object(data_map) => {
872 debug!("从数据库收到的数据: {:?}", data_map);
873 let model: T = match T::from_data_map(data_map.clone()) {
874 Ok(model) => model,
875 Err(e) => {
876 println!("❌ from_data_map失败: {}, 数据: {:?}", e, data_map);
877 return Err(e);
878 }
879 };
880 Ok(Some(model))
881 },
882 _ => {
883 debug!("收到非Object格式数据: {:?}", data_value);
885 let model: T = data_value.deserialize_to()?;
886 Ok(Some(model))
887 }
888 }
889 } else {
890 Ok(None)
891 }
892 }
893
894 async fn find(conditions: Vec<QueryCondition>, options: Option<QueryOptions>) -> QuickDbResult<Vec<T>> {
895 let collection_name = T::collection_name();
896 let database_alias = T::database_alias();
897
898 debug!("查找模型: collection={}", collection_name);
899
900 let result = odm::find(
901 &collection_name,
902 conditions,
903 options,
904 database_alias.as_deref(),
905 ).await?;
906
907 let mut models = Vec::new();
909 for data_value in result {
910 match data_value {
912 DataValue::Object(data_map) => {
913 debug!("查询收到的数据: {:?}", data_map);
914 let model: T = match T::from_data_map(data_map.clone()) {
915 Ok(model) => model,
916 Err(e) => {
917 println!("❌ 查询from_data_map失败: {}, 数据: {:?}", e, data_map);
918 continue;
919 }
920 };
921 models.push(model);
922 },
923 _ => {
924 debug!("查询收到非Object格式数据: {:?}", data_value);
926 let model: T = data_value.deserialize_to()?;
927 models.push(model);
928 }
929 }
930 }
931 Ok(models)
932 }
933
934 async fn update(&self, _updates: HashMap<String, DataValue>) -> QuickDbResult<bool> {
935 Err(QuickDbError::ValidationError {
937 field: "update".to_string(),
938 message: "update方法需要在模型实例上调用".to_string()
939 })
940 }
941
942 async fn delete(&self) -> QuickDbResult<bool> {
943 Err(QuickDbError::ValidationError {
945 field: "delete".to_string(),
946 message: "delete方法需要在模型实例上调用".to_string()
947 })
948 }
949
950 async fn count(conditions: Vec<QueryCondition>) -> QuickDbResult<u64> {
951 let collection_name = T::collection_name();
952 let database_alias = T::database_alias();
953
954 debug!("统计模型数量: collection={}", collection_name);
955
956 odm::count(
957 &collection_name,
958 conditions,
959 database_alias.as_deref(),
960 ).await
961 }
962
963 async fn exists(conditions: Vec<QueryCondition>) -> QuickDbResult<bool> {
964 let collection_name = T::collection_name();
965 let database_alias = T::database_alias();
966
967 debug!("检查模型是否存在: collection={}", collection_name);
968
969 odm::exists(
970 &collection_name,
971 conditions,
972 database_alias.as_deref(),
973 ).await
974 }
975}
976
977#[macro_export]
979macro_rules! field_types {
980 (string) => {
981 $crate::model::FieldType::String {
982 max_length: None,
983 min_length: None,
984 regex: None,
985 }
986 };
987 (string, max_length = $max:expr) => {
988 $crate::model::FieldType::String {
989 max_length: Some($max),
990 min_length: None,
991 regex: None,
992 }
993 };
994 (string, min_length = $min:expr) => {
995 $crate::model::FieldType::String {
996 max_length: None,
997 min_length: Some($min),
998 regex: None,
999 }
1000 };
1001 (string, max_length = $max:expr, min_length = $min:expr) => {
1002 $crate::model::FieldType::String {
1003 max_length: Some($max),
1004 min_length: Some($min),
1005 regex: None,
1006 }
1007 };
1008 (integer) => {
1009 $crate::model::FieldType::Integer {
1010 min_value: None,
1011 max_value: None,
1012 }
1013 };
1014 (integer, min = $min:expr) => {
1015 $crate::model::FieldType::Integer {
1016 min_value: Some($min),
1017 max_value: None,
1018 }
1019 };
1020 (integer, max = $max:expr) => {
1021 $crate::model::FieldType::Integer {
1022 min_value: None,
1023 max_value: Some($max),
1024 }
1025 };
1026 (integer, min = $min:expr, max = $max:expr) => {
1027 $crate::model::FieldType::Integer {
1028 min_value: Some($min),
1029 max_value: Some($max),
1030 }
1031 };
1032 (float) => {
1033 $crate::model::FieldType::Float {
1034 min_value: None,
1035 max_value: None,
1036 }
1037 };
1038 (boolean) => {
1039 $crate::model::FieldType::Boolean
1040 };
1041 (datetime) => {
1042 $crate::model::FieldType::DateTime
1043 };
1044 (uuid) => {
1045 $crate::model::FieldType::Uuid
1046 };
1047 (json) => {
1048 $crate::model::FieldType::Json
1049 };
1050 (array, $item_type:expr) => {
1051 $crate::model::FieldType::Array {
1052 item_type: Box::new($item_type),
1053 max_items: None,
1054 min_items: None,
1055 }
1056 };
1057 (reference, $target:expr) => {
1058 $crate::model::FieldType::Reference {
1059 target_collection: $target.to_string(),
1060 }
1061 };
1062}
1063
1064pub fn array_field(
1067 item_type: FieldType,
1068 max_items: Option<usize>,
1069 min_items: Option<usize>,
1070) -> FieldDefinition {
1071 FieldDefinition::new(FieldType::Array {
1072 item_type: Box::new(item_type),
1073 max_items,
1074 min_items,
1075 })
1076}
1077
1078pub fn list_field(
1081 item_type: FieldType,
1082 max_items: Option<usize>,
1083 min_items: Option<usize>,
1084) -> FieldDefinition {
1085 array_field(item_type, max_items, min_items)
1087}
1088
1089pub fn string_field(
1091 max_length: Option<usize>,
1092 min_length: Option<usize>,
1093 regex: Option<String>,
1094) -> FieldDefinition {
1095 FieldDefinition::new(FieldType::String {
1096 max_length,
1097 min_length,
1098 regex,
1099 })
1100}
1101
1102pub fn integer_field(
1104 min_value: Option<i64>,
1105 max_value: Option<i64>,
1106) -> FieldDefinition {
1107 FieldDefinition::new(FieldType::Integer {
1108 min_value,
1109 max_value,
1110 })
1111}
1112
1113pub fn float_field(
1115 min_value: Option<f64>,
1116 max_value: Option<f64>,
1117) -> FieldDefinition {
1118 FieldDefinition::new(FieldType::Float {
1119 min_value,
1120 max_value,
1121 })
1122}
1123
1124pub fn boolean_field() -> FieldDefinition {
1126 FieldDefinition::new(FieldType::Boolean)
1127}
1128
1129pub fn datetime_field() -> FieldDefinition {
1131 FieldDefinition::new(FieldType::DateTime)
1132}
1133
1134pub fn uuid_field() -> FieldDefinition {
1136 FieldDefinition::new(FieldType::Uuid)
1137}
1138
1139pub fn json_field() -> FieldDefinition {
1141 FieldDefinition::new(FieldType::Json)
1142}
1143
1144pub fn dict_field(fields: HashMap<String, FieldDefinition>) -> FieldDefinition {
1146 FieldDefinition::new(FieldType::Object { fields })
1147}
1148
1149pub fn reference_field(target_collection: String) -> FieldDefinition {
1151 FieldDefinition::new(FieldType::Reference {
1152 target_collection,
1153 })
1154}
1155
1156#[macro_export]
1158macro_rules! define_model {
1159 (
1160 $(#[$meta:meta])*
1161 struct $name:ident {
1162 $(
1163 $(#[$field_meta:meta])*
1164 $field:ident: $field_type:ty,
1165 )*
1166 }
1167
1168 collection = $collection:expr,
1169 $(
1170 database = $database:expr,
1171 )?
1172 fields = {
1173 $(
1174 $field_name:ident: $field_def:expr,
1175 )*
1176 }
1177 $(
1178 indexes = [
1179 $(
1180 { fields: [$($index_field:expr),*], unique: $unique:expr $(, name: $index_name:expr)? },
1181 )*
1182 ],
1183 )?
1184 ) => {
1185 $(#[$meta])*
1186 #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
1187 pub struct $name {
1188 $(
1189 $(#[$field_meta])*
1190 pub $field: $field_type,
1191 )*
1192 }
1193
1194 impl $crate::model::Model for $name {
1195 fn meta() -> $crate::model::ModelMeta {
1196 let mut fields = std::collections::HashMap::new();
1197 $(
1198 fields.insert(stringify!($field_name).to_string(), $field_def);
1199 )*
1200
1201 let mut indexes = Vec::new();
1202 $(
1203 $(
1204 indexes.push($crate::model::IndexDefinition {
1205 fields: vec![$($index_field.to_string()),*],
1206 unique: $unique,
1207 name: None $(.or(Some($index_name.to_string())))?,
1208 });
1209 )*
1210 )?
1211
1212 let model_meta = $crate::model::ModelMeta {
1213 collection_name: $collection.to_string(),
1214 database_alias: None $(.or(Some($database.to_string())))?,
1215 fields,
1216 indexes,
1217 description: None,
1218 };
1219
1220 static ONCE: std::sync::Once = std::sync::Once::new();
1222 ONCE.call_once(|| {
1223 if let Err(e) = $crate::manager::register_model(model_meta.clone()) {
1224 eprintln!("⚠️ 模型注册失败: {}", e);
1225 } else {
1226 println!("✅ 模型自动注册成功: {}", model_meta.collection_name);
1227 }
1228 });
1229
1230 model_meta
1231 }
1232
1233 fn to_data_map_direct(&self) -> $crate::error::QuickDbResult<std::collections::HashMap<String, $crate::types::DataValue>> {
1235 use $crate::model::ToDataValue;
1236 let mut data_map = std::collections::HashMap::new();
1237
1238 $(
1239 data_map.insert(stringify!($field).to_string(), self.$field.to_data_value());
1240 )*
1241
1242 if let Some(id_value) = data_map.get("_id") {
1244 if matches!(id_value, $crate::types::DataValue::Null) {
1245 data_map.remove("_id");
1246 }
1247 }
1248
1249 Ok(data_map)
1250 }
1251 }
1252
1253 impl $name {
1254 pub async fn save(&self) -> $crate::error::QuickDbResult<String> {
1256 self.validate()?;
1257 let data = self.to_data_map()?;
1258 let collection_name = Self::collection_name();
1259 let database_alias = Self::database_alias();
1260
1261 let alias = database_alias.as_deref().unwrap_or("default");
1263 if let Err(e) = $crate::manager::ensure_table_and_indexes(&collection_name, alias).await {
1264 println!("⚠️ 确保表和索引失败: {}", e);
1265 }
1266
1267 let result = $crate::odm::create(
1268 &collection_name,
1269 data,
1270 database_alias.as_deref(),
1271 ).await?;
1272
1273 match result {
1275 $crate::types::DataValue::String(id) => Ok(id),
1276 $crate::types::DataValue::Int(id) => Ok(id.to_string()),
1277 $crate::types::DataValue::Uuid(id) => Ok(id.to_string()),
1278 $crate::types::DataValue::Object(obj) => {
1279 if let Some(id_value) = obj.get("_id").or_else(|| obj.get("id")) {
1281 match id_value {
1282 $crate::types::DataValue::String(id) => Ok(id.clone()),
1283 $crate::types::DataValue::Int(id) => Ok(id.to_string()),
1284 $crate::types::DataValue::Uuid(id) => Ok(id.to_string()),
1285 _ => Ok(format!("{:?}", id_value))
1286 }
1287 } else {
1288 match serde_json::to_string(&obj) {
1290 Ok(json_str) => Ok(json_str),
1291 Err(_) => Ok(format!("{:?}", obj))
1292 }
1293 }
1294 },
1295 other => {
1296 match serde_json::to_string(&other) {
1298 Ok(json_str) => Ok(json_str),
1299 Err(_) => Ok(format!("{:?}", other))
1300 }
1301 }
1302 }
1303 }
1304
1305 pub async fn update(&self, updates: std::collections::HashMap<String, $crate::types::DataValue>) -> $crate::error::QuickDbResult<bool> {
1307 let data_map = self.to_data_map()?;
1309 let (id_field_name, id_value) = data_map.get("_id")
1310 .map(|v| ("_id", v))
1311 .or_else(|| data_map.get("id").map(|v| ("id", v)))
1312 .ok_or_else(|| $crate::error::QuickDbError::ValidationError {
1313 field: "id".to_string(),
1314 message: "模型缺少ID字段(id 或 _id),无法更新".to_string()
1315 })?;
1316
1317 let id_str = match id_value {
1319 $crate::types::DataValue::String(s) => s.clone(),
1320 $crate::types::DataValue::Int(i) => i.to_string(),
1321 $crate::types::DataValue::Uuid(u) => u.to_string(),
1322 $crate::types::DataValue::Object(obj) => {
1324 if let Some($crate::types::DataValue::String(oid)) = obj.get("$oid") {
1325 oid.clone()
1326 } else {
1327 return Err($crate::error::QuickDbError::ValidationError {
1328 field: id_field_name.to_string(),
1329 message: format!("不支持的MongoDB ObjectId格式: {:?}", obj)
1330 });
1331 }
1332 }
1333 _ => return Err($crate::error::QuickDbError::ValidationError {
1334 field: id_field_name.to_string(),
1335 message: format!("不支持的ID类型: {:?}", id_value)
1336 })
1337 };
1338
1339 let collection_name = Self::collection_name();
1340 let database_alias = Self::database_alias();
1341
1342 $crate::odm::update_by_id(&collection_name, &id_str, updates, database_alias.as_deref()).await
1343 }
1344
1345 pub async fn delete(&self) -> $crate::error::QuickDbResult<bool> {
1347 let data_map = self.to_data_map()?;
1349 let (id_field_name, id_value) = data_map.get("_id")
1350 .map(|v| ("_id", v))
1351 .or_else(|| data_map.get("id").map(|v| ("id", v)))
1352 .ok_or_else(|| $crate::error::QuickDbError::ValidationError {
1353 field: "id".to_string(),
1354 message: "模型缺少ID字段(id 或 _id),无法删除".to_string()
1355 })?;
1356
1357 let id_str = match id_value {
1359 $crate::types::DataValue::String(s) => s.clone(),
1360 $crate::types::DataValue::Int(i) => i.to_string(),
1361 $crate::types::DataValue::Uuid(u) => u.to_string(),
1362 $crate::types::DataValue::Object(obj) => {
1364 if let Some($crate::types::DataValue::String(oid)) = obj.get("$oid") {
1365 oid.clone()
1366 } else {
1367 return Err($crate::error::QuickDbError::ValidationError {
1368 field: id_field_name.to_string(),
1369 message: format!("不支持的MongoDB ObjectId格式: {:?}", obj)
1370 });
1371 }
1372 }
1373 _ => return Err($crate::error::QuickDbError::ValidationError {
1374 field: id_field_name.to_string(),
1375 message: format!("不支持的ID类型: {:?}", id_value)
1376 })
1377 };
1378
1379 let collection_name = Self::collection_name();
1380 let database_alias = Self::database_alias();
1381
1382 $crate::odm::delete_by_id(&collection_name, &id_str, database_alias.as_deref()).await
1383 }
1384 }
1385 };
1386}