rust-queries-core 1.0.8

Core functionality for rust-queries-builder - type-safe query builder for Rust collections
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
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
//! Query builder implementation for filtering, selecting, ordering, grouping, and aggregating data.
//!
//! This module provides the `Query` struct which enables SQL-like operations on collections
//! using type-safe key-paths.

use key_paths_core::KeyPaths;
use std::collections::HashMap;
use std::time::SystemTime;

#[cfg(feature = "datetime")]
use chrono::{DateTime, TimeZone};

/// A query builder for filtering, selecting, ordering, grouping, and aggregating data.
///
/// # Type Parameters
///
/// * `'a` - The lifetime of the data being queried
/// * `T` - The type of items in the collection
///
/// # Example
///
/// ```ignore
/// let products = vec![/* ... */];
/// let query = Query::new(&products)
///     .where_(Product::price(), |&price| price < 100.0)
///     .order_by_float(Product::price());
/// ```
pub struct Query<'a, T: 'static> {
    data: &'a [T],
    filters: Vec<Box<dyn Fn(&T) -> bool>>,
}

// Core implementation without Clone requirement
impl<'a, T: 'static> Query<'a, T> {
    /// Creates a new query from a slice of data.
    ///
    /// # Arguments
    ///
    /// * `data` - A slice of items to query
    ///
    /// # Example
    ///
    /// ```ignore
    /// let query = Query::new(&products);
    /// ```
    pub fn new(data: &'a [T]) -> Self {
        Self {
            data,
            filters: Vec::new(),
        }
    }

    /// Adds a filter predicate using a key-path.
    ///
    /// # Arguments
    ///
    /// * `path` - The key-path to the field to filter on
    /// * `predicate` - A function that returns true for items to keep
    ///
    /// # Example
    ///
    /// ```ignore
    /// let query = Query::new(&products)
    ///     .where_(Product::category(), |cat| cat == "Electronics");
    /// ```
    pub fn where_<F>(mut self, path: KeyPaths<T, F>, predicate: impl Fn(&F) -> bool + 'static) -> Self
    where
        F: 'static,
    {
        self.filters.push(Box::new(move |item| {
            path.get(item).map_or(false, |val| predicate(val))
        }));
        self
    }

    /// Returns all items matching the query filters.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let results = query.all();
    /// ```
    pub fn all(&self) -> Vec<&T> {
        self.data
            .iter()
            .filter(|item| self.filters.iter().all(|f| f(item)))
            .collect()
    }

    /// Returns the first item matching the query filters.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let first = query.first();
    /// ```
    pub fn first(&self) -> Option<&T> {
        self.data
            .iter()
            .find(|item| self.filters.iter().all(|f| f(item)))
    }

    /// Returns the count of items matching the query filters.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let count = query.count();
    /// ```
    pub fn count(&self) -> usize {
        self.data
            .iter()
            .filter(|item| self.filters.iter().all(|f| f(item)))
            .count()
    }

    /// Returns the first `n` items matching the query filters.
    ///
    /// # Arguments
    ///
    /// * `n` - The maximum number of items to return
    ///
    /// # Example
    ///
    /// ```ignore
    /// let first_10 = query.limit(10);
    /// ```
    pub fn limit(&self, n: usize) -> Vec<&T> {
        self.data
            .iter()
            .filter(|item| self.filters.iter().all(|f| f(item)))
            .take(n)
            .collect()
    }

    /// Skips the first `offset` items for pagination.
    ///
    /// # Arguments
    ///
    /// * `offset` - The number of items to skip
    ///
    /// # Example
    ///
    /// ```ignore
    /// let page_2 = query.skip(20).limit(10);
    /// ```
    pub fn skip<'b>(&'b self, offset: usize) -> QueryWithSkip<'a, 'b, T> {
        QueryWithSkip {
            query: self,
            offset,
        }
    }

    /// Projects/selects a single field from results.
    ///
    /// # Arguments
    ///
    /// * `path` - The key-path to the field to select
    ///
    /// # Example
    ///
    /// ```ignore
    /// let names = query.select(Product::name());
    /// ```
    pub fn select<F>(&self, path: KeyPaths<T, F>) -> Vec<F>
    where
        F: Clone + 'static,
    {
        self.data
            .iter()
            .filter(|item| self.filters.iter().all(|f| f(item)))
            .filter_map(|item| path.get(item).cloned())
            .collect()
    }

    /// Computes the sum of a numeric field.
    ///
    /// # Arguments
    ///
    /// * `path` - The key-path to the numeric field
    ///
    /// # Example
    ///
    /// ```ignore
    /// let total_price = query.sum(Product::price());
    /// ```
    pub fn sum<F>(&self, path: KeyPaths<T, F>) -> F
    where
        F: Clone + std::ops::Add<Output = F> + Default + 'static,
    {
        self.data
            .iter()
            .filter(|item| self.filters.iter().all(|f| f(item)))
            .filter_map(|item| path.get(item).cloned())
            .fold(F::default(), |acc, val| acc + val)
    }

    /// Computes the average of a float field.
    ///
    /// # Arguments
    ///
    /// * `path` - The key-path to the f64 field
    ///
    /// # Example
    ///
    /// ```ignore
    /// let avg_price = query.avg(Product::price()).unwrap_or(0.0);
    /// ```
    pub fn avg(&self, path: KeyPaths<T, f64>) -> Option<f64> {
        let items: Vec<f64> = self
            .data
            .iter()
            .filter(|item| self.filters.iter().all(|f| f(item)))
            .filter_map(|item| path.get(item).cloned())
            .collect();

        if items.is_empty() {
            None
        } else {
            Some(items.iter().sum::<f64>() / items.len() as f64)
        }
    }

    /// Finds the minimum value of a field.
    ///
    /// # Arguments
    ///
    /// * `path` - The key-path to the field
    ///
    /// # Example
    ///
    /// ```ignore
    /// let min_stock = query.min(Product::stock());
    /// ```
    pub fn min<F>(&self, path: KeyPaths<T, F>) -> Option<F>
    where
        F: Ord + Clone + 'static,
    {
        self.data
            .iter()
            .filter(|item| self.filters.iter().all(|f| f(item)))
            .filter_map(|item| path.get(item).cloned())
            .min()
    }

    /// Finds the maximum value of a field.
    ///
    /// # Arguments
    ///
    /// * `path` - The key-path to the field
    ///
    /// # Example
    ///
    /// ```ignore
    /// let max_stock = query.max(Product::stock());
    /// ```
    pub fn max<F>(&self, path: KeyPaths<T, F>) -> Option<F>
    where
        F: Ord + Clone + 'static,
    {
        self.data
            .iter()
            .filter(|item| self.filters.iter().all(|f| f(item)))
            .filter_map(|item| path.get(item).cloned())
            .max()
    }

    /// Finds the minimum value of a float field.
    ///
    /// # Arguments
    ///
    /// * `path` - The key-path to the f64 field
    ///
    /// # Example
    ///
    /// ```ignore
    /// let min_price = query.min_float(Product::price());
    /// ```
    pub fn min_float(&self, path: KeyPaths<T, f64>) -> Option<f64> {
        self.data
            .iter()
            .filter(|item| self.filters.iter().all(|f| f(item)))
            .filter_map(|item| path.get(item).cloned())
            .min_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
    }

    /// Finds the maximum value of a float field.
    ///
    /// # Arguments
    ///
    /// * `path` - The key-path to the f64 field
    ///
    /// # Example
    ///
    /// ```ignore
    /// let max_price = query.max_float(Product::price());
    /// ```
    pub fn max_float(&self, path: KeyPaths<T, f64>) -> Option<f64> {
        self.data
            .iter()
            .filter(|item| self.filters.iter().all(|f| f(item)))
            .filter_map(|item| path.get(item).cloned())
            .max_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
    }

    /// Checks if any items match the query filters.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let has_results = query.exists();
    /// ```
    pub fn exists(&self) -> bool {
        self.data
            .iter()
            .any(|item| self.filters.iter().all(|f| f(item)))
    }

    // DateTime operations for SystemTime
    /// Filter by SystemTime being after a reference time.
    ///
    /// # Arguments
    ///
    /// * `path` - The key-path to the SystemTime field
    /// * `reference` - The reference time to compare against
    ///
    /// # Example
    ///
    /// ```ignore
    /// let recent = query.where_after_systemtime(Event::timestamp(), &cutoff_time);
    /// ```
    pub fn where_after_systemtime(self, path: KeyPaths<T, SystemTime>, reference: SystemTime) -> Self {
        self.where_(path, move |time| time > &reference)
    }

    /// Filter by SystemTime being before a reference time.
    ///
    /// # Arguments
    ///
    /// * `path` - The key-path to the SystemTime field
    /// * `reference` - The reference time to compare against
    ///
    /// # Example
    ///
    /// ```ignore
    /// let old = query.where_before_systemtime(Event::timestamp(), &cutoff_time);
    /// ```
    pub fn where_before_systemtime(self, path: KeyPaths<T, SystemTime>, reference: SystemTime) -> Self {
        self.where_(path, move |time| time < &reference)
    }

    /// Filter by SystemTime being between two times (inclusive).
    ///
    /// # Arguments
    ///
    /// * `path` - The key-path to the SystemTime field
    /// * `start` - The start time
    /// * `end` - The end time
    ///
    /// # Example
    ///
    /// ```ignore
    /// let range = query.where_between_systemtime(Event::timestamp(), &start, &end);
    /// ```
    pub fn where_between_systemtime(
        self,
        path: KeyPaths<T, SystemTime>,
        start: SystemTime,
        end: SystemTime,
    ) -> Self {
        self.where_(path, move |time| time >= &start && time <= &end)
    }
}

