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
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
//! PostgreSQL 时区复杂查询示例
//!
//! 展示如何使用PostgreSQL的timestamptz字段进行时区相关的复杂查询

use chrono::{DateTime, Duration, TimeZone, Utc};
use rand::Rng;
use rat_logger::{LoggerBuilder, debug, handler::term::TermConfig};
use rat_quickdb::manager::shutdown;
use rat_quickdb::types::{
    DataValue, LogicalOperator, PaginationConfig, QueryCondition, QueryConditionGroup,
    QueryOperator, QueryOptions, SortConfig, SortDirection,
};
use rat_quickdb::*;
use rat_quickdb::{
    ModelOperations, boolean_field, datetime_field, float_field, integer_field, string_field,
};
use std::collections::HashMap;

#[tokio::main]
async fn main() -> QuickDbResult<()> {
    // 初始化日志系统
    LoggerBuilder::new()
        .add_terminal_with_config(TermConfig::default())
        .init()
        .expect("日志初始化失败");

    rat_quickdb::init();
    println!("=== PostgreSQL 时区复杂查询示例 ===");

    // 创建数据库配置 - PostgreSQL配置(从id_strategy_test_pgsql.rs复制)
    let config = DatabaseConfig {
        db_type: DatabaseType::PostgreSQL,
        connection: ConnectionConfig::PostgreSQL {
            host: "172.16.0.96".to_string(),
            port: 5432,
            database: "testdb".to_string(),
            username: "testdb".to_string(),
            password: "testdb123456".to_string(),
            ssl_mode: Some("prefer".to_string()),
            tls_config: None,
        },
        pool: PoolConfig::builder()
            .max_connections(10)
            .min_connections(2)
            .connection_timeout(30)
            .idle_timeout(300)
            .max_lifetime(1800)
            .max_retries(3)
            .retry_interval_ms(1000)
            .keepalive_interval_sec(60)
            .health_check_timeout_sec(10)
            .build()
            .unwrap(),
        alias: "default".to_string(),
        cache: None,
        id_strategy: IdStrategy::Uuid,
    };

    // 初始化数据库
    add_database(config).await?;

    // 清理旧的测试表(确保每次都是干净的状态)
    println!("清理旧的测试表...");
    match drop_table("default", "timezone_events").await {
        Ok(_) => println!("✅ 已清理旧的timezone_events表"),
        Err(e) => println!("   注意:清理表失败(可能表不存在): {}", e),
    }

    // 创建测试表
    create_test_table().await?;

    // 插入测试数据
    insert_test_data().await?;

    println!("\n=== 开始时区复杂查询测试 ===\n");

    // 示例1: 基础时区查询 - 查找特定时区的事件
    println!("1. 基础时区查询: 查找UTC时区的事件");

    let utc_condition = QueryConditionGroup::Group {
        operator: LogicalOperator::And,
        conditions: vec![QueryConditionGroup::Single(QueryCondition {
            field: "timezone".to_string(),
            operator: QueryOperator::Eq,
            value: DataValue::String("UTC".to_string()),
        })],
    };

    let utc_result =
        ModelManager::<TimeZoneEvent>::find_with_groups(vec![utc_condition], None).await;

    match utc_result {
        Ok(events) => {
            if events.is_empty() {
                println!(
                    "   ❌ 查询结果为空:预期应该找到UTC时区事件(全球技术峰会),但查询返回0个结果"
                );
            } else {
                println!("   ✅ 找到 {} 个UTC时区事件", events.len());
                for event in &events {
                    println!(
                        "   - {} ({}) - {} ({})",
                        event.event_name, event.event_type, event.location, event.timezone
                    );
                }
            }
        }
        Err(e) => println!("   ❌ 查询失败: {}", e),
    }

    println!();

    // 示例2: 时间范围查询 + 时区过滤 - 查找亚洲时区在特定时间范围内的事件
    println!("2. 时间范围查询 + 时区过滤: 查找亚洲时区且高优先级的事件");

    let current_time = Utc::now();
    let asian_timezones_condition = QueryConditionGroup::Group {
        operator: LogicalOperator::And,
        conditions: vec![
            // 时区条件组 (OR): 查找亚洲时区
            QueryConditionGroup::Group {
                operator: LogicalOperator::Or,
                conditions: vec![
                    QueryConditionGroup::Single(QueryCondition {
                        field: "timezone".to_string(),
                        operator: QueryOperator::Eq,
                        value: DataValue::String("Asia/Shanghai".to_string()),
                    }),
                    QueryConditionGroup::Single(QueryCondition {
                        field: "timezone".to_string(),
                        operator: QueryOperator::Eq,
                        value: DataValue::String("Asia/Tokyo".to_string()),
                    }),
                    QueryConditionGroup::Single(QueryCondition {
                        field: "timezone".to_string(),
                        operator: QueryOperator::Eq,
                        value: DataValue::String("Asia/Dubai".to_string()),
                    }),
                    QueryConditionGroup::Single(QueryCondition {
                        field: "timezone".to_string(),
                        operator: QueryOperator::Eq,
                        value: DataValue::String("Asia/Kolkata".to_string()),
                    }),
                ],
            },
            // 高优先级条件
            QueryConditionGroup::Single(QueryCondition {
                field: "priority".to_string(),
                operator: QueryOperator::Gte,
                value: DataValue::Int(7),
            }),
            // 活跃状态条件
            QueryConditionGroup::Single(QueryCondition {
                field: "is_active".to_string(),
                operator: QueryOperator::Eq,
                value: DataValue::Bool(true),
            }),
        ],
    };

    let asian_result =
        ModelManager::<TimeZoneEvent>::find_with_groups(vec![asian_timezones_condition], None)
            .await;

    match asian_result {
        Ok(events) => {
            if events.is_empty() {
                println!(
                    "   ❌ 查询结果为空:预期应该找到亚洲高优先级活跃事件(亚洲开发者聚会、印度市场活动),但查询返回0个结果"
                );
            } else {
                println!("   ✅ 找到 {} 个亚洲高优先级活跃事件", events.len());
                for event in &events {
                    println!(
                        "   - {} ({}) - {} (优先级: {}, 时区: {})",
                        event.event_name,
                        event.event_type,
                        event.location,
                        event.priority,
                        event.timezone
                    );
                }
            }
        }
        Err(e) => println!("   ❌ 查询失败: {}", e),
    }

    println!();

    // 示例3: 复杂时间窗口查询 - 查找正在进行或即将开始的事件
    println!("3. 复杂时间窗口查询: 查找正在进行或即将开始的事件");

    let time_window_condition = QueryConditionGroup::Group {
        operator: LogicalOperator::And,
        conditions: vec![
            // 活跃状态
            QueryConditionGroup::Single(QueryCondition {
                field: "is_active".to_string(),
                operator: QueryOperator::Eq,
                value: DataValue::Bool(true),
            }),
            // 时间条件组: (事件时间在过去3小时内 OR 事件在未来2小时内)
            QueryConditionGroup::Group {
                operator: LogicalOperator::Or,
                conditions: vec![
                    // 事件在过去3小时内开始
                    QueryConditionGroup::Group {
                        operator: LogicalOperator::And,
                        conditions: vec![
                            QueryConditionGroup::Single(QueryCondition {
                                field: "start_time".to_string(),
                                operator: QueryOperator::Gte,
                                value: DataValue::DateTime(current_time - Duration::hours(3)),
                            }),
                            QueryConditionGroup::Single(QueryCondition {
                                field: "start_time".to_string(),
                                operator: QueryOperator::Lte,
                                value: DataValue::DateTime(current_time),
                            }),
                        ],
                    },
                    // 事件在未来2小时内开始
                    QueryConditionGroup::Group {
                        operator: LogicalOperator::And,
                        conditions: vec![
                            QueryConditionGroup::Single(QueryCondition {
                                field: "start_time".to_string(),
                                operator: QueryOperator::Gt,
                                value: DataValue::DateTime(current_time),
                            }),
                            QueryConditionGroup::Single(QueryCondition {
                                field: "start_time".to_string(),
                                operator: QueryOperator::Lte,
                                value: DataValue::DateTime(current_time + Duration::hours(2)),
                            }),
                        ],
                    },
                ],
            },
        ],
    };

    let time_window_result =
        ModelManager::<TimeZoneEvent>::find_with_groups(vec![time_window_condition], None).await;

    match time_window_result {
        Ok(events) => {
            if events.is_empty() {
                println!(
                    "   ✅ 查询成功,但没有找到正在进行或即将开始的事件(符合预期:测试数据设置的时间窗口不匹配当前时间)"
                );
            } else {
                println!("   找到 {} 个正在进行或即将开始的事件", events.len());
                for event in &events {
                    let time_until_start = if event.start_time > current_time {
                        format!(
                            "将在 {} 分钟后开始",
                            (event.start_time - current_time).num_minutes()
                        )
                    } else {
                        format!(
                            "已开始 {} 分钟",
                            (current_time - event.start_time).num_minutes()
                        )
                    };
                    println!(
                        "   - {} - {} ({})",
                        event.event_name, event.location, time_until_start
                    );
                }
            }
        }
        Err(e) => println!("   ❌ 查询失败: {}", e),
    }

    println!();

    // 示例4: 参与者规模和时区组合查询
    println!("4. 参与者规模和时区组合查询: 查找大型跨时区活动");

    let large_event_condition = QueryConditionGroup::Group {
        operator: LogicalOperator::And,
        conditions: vec![
            // 大型活动条件组
            QueryConditionGroup::Group {
                operator: LogicalOperator::Or,
                conditions: vec![
                    QueryConditionGroup::Single(QueryCondition {
                        field: "participant_count".to_string(),
                        operator: QueryOperator::Gte,
                        value: DataValue::Int(100),
                    }),
                    QueryConditionGroup::Single(QueryCondition {
                        field: "priority".to_string(),
                        operator: QueryOperator::Gte,
                        value: DataValue::Int(8),
                    }),
                ],
            },
            // 排除已结束的活动
            QueryConditionGroup::Single(QueryCondition {
                field: "is_active".to_string(),
                operator: QueryOperator::Eq,
                value: DataValue::Bool(true),
            }),
            // 非UTC时区(跨时区活动)
            QueryConditionGroup::Group {
                operator: LogicalOperator::And,
                conditions: vec![QueryConditionGroup::Single(QueryCondition {
                    field: "timezone".to_string(),
                    operator: QueryOperator::Ne,
                    value: DataValue::String("UTC".to_string()),
                })],
            },
        ],
    };

    let large_event_options = QueryOptions {
        conditions: vec![],
        sort: vec![
            SortConfig {
                field: "participant_count".to_string(),
                direction: SortDirection::Desc,
            },
            SortConfig {
                field: "priority".to_string(),
                direction: SortDirection::Desc,
            },
        ],
        pagination: Some(PaginationConfig { limit: 5, skip: 0 }),
        fields: vec![],
    };

    let large_event_result = ModelManager::<TimeZoneEvent>::find_with_groups(
        vec![large_event_condition],
        Some(large_event_options),
    )
    .await;

    match large_event_result {
        Ok(events) => {
            if events.is_empty() {
                println!(
                    "   ❌ 查询结果为空:预期应该找到跨时区大型活动(美洲用户大会、欧洲产品发布会等),但查询返回0个结果"
                );
            } else {
                println!("   ✅ 找到 {} 个大型跨时区活动", events.len());
                for (i, event) in events.iter().enumerate() {
                    println!(
                        "   {}. {} ({} 人参与, 优先级: {}, 时区: {})",
                        i + 1,
                        event.event_name,
                        event.participant_count,
                        event.priority,
                        event.timezone
                    );
                }
            }
        }
        Err(e) => println!("   ❌ 查询失败: {}", e),
    }

    println!();

    // 示例5: 多层嵌套复杂查询 - 综合条件查询
    println!("5. 多层嵌套复杂查询: 查找技术类高优先级事件或在欧美时区的大型活动");

    let complex_nested_condition = QueryConditionGroup::Group {
        operator: LogicalOperator::Or,
        conditions: vec![
            // 第一个条件组: 技术类高优先级事件
            QueryConditionGroup::Group {
                operator: LogicalOperator::And,
                conditions: vec![
                    QueryConditionGroup::Group {
                        operator: LogicalOperator::Or,
                        conditions: vec![
                            QueryConditionGroup::Single(QueryCondition {
                                field: "event_type".to_string(),
                                operator: QueryOperator::Contains,
                                value: DataValue::String("技术".to_string()),
                            }),
                            QueryConditionGroup::Single(QueryCondition {
                                field: "event_type".to_string(),
                                operator: QueryOperator::Contains,
                                value: DataValue::String("开发".to_string()),
                            }),
                        ],
                    },
                    QueryConditionGroup::Single(QueryCondition {
                        field: "priority".to_string(),
                        operator: QueryOperator::Gte,
                        value: DataValue::Int(7),
                    }),
                    QueryConditionGroup::Single(QueryCondition {
                        field: "is_active".to_string(),
                        operator: QueryOperator::Eq,
                        value: DataValue::Bool(true),
                    }),
                ],
            },
            // 第二个条件组: 欧美时区的大型活动
            QueryConditionGroup::Group {
                operator: LogicalOperator::And,
                conditions: vec![
                    QueryConditionGroup::Group {
                        operator: LogicalOperator::Or,
                        conditions: vec![
                            QueryConditionGroup::Single(QueryCondition {
                                field: "timezone".to_string(),
                                operator: QueryOperator::Eq,
                                value: DataValue::String("Europe/London".to_string()),
                            }),
                            QueryConditionGroup::Single(QueryCondition {
                                field: "timezone".to_string(),
                                operator: QueryOperator::Eq,
                                value: DataValue::String("America/New_York".to_string()),
                            }),
                        ],
                    },
                    QueryConditionGroup::Single(QueryCondition {
                        field: "participant_count".to_string(),
                        operator: QueryOperator::Gt,
                        value: DataValue::Int(150),
                    }),
                    QueryConditionGroup::Single(QueryCondition {
                        field: "is_active".to_string(),
                        operator: QueryOperator::Eq,
                        value: DataValue::Bool(true),
                    }),
                ],
            },
        ],
    };

    let complex_nested_result =
        ModelManager::<TimeZoneEvent>::find_with_groups(vec![complex_nested_condition], None).await;

    match complex_nested_result {
        Ok(events) => {
            if events.is_empty() {
                println!(
                    "   ❌ 查询结果为空:预期应该找到技术类高优先级事件或欧美时区大型活动,但查询返回0个结果"
                );
            } else {
                println!("   ✅ 找到 {} 个匹配条件的事件", events.len());
                for event in &events {
                    let category = if event.event_type.contains("技术")
                        || event.event_type.contains("开发")
                    {
                        "技术类高优先级"
                    } else {
                        "欧美时区大型活动"
                    };
                    println!(
                        "   - [{}] {} - {} ({}, {} 人)",
                        category,
                        event.event_name,
                        event.location,
                        event.timezone,
                        event.participant_count
                    );
                }
            }
        }
        Err(e) => println!("   ❌ 查询失败: {}", e),
    }

    println!();

    // 示例6: 选填时间字段查询 - 查找有设置结束时间的事件(排除end_time为null的记录)
    println!("6. 选填时间字段查询: 查找有明确结束时间的事件(排除end_time为null的记录)");

    let has_end_time_condition = QueryConditionGroup::Group {
        operator: LogicalOperator::And,
        conditions: vec![
            // 结束时间不为null的条件
            QueryConditionGroup::Single(QueryCondition {
                field: "end_time".to_string(),
                operator: QueryOperator::IsNotNull,
                value: DataValue::Null, // IsNotNull操作符不需要值,但框架要求提供一个值
            }),
            // 活跃状态条件
            QueryConditionGroup::Single(QueryCondition {
                field: "is_active".to_string(),
                operator: QueryOperator::Eq,
                value: DataValue::Bool(true),
            }),
            // 持续时间至少1小时的事件(结束时间 > 开始时间 + 1小时)
            QueryConditionGroup::Group {
                operator: LogicalOperator::And,
                conditions: vec![QueryConditionGroup::Single(QueryCondition {
                    field: "end_time".to_string(),
                    operator: QueryOperator::Gt,
                    value: DataValue::DateTime(Utc::now() - Duration::days(1)), // 确保结束时间有意义
                })],
            },
        ],
    };

    let has_end_time_result =
        ModelManager::<TimeZoneEvent>::find_with_groups(vec![has_end_time_condition], None).await;

    match has_end_time_result {
        Ok(events) => {
            if events.is_empty() {
                println!(
                    "   ❌ 查询结果为空:预期应该找到有明确结束时间的活跃事件,但查询返回0个结果"
                );
            } else {
                println!("   ✅ 找到 {} 个有明确结束时间的活跃事件", events.len());
                for event in &events {
                    if let Some(end_time) = event.end_time {
                        let duration = end_time - event.start_time;
                        let duration_hours = duration.num_hours();
                        let duration_minutes = duration.num_minutes() % 60;

                        println!(
                            "   - {} ({}) - {} (持续时间: {}小时{}分钟)",
                            event.event_name,
                            event.event_type,
                            event.location,
                            duration_hours,
                            duration_minutes
                        );

                        // 显示具体的时间信息
                        println!(
                            "     开始时间: {} UTC",
                            event.start_time.format("%Y-%m-%d %H:%M:%S")
                        );
                        println!(
                            "     结束时间: {} UTC",
                            end_time.format("%Y-%m-%d %H:%M:%S")
                        );
                    }
                }
            }
        }
        Err(e) => println!("   ❌ 查询失败: {}", e),
    }

    println!();

    // 额外演示:对比查询 - 查找没有设置结束时间的事件
    println!("6b. 对比查询: 查找没有设置结束时间的事件(end_time为null)");

    let no_end_time_condition = QueryConditionGroup::Group {
        operator: LogicalOperator::And,
        conditions: vec![
            // 结束时间为null的条件
            QueryConditionGroup::Single(QueryCondition {
                field: "end_time".to_string(),
                operator: QueryOperator::IsNull,
                value: DataValue::Null, // IsNull操作符不需要值,但框架要求提供一个值
            }),
            // 活跃状态条件
            QueryConditionGroup::Single(QueryCondition {
                field: "is_active".to_string(),
                operator: QueryOperator::Eq,
                value: DataValue::Bool(true),
            }),
        ],
    };

    let no_end_time_result =
        ModelManager::<TimeZoneEvent>::find_with_groups(vec![no_end_time_condition], None).await;

    match no_end_time_result {
        Ok(events) => {
            if events.is_empty() {
                println!(
                    "   ✅ 查询成功,但没有找到没有结束时间的活跃事件(说明所有活跃事件都设置了结束时间)"
                );
            } else {
                println!("   ✅ 找到 {} 个没有设置结束时间的活跃事件", events.len());
                for event in &events {
                    println!(
                        "   - {} ({}) - {} (开始时间: {} UTC, 结束时间: 未设置)",
                        event.event_name,
                        event.event_type,
                        event.location,
                        event.start_time.format("%Y-%m-%d %H:%M:%S")
                    );
                }
            }
        }
        Err(e) => println!("   ❌ 查询失败: {}", e),
    }

    println!("\n=== 时区复杂查询示例完成 ===");

    // 关闭连接池
    shutdown().await?;

    Ok(())
}