// DateTime operations with chrono (only available with datetime feature)
#[cfg(feature = "datetime")]
impl<'a, T: 'static> Query<'a, T> {
    /// Filter by DateTime being after a reference time.
    ///
    /// # Arguments
    ///
    /// * `path` - The key-path to the DateTime field
    /// * `reference` - The reference time to compare against
    ///
    /// # Example
    ///
    /// ```ignore
    /// let recent = query.where_after(Event::timestamp(), &cutoff_time);
    /// ```
    pub fn where_after<Tz>(self, path: KeyPaths<T, DateTime<Tz>>, reference: DateTime<Tz>) -> Self
    where
        Tz: TimeZone + 'static,
        Tz::Offset: std::fmt::Display,
    {
        self.where_(path, move |time| time > &reference)
    }

    /// Filter by DateTime being before a reference time.
    ///
    /// # Arguments
    ///
    /// * `path` - The key-path to the DateTime field
    /// * `reference` - The reference time to compare against
    ///
    /// # Example
    ///
    /// ```ignore
    /// let old = query.where_before(Event::timestamp(), &cutoff_time);
    /// ```
    pub fn where_before<Tz>(self, path: KeyPaths<T, DateTime<Tz>>, reference: DateTime<Tz>) -> Self
    where
        Tz: TimeZone + 'static,
        Tz::Offset: std::fmt::Display,
    {
        self.where_(path, move |time| time < &reference)
    }

    /// Filter by DateTime being between two times (inclusive).
    ///
    /// # Arguments
    ///
    /// * `path` - The key-path to the DateTime field
    /// * `start` - The start time
    /// * `end` - The end time
    ///
    /// # Example
    ///
    /// ```ignore
    /// let range = query.where_between(Event::timestamp(), &start, &end);
    /// ```
    pub fn where_between<Tz>(
        self,
        path: KeyPaths<T, DateTime<Tz>>,
        start: DateTime<Tz>,
        end: DateTime<Tz>,
    ) -> Self
    where
        Tz: TimeZone + 'static,
        Tz::Offset: std::fmt::Display,
    {
        self.where_(path, move |time| time >= &start && time <= &end)
    }

    /// Filter by DateTime being today.
    ///
    /// # Arguments
    ///
    /// * `path` - The key-path to the DateTime field
    /// * `now` - The current DateTime to compare against
    ///
    /// # Example
    ///
    /// ```ignore
    /// let today = query.where_today(Event::timestamp(), &Utc::now());
    /// ```
    pub fn where_today<Tz>(self, path: KeyPaths<T, DateTime<Tz>>, now: DateTime<Tz>) -> Self
    where
        Tz: TimeZone + 'static,
        Tz::Offset: std::fmt::Display,
    {
        self.where_(path, move |time| {
            time.date_naive() == now.date_naive()
        })
    }

    /// Filter by DateTime year.
    ///
    /// # Arguments
    ///
    /// * `path` - The key-path to the DateTime field
    /// * `year` - The year to filter by
    ///
    /// # Example
    ///
    /// ```ignore
    /// let this_year = query.where_year(Event::timestamp(), 2024);
    /// ```
    pub fn where_year<Tz>(self, path: KeyPaths<T, DateTime<Tz>>, year: i32) -> Self
    where
        Tz: TimeZone + 'static,
        Tz::Offset: std::fmt::Display,
    {
        use chrono::Datelike;
        self.where_(path, move |time| time.year() == year)
    }

    /// Filter by DateTime month.
    ///
    /// # Arguments
    ///
    /// * `path` - The key-path to the DateTime field
    /// * `month` - The month to filter by (1-12)
    ///
    /// # Example
    ///
    /// ```ignore
    /// let december = query.where_month(Event::timestamp(), 12);
    /// ```
    pub fn where_month<Tz>(self, path: KeyPaths<T, DateTime<Tz>>, month: u32) -> Self
    where
        Tz: TimeZone + 'static,
        Tz::Offset: std::fmt::Display,
    {
        use chrono::Datelike;
        self.where_(path, move |time| time.month() == month)
    }

    /// Filter by DateTime day.
    ///
    /// # Arguments
    ///
    /// * `path` - The key-path to the DateTime field
    /// * `day` - The day to filter by (1-31)
    ///
    /// # Example
    ///
    /// ```ignore
    /// let first = query.where_day(Event::timestamp(), 1);
    /// ```
    pub fn where_day<Tz>(self, path: KeyPaths<T, DateTime<Tz>>, day: u32) -> Self
    where
        Tz: TimeZone + 'static,
        Tz::Offset: std::fmt::Display,
    {
        use chrono::Datelike;
        self.where_(path, move |time| time.day() == day)
    }

    /// Filter by weekend dates (Saturday and Sunday).
    ///
    /// # Arguments
    ///
    /// * `path` - The key-path to the DateTime field
    ///
    /// # Example
    ///
    /// ```ignore
    /// let weekend_events = query.where_weekend(Event::timestamp());
    /// ```
    pub fn where_weekend<Tz>(self, path: KeyPaths<T, DateTime<Tz>>) -> Self
    where
        Tz: TimeZone + 'static,
        Tz::Offset: std::fmt::Display,
    {
        use chrono::Datelike;
        self.where_(path, |time| {
            let weekday = time.weekday().num_days_from_monday();
            weekday >= 5
        })
    }

    /// Filter by weekday dates (Monday through Friday).
    ///
    /// # Arguments
    ///
    /// * `path` - The key-path to the DateTime field
    ///
    /// # Example
    ///
    /// ```ignore
    /// let weekday_events = query.where_weekday(Event::timestamp());
    /// ```
    pub fn where_weekday<Tz>(self, path: KeyPaths<T, DateTime<Tz>>) -> Self
    where
        Tz: TimeZone + 'static,
        Tz::Offset: std::fmt::Display,
    {
        use chrono::Datelike;
        self.where_(path, |time| {
            let weekday = time.weekday().num_days_from_monday();
            weekday < 5
        })
    }

    /// Filter by business hours (9 AM - 5 PM).
    ///
    /// # Arguments
    ///
    /// * `path` - The key-path to the DateTime field
    ///
    /// # Example
    ///
    /// ```ignore
    /// let business_hours = query.where_business_hours(Event::timestamp());
    /// ```
    pub fn where_business_hours<Tz>(self, path: KeyPaths<T, DateTime<Tz>>) -> Self
    where
        Tz: TimeZone + 'static,
        Tz::Offset: std::fmt::Display,
    {
        use chrono::Timelike;
        self.where_(path, |time| {
            let hour = time.hour();
            hour >= 9 && hour < 17
        })
    }
}

// Operations that require Clone - separated for flexibility
impl<'a, T: 'static + Clone> Query<'a, T> {
    /// Orders results by a field in ascending order.
    /// 
    /// **Note**: This method requires `T: Clone` as it creates owned sorted copies.
    ///
    /// # Arguments
    ///
    /// * `path` - The key-path to the field to order by
    ///
    /// # Example
    ///
    /// ```ignore
    /// let sorted = query.order_by(Product::name());
    /// ```
    pub fn order_by<F>(&self, path: KeyPaths<T, F>) -> Vec<T>
    where
        F: Ord + Clone + 'static,
    {
        let mut results: Vec<T> = self
            .data
            .iter()
            .filter(|item| self.filters.iter().all(|f| f(item)))
            .cloned()
            .collect();

        results.sort_by_key(|item| path.get(item).cloned());
        results
    }

    /// Orders results by a field in descending order.
    /// 
    /// **Note**: This method requires `T: Clone` as it creates owned sorted copies.
    ///
    /// # Arguments
    ///
    /// * `path` - The key-path to the field to order by
    ///
    /// # Example
    ///
    /// ```ignore
    /// let sorted = query.order_by_desc(Product::stock());
    /// ```
    pub fn order_by_desc<F>(&self, path: KeyPaths<T, F>) -> Vec<T>
    where
        F: Ord + Clone + 'static,
    {
        let mut results: Vec<T> = self
            .data
            .iter()
            .filter(|item| self.filters.iter().all(|f| f(item)))
            .cloned()
            .collect();

        results.sort_by(|a, b| {
            let a_val = path.get(a).cloned();
            let b_val = path.get(b).cloned();
            b_val.cmp(&a_val)
        });
        results
    }

    /// Orders results by a float field in ascending order.
    /// 
    /// **Note**: This method requires `T: Clone` as it creates owned sorted copies.
    ///
    /// # Arguments
    ///
    /// * `path` - The key-path to the f64 field to order by
    ///
    /// # Example
    ///
    /// ```ignore
    /// let sorted = query.order_by_float(Product::price());
    /// ```
    pub fn order_by_float(&self, path: KeyPaths<T, f64>) -> Vec<T> {
        let mut results: Vec<T> = self
            .data
            .iter()
            .filter(|item| self.filters.iter().all(|f| f(item)))
            .cloned()
            .collect();

        results.sort_by(|a, b| {
            let a_val = path.get(a).cloned().unwrap_or(0.0);
            let b_val = path.get(b).cloned().unwrap_or(0.0);
            a_val.partial_cmp(&b_val).unwrap_or(std::cmp::Ordering::Equal)
        });
        results
    }

    /// Orders results by a float field in descending order.
    /// 
    /// **Note**: This method requires `T: Clone` as it creates owned sorted copies.
    ///
    /// # Arguments
    ///
    /// * `path` - The key-path to the f64 field to order by
    ///
    /// # Example
    ///
    /// ```ignore
    /// let sorted = query.order_by_float_desc(Product::rating());
    /// ```
    pub fn order_by_float_desc(&self, path: KeyPaths<T, f64>) -> Vec<T> {
        let mut results: Vec<T> = self
            .data
            .iter()
            .filter(|item| self.filters.iter().all(|f| f(item)))
            .cloned()
            .collect();

        results.sort_by(|a, b| {
            let a_val = path.get(a).cloned().unwrap_or(0.0);
            let b_val = path.get(b).cloned().unwrap_or(0.0);
            b_val.partial_cmp(&a_val).unwrap_or(std::cmp::Ordering::Equal)
        });
        results
    }

    /// Groups results by a field value.
    /// 
    /// **Note**: This method requires `T: Clone` as it creates owned copies in groups.
    ///
    /// # Arguments
    ///
    /// * `path` - The key-path to the field to group by
    ///
    /// # Example
    ///
    /// ```ignore
    /// let by_category = query.group_by(Product::category());
    /// ```
    pub fn group_by<F>(&self, path: KeyPaths<T, F>) -> HashMap<F, Vec<T>>
    where
        F: Eq + std::hash::Hash + Clone + 'static,
    {
        let mut groups: HashMap<F, Vec<T>> = HashMap::new();

        for item in self.data.iter() {
            if self.filters.iter().all(|f| f(item)) {
                if let Some(key) = path.get(item).cloned() {
                    groups.entry(key).or_insert_with(Vec::new).push(item.clone());
                }
            }
        }

        groups
    }

    // ============================================================================
    // i64 DateTime Aggregators (Unix timestamps in milliseconds)
    // ============================================================================

    /// Finds the minimum i64 timestamp value.
    ///
    /// # Arguments
    ///
    /// * `path` - The key-path to the i64 timestamp field
    ///
    /// # Example
    ///
    /// ```ignore
    /// let earliest = query.min_timestamp(Event::created_at());
    /// ```
    #[cfg(feature = "datetime")]
    pub fn min_timestamp(&self, path: KeyPaths<T, i64>) -> Option<i64> {
        self.data
            .iter()
            .filter(|item| self.filters.iter().all(|f| f(item)))
            .filter_map(|item| path.get(item).cloned())
            .min()
    }

    /// Finds the maximum i64 timestamp value.
    ///
    /// # Arguments
    ///
    /// * `path` - The key-path to the i64 timestamp field
    ///
    /// # Example
    ///
    /// ```ignore
    /// let latest = query.max_timestamp(Event::created_at());
    /// ```
    #[cfg(feature = "datetime")]
    pub fn max_timestamp(&self, path: KeyPaths<T, i64>) -> Option<i64> {
        self.data
            .iter()
            .filter(|item| self.filters.iter().all(|f| f(item)))
            .filter_map(|item| path.get(item).cloned())
            .max()
    }

    /// Calculates the average of i64 timestamp values.
    ///
    /// # Arguments
    ///
    /// * `path` - The key-path to the i64 timestamp field
    ///
    /// # Example
    ///
    /// ```ignore
    /// let avg_timestamp = query.avg_timestamp(Event::created_at()).unwrap_or(0);
    /// ```
    #[cfg(feature = "datetime")]
    pub fn avg_timestamp(&self, path: KeyPaths<T, i64>) -> Option<i64> {
        let items: Vec<i64> = self
            .data
            .iter()
            .filter(|item| self.filters.iter().all(|f| f(item)))
            .filter_map(|item| path.get(item).cloned())
            .collect();

        if items.is_empty() {
            None
        } else {
            Some(items.iter().sum::<i64>() / items.len() as i64)
        }
    }

    /// Calculates the sum of i64 timestamp values.
    ///
    /// # Arguments
    ///
    /// * `path` - The key-path to the i64 timestamp field
    ///
    /// # Example
    ///
    /// ```ignore
    /// let total_timestamp = query.sum_timestamp(Event::created_at());
    /// ```
    #[cfg(feature = "datetime")]
    pub fn sum_timestamp(&self, path: KeyPaths<T, i64>) -> i64 {
        self.data
            .iter()
            .filter(|item| self.filters.iter().all(|f| f(item)))
            .filter_map(|item| path.get(item).cloned())
            .sum()
    }

    /// Counts the number of non-null i64 timestamp values.
    ///
    /// # Arguments
    ///
    /// * `path` - The key-path to the i64 timestamp field
    ///
    /// # Example
    ///
    /// ```ignore
    /// let timestamp_count = query.count_timestamp(Event::created_at());
    /// ```
    #[cfg(feature = "datetime")]
    pub fn count_timestamp(&self, path: KeyPaths<T, i64>) -> usize {
        self.data
            .iter()
            .filter(|item| self.filters.iter().all(|f| f(item)))
            .filter(|item| path.get(item).is_some())
            .count()
    }

    /// Filters by i64 timestamp being after a reference timestamp.
    ///
    /// # Arguments
    ///
    /// * `path` - The key-path to the i64 timestamp field
    /// * `reference` - The reference timestamp to compare against
    ///
    /// # Example
    ///
    /// ```ignore
    /// let recent = query.where_after_timestamp(Event::created_at(), cutoff_timestamp);
    /// ```
    #[cfg(feature = "datetime")]
    pub fn where_after_timestamp(self, path: KeyPaths<T, i64>, reference: i64) -> Self {
        self.where_(path, move |timestamp| timestamp > &reference)
    }

    /// Filters by i64 timestamp being before a reference timestamp.
    ///
    /// # Arguments
    ///
    /// * `path` - The key-path to the i64 timestamp field
    /// * `reference` - The reference timestamp to compare against
    ///
    /// # Example
    ///
    /// ```ignore
    /// let old = query.where_before_timestamp(Event::created_at(), cutoff_timestamp);
    /// ```
    #[cfg(feature = "datetime")]
    pub fn where_before_timestamp(self, path: KeyPaths<T, i64>, reference: i64) -> Self {
        self.where_(path, move |timestamp| timestamp < &reference)
    }

    /// Filters by i64 timestamp being between two timestamps (inclusive).
    ///
    /// # Arguments
    ///
    /// * `path` - The key-path to the i64 timestamp field
    /// * `start` - The start timestamp
    /// * `end` - The end timestamp
    ///
    /// # Example
    ///
    /// ```ignore
    /// let range = query.where_between_timestamp(Event::created_at(), start_ts, end_ts);
    /// ```
    #[cfg(feature = "datetime")]
    pub fn where_between_timestamp(self, path: KeyPaths<T, i64>, start: i64, end: i64) -> Self {
        self.where_(path, move |timestamp| timestamp >= &start && timestamp <= &end)
    }

    /// Filters by i64 timestamp being within the last N days from now.
    ///
    /// # Arguments
    ///
    /// * `path` - The key-path to the i64 timestamp field
    /// * `days` - Number of days to look back
    ///
    /// # Example
    ///
    /// ```ignore
    /// let recent = query.where_last_days_timestamp(Event::created_at(), 30);
    /// ```
    #[cfg(feature = "datetime")]
    pub fn where_last_days_timestamp(self, path: KeyPaths<T, i64>, days: i64) -> Self {
        let now = chrono::Utc::now().timestamp_millis();
        let cutoff = now - (days * 24 * 60 * 60 * 1000); // Convert days to milliseconds
        self.where_after_timestamp(path, cutoff)
    }

    /// Filters by i64 timestamp being within the next N days from now.
    ///
    /// # Arguments
    ///
    /// * `path` - The key-path to the i64 timestamp field
    /// * `days` - Number of days to look ahead
    ///
    /// # Example
    ///
    /// ```ignore
    /// let upcoming = query.where_next_days_timestamp(Event::scheduled_at(), 7);
    /// ```
    #[cfg(feature = "datetime")]
    pub fn where_next_days_timestamp(self, path: KeyPaths<T, i64>, days: i64) -> Self {
        let now = chrono::Utc::now().timestamp_millis();
        let cutoff = now + (days * 24 * 60 * 60 * 1000); // Convert days to milliseconds
        self.where_before_timestamp(path, cutoff)
    }

    /// Filters by i64 timestamp being within the last N hours from now.
    ///
    /// # Arguments
    ///
    /// * `path` - The key-path to the i64 timestamp field
    /// * `hours` - Number of hours to look back
    ///
    /// # Example
    ///
    /// ```ignore
    /// let recent = query.where_last_hours_timestamp(Event::created_at(), 24);
    /// ```
    #[cfg(feature = "datetime")]
    pub fn where_last_hours_timestamp(self, path: KeyPaths<T, i64>, hours: i64) -> Self {
        let now = chrono::Utc::now().timestamp_millis();
        let cutoff = now - (hours * 60 * 60 * 1000); // Convert hours to milliseconds
        self.where_after_timestamp(path, cutoff)
    }

    /// Filters by i64 timestamp being within the next N hours from now.
    ///
    /// # Arguments
    ///
    /// * `path` - The key-path to the i64 timestamp field
    /// * `hours` - Number of hours to look ahead
    ///
    /// # Example
    ///
    /// ```ignore
    /// let upcoming = query.where_next_hours_timestamp(Event::scheduled_at(), 2);
    /// ```
    #[cfg(feature = "datetime")]
    pub fn where_next_hours_timestamp(self, path: KeyPaths<T, i64>, hours: i64) -> Self {
        let now = chrono::Utc::now().timestamp_millis();
        let cutoff = now + (hours * 60 * 60 * 1000); // Convert hours to milliseconds
        self.where_before_timestamp(path, cutoff)
    }

    /// Filters by i64 timestamp being within the last N minutes from now.
    ///
    /// # Arguments
    ///
    /// * `path` - The key-path to the i64 timestamp field
    /// * `minutes` - Number of minutes to look back
    ///
    /// # Example
    ///
    /// ```ignore
    /// let recent = query.where_last_minutes_timestamp(Event::created_at(), 60);
    /// ```
    #[cfg(feature = "datetime")]
    pub fn where_last_minutes_timestamp(self, path: KeyPaths<T, i64>, minutes: i64) -> Self {
        let now = chrono::Utc::now().timestamp_millis();
        let cutoff = now - (minutes * 60 * 1000); // Convert minutes to milliseconds
        self.where_after_timestamp(path, cutoff)
    }

    /// Filters by i64 timestamp being within the next N minutes from now.
    ///
    /// # Arguments
    ///
    /// * `path` - The key-path to the i64 timestamp field
    /// * `minutes` - Number of minutes to look ahead
    ///
    /// # Example
    ///
    /// ```ignore
    /// let upcoming = query.where_next_minutes_timestamp(Event::scheduled_at(), 30);
    /// ```
    #[cfg(feature = "datetime")]
    pub fn where_next_minutes_timestamp(self, path: KeyPaths<T, i64>, minutes: i64) -> Self {
        let now = chrono::Utc::now().timestamp_millis();
        let cutoff = now + (minutes * 60 * 1000); // Convert minutes to milliseconds
        self.where_before_timestamp(path, cutoff)
    }

    /// Orders results by i64 timestamp in ascending order (oldest first).
    ///
    /// # Arguments
    ///
    /// * `path` - The key-path to the i64 timestamp field
    ///
    /// # Example
    ///
    /// ```ignore
    /// let sorted = query.order_by_timestamp(Event::created_at());
    /// ```
    #[cfg(feature = "datetime")]
    pub fn order_by_timestamp(&self, path: KeyPaths<T, i64>) -> Vec<T> {
        let mut results: Vec<T> = self
            .data
            .iter()
            .filter(|item| self.filters.iter().all(|f| f(item)))
            .cloned()
            .collect();

        results.sort_by(|a, b| {
            let a_val = path.get(a).cloned().unwrap_or(0);
            let b_val = path.get(b).cloned().unwrap_or(0);
            a_val.cmp(&b_val)
        });
        results
    }

    /// Orders results by i64 timestamp in descending order (newest first).
    ///
    /// # Arguments
    ///
    /// * `path` - The key-path to the i64 timestamp field
    ///
    /// # Example
    ///
    /// ```ignore
    /// let sorted = query.order_by_timestamp_desc(Event::created_at());
    /// ```
    #[cfg(feature = "datetime")]
    pub fn order_by_timestamp_desc(&self, path: KeyPaths<T, i64>) -> Vec<T> {
        let mut results: Vec<T> = self
            .data
            .iter()
            .filter(|item| self.filters.iter().all(|f| f(item)))
            .cloned()
            .collect();

        results.sort_by(|a, b| {
            let a_val = path.get(a).cloned().unwrap_or(0);
            let b_val = path.get(b).cloned().unwrap_or(0);
            b_val.cmp(&a_val)
        });
        results
    }
}