// 定义时区事件模型
define_model! {
    /// 时区事件模型 - 用于演示timestamptz字段和时区相关查询
    struct TimeZoneEvent {
        id: String,
        event_name: String,
        event_type: String,
        location: String,
        timezone: String,  // 时区标识符
        event_time: chrono::DateTime<chrono::Utc>,  // 主事件时间 (timestamptz)
        start_time: chrono::DateTime<chrono::Utc>,  // 开始时间 (timestamptz)
        end_time: Option<chrono::DateTime<chrono::Utc>>,  // 结束时间 (timestamptz)
        participant_count: i32,
        is_active: bool,
        priority: i32,  // 优先级 1-10
        created_at: chrono::DateTime<chrono::Utc>,
        updated_at: Option<chrono::DateTime<chrono::Utc>>,
    }
    collection = "timezone_events",
    fields = {
        id: string_field(None, None, None).required().unique(),
        event_name: string_field(Some(200), Some(1), None).required(),
        event_type: string_field(Some(50), Some(1), None).required(),
        location: string_field(Some(100), Some(1), None).required(),
        timezone: string_field(Some(50), Some(1), None).required(),
        event_time: datetime_field().required(),
        start_time: datetime_field().required(),
        end_time: datetime_field(),
        participant_count: integer_field(Some(0), Some(10000)).required(),
        is_active: boolean_field().required(),
        priority: integer_field(Some(1), Some(10)).required(),
        created_at: datetime_field().required(),
        updated_at: datetime_field(),
    }
    indexes = [
        { fields: ["event_type"], unique: false, name: "idx_event_type" },
        { fields: ["timezone"], unique: false, name: "idx_timezone" },
        { fields: ["event_time"], unique: false, name: "idx_event_time" },
        { fields: ["start_time"], unique: false, name: "idx_start_time" },
        { fields: ["end_time"], unique: false, name: "idx_end_time" },
        { fields: ["is_active"], unique: false, name: "idx_is_active" },
        { fields: ["priority"], unique: false, name: "idx_priority" },
        { fields: ["event_type", "timezone"], unique: false, name: "idx_type_timezone" },
        { fields: ["event_time", "timezone"], unique: false, name: "idx_time_timezone" },
        { fields: ["is_active", "event_time"], unique: false, name: "idx_active_time" },
        { fields: ["event_type", "is_active", "event_time"], unique: false, name: "idx_type_active_time" },
    ],
}

/// 创建测试表(现在由模型自动处理)
async fn create_test_table() -> QuickDbResult<()> {
    // 模型会自动创建表和索引,无需手动操作
    println!("✅ 时区事件表定义完成(通过模型自动创建)");
    Ok(())
}

/// 插入测试数据
async fn insert_test_data() -> QuickDbResult<()> {
    println!("插入时区事件测试数据...");

    let base_time = Utc::now();
    let test_events = vec![
        create_timezone_event(
            "全球技术峰会",
            "技术会议",
            "线上",
            "UTC",
            base_time + Duration::hours(8),
            base_time + Duration::hours(8),
            Duration::hours(4), // 4小时基础持续时间
            500,
            true,
            8,
        ),
        create_timezone_event(
            "亚洲开发者聚会",
            "技术聚会",
            "上海",
            "Asia/Shanghai",
            base_time + Duration::hours(10),
            base_time + Duration::hours(10),
            Duration::hours(4), // 4小时基础持续时间
            150,
            true,
            7,
        ),
        create_timezone_event(
            "欧洲产品发布会",
            "产品发布",
            "伦敦",
            "Europe/London",
            base_time + Duration::hours(14),
            base_time + Duration::hours(14),
            Duration::hours(2), // 2小时基础持续时间
            200,
            true,
            9,
        ),
        create_timezone_event(
            "美洲用户大会",
            "用户会议",
            "纽约",
            "America/New_York",
            base_time + Duration::hours(18),
            base_time + Duration::hours(18),
            Duration::hours(4), // 4小时基础持续时间
            300,
            true,
            10,
        ),
        create_timezone_event(
            "太平洋区域研讨会",
            "研讨会",
            "东京",
            "Asia/Tokyo",
            base_time + Duration::hours(6),
            base_time + Duration::hours(6),
            Duration::hours(3), // 3小时基础持续时间
            80,
            true,
            6,
        ),
        create_timezone_event(
            "澳洲技术交流会",
            "技术交流",
            "悉尼",
            "Australia/Sydney",
            base_time + Duration::hours(12),
            base_time + Duration::hours(12),
            Duration::hours(3), // 3小时基础持续时间
            60,
            false, // 已结束的活动
            5,
        ),
        create_timezone_event(
            "中东地区培训",
            "培训",
            "迪拜",
            "Asia/Dubai",
            base_time + Duration::hours(16),
            base_time + Duration::hours(16),
            Duration::hours(3), // 3小时基础持续时间
            40,
            true,
            4,
        ),
        create_timezone_event(
            "印度市场活动",
            "市场活动",
            "班加罗尔",
            "Asia/Kolkata",
            base_time + Duration::hours(11),
            base_time + Duration::hours(11),
            Duration::hours(2), // 2小时基础持续时间
            120,
            true,
            7,
        ),
    ];

    for (i, event_data) in test_events.iter().enumerate() {
        // 从HashMap数据创建TimeZoneEvent结构体实例
        let event = TimeZoneEvent {
            id: String::new(), // 框架会自动生成ID
            event_name: if let Some(DataValue::String(name)) = event_data.get("event_name") {
                name.clone()
            } else {
                "".to_string()
            },
            event_type: if let Some(DataValue::String(event_type)) = event_data.get("event_type") {
                event_type.clone()
            } else {
                "".to_string()
            },
            location: if let Some(DataValue::String(location)) = event_data.get("location") {
                location.clone()
            } else {
                "".to_string()
            },
            timezone: if let Some(DataValue::String(timezone)) = event_data.get("timezone") {
                timezone.clone()
            } else {
                "".to_string()
            },
            event_time: if let Some(DataValue::DateTime(dt)) = event_data.get("event_time") {
                *dt
            } else {
                Utc::now()
            },
            start_time: if let Some(DataValue::DateTime(dt)) = event_data.get("start_time") {
                *dt
            } else {
                Utc::now()
            },
            end_time: if let Some(end_time_data) = event_data.get("end_time") {
                match end_time_data {
                    DataValue::DateTime(dt) => Some(*dt),
                    _ => None,
                }
            } else {
                None
            },
            participant_count: if let Some(DataValue::Int(count)) =
                event_data.get("participant_count")
            {
                *count as i32
            } else {
                0
            },
            is_active: if let Some(DataValue::Bool(active)) = event_data.get("is_active") {
                *active
            } else {
                false
            },
            priority: if let Some(DataValue::Int(priority)) = event_data.get("priority") {
                *priority as i32
            } else {
                1
            },
            created_at: if let Some(DataValue::DateTime(dt)) = event_data.get("created_at") {
                *dt
            } else {
                Utc::now()
            },
            updated_at: Some(Utc::now()),
        };

        let result = event.save().await?;
        println!(
            "   创建事件 {}: {} ({})",
            i + 1,
            result,
            if let Some(DataValue::String(tz)) = event_data.get("timezone") {
                tz
            } else {
                "Unknown"
            }
        );
    }

    println!("✅ 时区事件测试数据插入完成");
    Ok(())
}