/// Helper struct for pagination after a skip operation.
///
/// Created by calling `skip()` on a `Query`.
pub struct QueryWithSkip<'a, 'b, T: 'static> {
    query: &'b Query<'a, T>,
    offset: usize,
}

impl<'a, 'b, T: 'static> QueryWithSkip<'a, 'b, T> {
    /// Returns up to `n` items after skipping the offset.
    ///
    /// # Arguments
    ///
    /// * `n` - The maximum number of items to return
    ///
    /// # Example
    ///
    /// ```ignore
    /// let page_2 = query.skip(20).limit(10);
    /// ```
    pub fn limit(&self, n: usize) -> Vec<&'a T> {
        self.query
            .data
            .iter()
            .filter(|item| self.query.filters.iter().all(|f| f(item)))
            .skip(self.offset)
            .take(n)
            .collect()
    }
}

    // Parallel operations (only available with parallel feature)
    #[cfg(feature = "parallel")]
    impl<'a, T: 'static + Send + Sync> Query<'a, T> {
    /// Get all items using parallel processing.
    /// Note: This method ignores filters for thread safety.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let results = query.all_parallel();
    /// ```
    pub fn all_parallel(&self) -> Vec<&'a T> {
        use rayon::prelude::*;
        self.data.par_iter().collect()
    }

    /// Count all items using parallel processing.
    /// Note: This method ignores filters for thread safety.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let count = query.count_parallel();
    /// ```
    pub fn count_parallel(&self) -> usize {
        use rayon::prelude::*;
        self.data.par_iter().count()
    }

    /// Check if any items exist using parallel processing.
    /// Note: This method ignores filters for thread safety.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let exists = query.exists_parallel();
    /// ```
    pub fn exists_parallel(&self) -> bool {
        use rayon::prelude::*;
        self.data.par_iter().any(|_| true)
    }

    /// Find minimum value using parallel processing.
    /// Note: This method ignores filters for thread safety.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let min = query.min_parallel(Product::price());
    /// ```
    pub fn min_parallel<F>(&self, path: KeyPaths<T, F>) -> Option<F>
    where
        F: Ord + Clone + 'static + Send + Sync,
    {
        use rayon::prelude::*;
        self.data
            .par_iter()
            .filter_map(|item| path.get(item).cloned())
            .min()
    }

    /// Find maximum value using parallel processing.
    /// Note: This method ignores filters for thread safety.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let max = query.max_parallel(Product::price());
    /// ```
    pub fn max_parallel<F>(&self, path: KeyPaths<T, F>) -> Option<F>
    where
        F: Ord + Clone + 'static + Send + Sync,
    {
        use rayon::prelude::*;
        self.data
            .par_iter()
            .filter_map(|item| path.get(item).cloned())
            .max()
    }

    /// Compute sum using parallel processing.
    /// Note: This method ignores filters for thread safety.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let sum = query.sum_parallel(Product::price());
    /// ```
    pub fn sum_parallel<F>(&self, path: KeyPaths<T, F>) -> F
    where
        F: Clone + std::ops::Add<Output = F> + Default + 'static + Send + Sync + std::iter::Sum,
    {
        use rayon::prelude::*;
        self.data
            .par_iter()
            .filter_map(|item| path.get(item).cloned())
            .sum()
    }

    /// Compute average using parallel processing.
    /// Note: This method ignores filters for thread safety.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let avg = query.avg_parallel(Product::price());
    /// ```
    pub fn avg_parallel(&self, path: KeyPaths<T, f64>) -> Option<f64> {
        use rayon::prelude::*;
        let items: Vec<f64> = self.data
            .par_iter()
            .filter_map(|item| path.get(item).cloned())
            .collect();

        if items.is_empty() {
            None
        } else {
            Some(items.par_iter().sum::<f64>() / items.len() as f64)
        }
    }

    /// Find minimum i64 timestamp using parallel processing.
    /// Note: This method ignores filters for thread safety.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let earliest = query.min_timestamp_parallel(Event::created_at());
    /// ```
    pub fn min_timestamp_parallel(&self, path: KeyPaths<T, i64>) -> Option<i64> {
        use rayon::prelude::*;
        self.data
            .par_iter()
            .filter_map(|item| path.get(item).cloned())
            .min()
    }

    /// Find maximum i64 timestamp using parallel processing.
    /// Note: This method ignores filters for thread safety.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let latest = query.max_timestamp_parallel(Event::created_at());
    /// ```
    pub fn max_timestamp_parallel(&self, path: KeyPaths<T, i64>) -> Option<i64> {
        use rayon::prelude::*;
        self.data
            .par_iter()
            .filter_map(|item| path.get(item).cloned())
            .max()
    }

    /// Compute average i64 timestamp using parallel processing.
    /// Note: This method ignores filters for thread safety.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let avg = query.avg_timestamp_parallel(Event::created_at());
    /// ```
    pub fn avg_timestamp_parallel(&self, path: KeyPaths<T, i64>) -> Option<i64> {
        use rayon::prelude::*;
        let items: Vec<i64> = self.data
            .par_iter()
            .filter_map(|item| path.get(item).cloned())
            .collect();

        if items.is_empty() {
            None
        } else {
            Some(items.par_iter().sum::<i64>() / items.len() as i64)
        }
    }

    /// Compute sum of i64 timestamps using parallel processing.
    /// Note: This method ignores filters for thread safety.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let total = query.sum_timestamp_parallel(Event::created_at());
    /// ```
    pub fn sum_timestamp_parallel(&self, path: KeyPaths<T, i64>) -> i64 {
        use rayon::prelude::*;
        self.data
            .par_iter()
            .filter_map(|item| path.get(item).cloned())
            .sum()
    }

    /// Count i64 timestamps using parallel processing.
    /// Note: This method ignores filters for thread safety.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let count = query.count_timestamp_parallel(Event::created_at());
    /// ```
    pub fn count_timestamp_parallel(&self, path: KeyPaths<T, i64>) -> usize {
        use rayon::prelude::*;
        self.data
            .par_iter()
            .filter(|item| path.get(item).is_some())
            .count()
    }
}