/// 创建时区事件数据的辅助函数
fn create_timezone_event(
    name: &str,
    event_type: &str,
    location: &str,
    timezone: &str,
    event_time: DateTime<Utc>,
    start_time: DateTime<Utc>,
    base_duration: Duration, // 基础持续时间
    participant_count: i32,
    is_active: bool,
    priority: i32,
) -> HashMap<String, DataValue> {
    // 随机决定是否设置结束时间(70%概率设置结束时间,30%概率不设置)
    let mut rng = rand::thread_rng();
    let has_end_time = rng.gen_bool(0.7);

    // 计算结束时间(如果设置的话)
    let end_time = if has_end_time {
        // 随机调整持续时间:基础时间 ± 1小时
        let duration_variation = rng.gen_range(-60..=60); // 分钟变化
        let actual_duration = base_duration + Duration::minutes(duration_variation);
        Some(start_time + actual_duration)
    } else {
        None
    };
    let mut event_data = HashMap::new();
    event_data.insert(
        "event_name".to_string(),
        DataValue::String(name.to_string()),
    );
    event_data.insert(
        "event_type".to_string(),
        DataValue::String(event_type.to_string()),
    );
    event_data.insert(
        "location".to_string(),
        DataValue::String(location.to_string()),
    );
    event_data.insert(
        "timezone".to_string(),
        DataValue::String(timezone.to_string()),
    );
    event_data.insert("event_time".to_string(), DataValue::DateTime(event_time));
    event_data.insert("start_time".to_string(), DataValue::DateTime(start_time));

    // 只有在有结束时间时才设置end_time字段
    if let Some(end_time) = end_time {
        event_data.insert("end_time".to_string(), DataValue::DateTime(end_time));
        debug!(
            "事件 '{}' 设置了结束时间: {}",
            name,
            end_time.format("%Y-%m-%d %H:%M:%S UTC")
        );
    } else {
        debug!("事件 '{}' 没有设置结束时间", name);
    }

    event_data.insert(
        "participant_count".to_string(),
        DataValue::Int(participant_count as i64),
    );
    event_data.insert("is_active".to_string(), DataValue::Bool(is_active));
    event_data.insert("priority".to_string(), DataValue::Int(priority as i64));
    event_data.insert("created_at".to_string(), DataValue::DateTime(Utc::now()));
    event_data
}