type-bridge-orm 1.5.0

Async ORM for TypeDB built on type-bridge-core-lib
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
//! Integration tests for `EntityQuery` and `RelationQuery` using a mock backend.

use std::sync::{Arc, Mutex};

use type_bridge_orm::*;

// ── Test entity ──────────────────────────────────────────────────────

define_attribute!(Name, "name", "string");
define_attribute!(Age, "age", "long");
define_attribute!(Score, "score", "double");

#[derive(Debug)]
struct Person {
    iid: Option<String>,
    name: Name,
    age: Age,
}

impl TypeBridgeEntity for Person {
    const TYPE_NAME: &'static str = "person";

    fn owned_attributes() -> &'static [OwnedAttributeInfo] {
        &[
            OwnedAttributeInfo {
                attr_name: "name",
                value_type: ValueType::String,
                annotations: &[Annotation::Key],
            },
            OwnedAttributeInfo {
                attr_name: "age",
                value_type: ValueType::Long,
                annotations: &[],
            },
        ]
    }

    fn iid(&self) -> Option<&str> {
        self.iid.as_deref()
    }

    fn set_iid(&mut self, iid: String) {
        self.iid = Some(iid);
    }

    fn to_attribute_values(&self) -> Vec<(&'static str, AttributeValue)> {
        vec![("name", self.name.to_value()), ("age", self.age.to_value())]
    }

    fn from_document(doc: &serde_json::Map<String, serde_json::Value>) -> Result<Self> {
        let name = doc
            .get("name")
            .and_then(|v| v.as_str())
            .ok_or_else(|| OrmError::Hydration {
                type_name: "person".into(),
                message: "missing name".into(),
            })?;
        let age = doc
            .get("age")
            .and_then(|v| v.as_i64())
            .ok_or_else(|| OrmError::Hydration {
                type_name: "person".into(),
                message: "missing age".into(),
            })?;
        Ok(Person {
            iid: None,
            name: Name(name.to_string()),
            age: Age(age),
        })
    }
}

// ── Test relation ──────────────────────────────────────────────────────

define_attribute!(Since, "since", "string");

#[derive(Debug)]
struct Friendship {
    iid: Option<String>,
    since: Since,
}

impl TypeBridgeRelation for Friendship {
    const TYPE_NAME: &'static str = "friendship";

    fn owned_attributes() -> &'static [OwnedAttributeInfo] {
        &[OwnedAttributeInfo {
            attr_name: "since",
            value_type: ValueType::String,
            annotations: &[],
        }]
    }

    fn role_info() -> &'static [RoleInfo] {
        &[
            RoleInfo {
                role_name: "friend",
                player_type_name: "person",
            },
            RoleInfo {
                role_name: "friend",
                player_type_name: "person",
            },
        ]
    }

    fn iid(&self) -> Option<&str> {
        self.iid.as_deref()
    }

    fn set_iid(&mut self, iid: String) {
        self.iid = Some(iid);
    }

    fn to_attribute_values(&self) -> Vec<(&'static str, AttributeValue)> {
        vec![("since", self.since.to_value())]
    }

    fn to_role_player_refs(&self) -> Vec<RolePlayerRef> {
        vec![]
    }

    fn from_document(doc: &serde_json::Map<String, serde_json::Value>) -> Result<Self> {
        let since =
            doc.get("since")
                .and_then(|v| v.as_str())
                .ok_or_else(|| OrmError::Hydration {
                    type_name: "friendship".into(),
                    message: "missing since".into(),
                })?;
        Ok(Friendship {
            iid: None,
            since: Since(since.to_string()),
        })
    }
}

// ── Mock backend ─────────────────────────────────────────────────────

use type_bridge_orm::session::backend::{BoxFuture, DriverBackend, QueryResult, TransactionOps};

/// Records queries and returns pre-configured results.
struct MockBackend {
    responses: Arc<Mutex<Vec<QueryResult>>>,
    queries: Arc<Mutex<Vec<String>>>,
}

impl MockBackend {
    fn new(responses: Vec<QueryResult>) -> Self {
        Self {
            responses: Arc::new(Mutex::new(responses)),
            queries: Arc::new(Mutex::new(Vec::new())),
        }
    }
}

impl DriverBackend for MockBackend {
    fn open_transaction(
        &self,
        _database: &str,
        _tx_type: TxType,
    ) -> BoxFuture<'_, std::result::Result<Box<dyn TransactionOps>, OrmError>> {
        let responses = Arc::clone(&self.responses);
        let queries = Arc::clone(&self.queries);
        Box::pin(async move {
            Ok(Box::new(MockTransaction { responses, queries }) as Box<dyn TransactionOps>)
        })
    }

    fn is_open(&self) -> bool {
        true
    }
}

struct MockTransaction {
    responses: Arc<Mutex<Vec<QueryResult>>>,
    queries: Arc<Mutex<Vec<String>>>,
}

impl TransactionOps for MockTransaction {
    fn query(&mut self, typeql: &str) -> BoxFuture<'_, std::result::Result<QueryResult, OrmError>> {
        self.queries.lock().unwrap().push(typeql.to_string());
        let result = self
            .responses
            .lock()
            .unwrap()
            .pop()
            .unwrap_or(QueryResult::Ok);
        Box::pin(async move { Ok(result) })
    }

    fn commit(&mut self) -> BoxFuture<'_, std::result::Result<(), OrmError>> {
        Box::pin(async { Ok(()) })
    }

    fn rollback(&mut self) -> BoxFuture<'_, std::result::Result<(), OrmError>> {
        Box::pin(async { Ok(()) })
    }

    fn close(&mut self) -> BoxFuture<'_, std::result::Result<(), OrmError>> {
        Box::pin(async { Ok(()) })
    }
}

// ── Helper ──────────────────────────────────────────────────────────

fn person_doc(name: &str, age: i64) -> serde_json::Value {
    serde_json::json!({
        "_iid": format!("0x{name}"),
        "attributes": {
            "name": [{"value": name}],
            "age": [{"value": age}]
        }
    })
}

fn friendship_doc(since: &str) -> serde_json::Value {
    serde_json::json!({
        "_iid": format!("0xfr_{since}"),
        "attributes": {
            "since": [{"value": since}]
        }
    })
}

// ── EntityQuery tests ────────────────────────────────────────────────

#[tokio::test]
async fn query_with_gt_filter() {
    let backend = MockBackend::new(vec![QueryResult::Documents(vec![person_doc("Alice", 30)])]);
    let queries = Arc::clone(&backend.queries);
    let db = Database::with_backend(Box::new(backend), "testdb");

    let manager = EntityManager::<Person>::new(&db);
    let _ = manager
        .query()
        .filter(Expr::gt("age", AttributeValue::Long(18)))
        .execute()
        .await
        .unwrap();

    let recorded = queries.lock().unwrap();
    let q = &recorded[0];
    assert!(q.contains("has age"), "should contain 'has age': {q}");
    assert!(q.contains("> 18"), "should contain '> 18': {q}");
}

#[tokio::test]
async fn query_with_string_contains() {
    let backend = MockBackend::new(vec![QueryResult::Documents(vec![person_doc("Alice", 30)])]);
    let queries = Arc::clone(&backend.queries);
    let db = Database::with_backend(Box::new(backend), "testdb");

    let manager = EntityManager::<Person>::new(&db);
    let _ = manager
        .query()
        .filter(Expr::contains("name", "Ali"))
        .execute()
        .await
        .unwrap();

    let recorded = queries.lock().unwrap();
    let q = &recorded[0];
    assert!(q.contains("has name"), "should contain 'has name': {q}");
    assert!(
        q.contains(r#"contains "Ali""#),
        "should contain 'contains \"Ali\"': {q}"
    );
}

#[tokio::test]
async fn query_with_and_expression() {
    let backend = MockBackend::new(vec![QueryResult::Documents(vec![person_doc("Alice", 30)])]);
    let queries = Arc::clone(&backend.queries);
    let db = Database::with_backend(Box::new(backend), "testdb");

    let manager = EntityManager::<Person>::new(&db);
    let _ = manager
        .query()
        .filter(Expr::And(vec![
            Expr::gte("age", AttributeValue::Long(18)),
            Expr::lte("age", AttributeValue::Long(65)),
        ]))
        .execute()
        .await
        .unwrap();

    let recorded = queries.lock().unwrap();
    let q = &recorded[0];
    assert!(q.contains(">= 18"), "should contain '>= 18': {q}");
    assert!(q.contains("<= 65"), "should contain '<= 65': {q}");
}

#[tokio::test]
async fn query_with_or_expression() {
    let backend = MockBackend::new(vec![QueryResult::Documents(vec![person_doc("Alice", 30)])]);
    let queries = Arc::clone(&backend.queries);
    let db = Database::with_backend(Box::new(backend), "testdb");

    let manager = EntityManager::<Person>::new(&db);
    let _ = manager
        .query()
        .filter(Expr::Or(vec![
            Expr::eq("name", AttributeValue::String("Alice".into())),
            Expr::eq("name", AttributeValue::String("Bob".into())),
        ]))
        .execute()
        .await
        .unwrap();

    let recorded = queries.lock().unwrap();
    let q = &recorded[0];
    assert!(q.contains("or"), "should contain 'or': {q}");
}

#[tokio::test]
async fn query_with_not_expression() {
    let backend = MockBackend::new(vec![QueryResult::Documents(vec![person_doc("Alice", 30)])]);
    let queries = Arc::clone(&backend.queries);
    let db = Database::with_backend(Box::new(backend), "testdb");

    let manager = EntityManager::<Person>::new(&db);
    let _ = manager
        .query()
        .filter(Expr::not(Expr::eq(
            "name",
            AttributeValue::String("Bob".into()),
        )))
        .execute()
        .await
        .unwrap();

    let recorded = queries.lock().unwrap();
    let q = &recorded[0];
    assert!(q.contains("not"), "should contain 'not': {q}");
}

#[tokio::test]
async fn query_with_sort() {
    let backend = MockBackend::new(vec![QueryResult::Documents(vec![
        person_doc("Alice", 30),
        person_doc("Bob", 25),
    ])]);
    let queries = Arc::clone(&backend.queries);
    let db = Database::with_backend(Box::new(backend), "testdb");

    let manager = EntityManager::<Person>::new(&db);
    let _ = manager
        .query()
        .order_by("name", SortDir::Asc)
        .execute()
        .await
        .unwrap();

    let recorded = queries.lock().unwrap();
    let q = &recorded[0];
    assert!(q.contains("sort"), "should contain 'sort': {q}");
    assert!(q.contains("asc"), "should contain 'asc': {q}");
}

#[tokio::test]
async fn query_with_limit_offset() {
    let backend = MockBackend::new(vec![QueryResult::Documents(vec![person_doc("Alice", 30)])]);
    let queries = Arc::clone(&backend.queries);
    let db = Database::with_backend(Box::new(backend), "testdb");

    let manager = EntityManager::<Person>::new(&db);
    let _ = manager.query().limit(10).offset(5).execute().await.unwrap();

    let recorded = queries.lock().unwrap();
    let q = &recorded[0];
    assert!(q.contains("limit 10"), "should contain 'limit 10': {q}");
    assert!(q.contains("offset 5"), "should contain 'offset 5': {q}");
}

#[tokio::test]
async fn query_execute_returns_entities() {
    let backend = MockBackend::new(vec![QueryResult::Documents(vec![
        person_doc("Alice", 30),
        person_doc("Bob", 25),
    ])]);
    let db = Database::with_backend(Box::new(backend), "testdb");

    let manager = EntityManager::<Person>::new(&db);
    let people = manager
        .query()
        .filter(Expr::gte("age", AttributeValue::Long(20)))
        .execute()
        .await
        .unwrap();

    assert_eq!(people.len(), 2);
    assert_eq!(people[0].name.0, "Alice");
    assert_eq!(people[1].name.0, "Bob");
}

#[tokio::test]
async fn query_first_returns_single() {
    let backend = MockBackend::new(vec![QueryResult::Documents(vec![person_doc("Alice", 30)])]);
    let queries = Arc::clone(&backend.queries);
    let db = Database::with_backend(Box::new(backend), "testdb");

    let manager = EntityManager::<Person>::new(&db);
    let person = manager
        .query()
        .filter(Expr::eq("name", AttributeValue::String("Alice".into())))
        .first()
        .await
        .unwrap();

    assert!(person.is_some());
    assert_eq!(person.unwrap().name.0, "Alice");

    let recorded = queries.lock().unwrap();
    let q = &recorded[0];
    assert!(q.contains("limit 1"), "first() should set limit 1: {q}");
}

#[tokio::test]
async fn query_first_returns_none_when_empty() {
    let backend = MockBackend::new(vec![QueryResult::Documents(vec![])]);
    let db = Database::with_backend(Box::new(backend), "testdb");

    let manager = EntityManager::<Person>::new(&db);
    let person = manager.query().first().await.unwrap();

    assert!(person.is_none());
}

#[tokio::test]
async fn query_count_returns_value() {
    let backend = MockBackend::new(vec![QueryResult::Rows(vec![
        serde_json::json!({"$count": 42}),
    ])]);
    let queries = Arc::clone(&backend.queries);
    let db = Database::with_backend(Box::new(backend), "testdb");

    let manager = EntityManager::<Person>::new(&db);
    let count = manager
        .query()
        .filter(Expr::gte("age", AttributeValue::Long(18)))
        .count()
        .await
        .unwrap();

    assert_eq!(count, 42);

    let recorded = queries.lock().unwrap();
    let q = &recorded[0];
    assert!(q.contains("reduce"), "should contain 'reduce': {q}");
    assert!(q.contains("count"), "should contain 'count': {q}");
}

#[tokio::test]
async fn query_aggregate_sum() {
    let backend = MockBackend::new(vec![QueryResult::Rows(vec![
        serde_json::json!({"$sum": 1500}),
    ])]);
    let queries = Arc::clone(&backend.queries);
    let db = Database::with_backend(Box::new(backend), "testdb");

    let manager = EntityManager::<Person>::new(&db);
    let result = manager
        .query()
        .aggregate(&[Agg::Sum("age".to_string())])
        .await
        .unwrap();

    assert_eq!(result.get_i64("$sum"), Some(1500));

    let recorded = queries.lock().unwrap();
    let q = &recorded[0];
    assert!(q.contains("sum"), "should contain 'sum': {q}");
    assert!(q.contains("reduce"), "should contain 'reduce': {q}");
}

#[tokio::test]
async fn query_chain_all_modifiers() {
    let backend = MockBackend::new(vec![QueryResult::Documents(vec![person_doc("Alice", 30)])]);
    let queries = Arc::clone(&backend.queries);
    let db = Database::with_backend(Box::new(backend), "testdb");

    let manager = EntityManager::<Person>::new(&db);
    let people = manager
        .query()
        .filter(Expr::gte("age", AttributeValue::Long(18)))
        .filter(Expr::lte("age", AttributeValue::Long(65)))
        .order_by("name", SortDir::Asc)
        .limit(10)
        .offset(20)
        .execute()
        .await
        .unwrap();

    assert_eq!(people.len(), 1);

    let recorded = queries.lock().unwrap();
    let q = &recorded[0];
    assert!(q.contains(">= 18"), "should contain '>= 18': {q}");
    assert!(q.contains("<= 65"), "should contain '<= 65': {q}");
    assert!(q.contains("sort"), "should contain 'sort': {q}");
    assert!(q.contains("limit 10"), "should contain 'limit 10': {q}");
    assert!(q.contains("offset 20"), "should contain 'offset 20': {q}");
}

// ── RelationQuery tests ──────────────────────────────────────────────

#[tokio::test]
async fn relation_query_with_filter() {
    let backend = MockBackend::new(vec![QueryResult::Documents(vec![friendship_doc(
        "2024-01-01",
    )])]);
    let queries = Arc::clone(&backend.queries);
    let db = Database::with_backend(Box::new(backend), "testdb");

    let manager = RelationManager::<Friendship>::new(&db);
    let results = manager
        .query()
        .filter(Expr::eq(
            "since",
            AttributeValue::String("2024-01-01".into()),
        ))
        .execute()
        .await
        .unwrap();

    assert_eq!(results.len(), 1);
    assert_eq!(results[0].since.0, "2024-01-01");

    let recorded = queries.lock().unwrap();
    let q = &recorded[0];
    assert!(q.contains("has since"), "should contain 'has since': {q}");
    assert!(
        q.contains(r#"== "2024-01-01""#),
        "should contain '== \"2024-01-01\"': {q}"
    );
}

#[tokio::test]
async fn relation_query_with_sort_and_limit() {
    let backend = MockBackend::new(vec![QueryResult::Documents(vec![
        friendship_doc("2024-01-01"),
        friendship_doc("2023-06-15"),
    ])]);
    let queries = Arc::clone(&backend.queries);
    let db = Database::with_backend(Box::new(backend), "testdb");

    let manager = RelationManager::<Friendship>::new(&db);
    let _ = manager
        .query()
        .order_by("since", SortDir::Desc)
        .limit(5)
        .execute()
        .await
        .unwrap();

    let recorded = queries.lock().unwrap();
    let q = &recorded[0];
    assert!(q.contains("sort"), "should contain 'sort': {q}");
    assert!(q.contains("desc"), "should contain 'desc': {q}");
    assert!(q.contains("limit 5"), "should contain 'limit 5': {q}");
}

#[tokio::test]
async fn relation_query_count() {
    let backend = MockBackend::new(vec![QueryResult::Rows(vec![
        serde_json::json!({"$count": 7}),
    ])]);
    let db = Database::with_backend(Box::new(backend), "testdb");

    let manager = RelationManager::<Friendship>::new(&db);
    let count = manager.query().count().await.unwrap();

    assert_eq!(count, 7);
}

#[tokio::test]
async fn relation_query_first() {
    let backend = MockBackend::new(vec![QueryResult::Documents(vec![friendship_doc(
        "2024-01-01",
    )])]);
    let queries = Arc::clone(&backend.queries);
    let db = Database::with_backend(Box::new(backend), "testdb");

    let manager = RelationManager::<Friendship>::new(&db);
    let result = manager.query().first().await.unwrap();

    assert!(result.is_some());
    assert_eq!(result.unwrap().since.0, "2024-01-01");

    let recorded = queries.lock().unwrap();
    let q = &recorded[0];
    assert!(q.contains("limit 1"), "first() should set limit 1: {q}");
}

#[tokio::test]
async fn relation_query_aggregate() {
    let backend = MockBackend::new(vec![QueryResult::Rows(vec![
        serde_json::json!({"$count": 10}),
    ])]);
    let queries = Arc::clone(&backend.queries);
    let db = Database::with_backend(Box::new(backend), "testdb");

    let manager = RelationManager::<Friendship>::new(&db);
    let result = manager.query().aggregate(&[Agg::Count]).await.unwrap();

    assert_eq!(result.count(), Some(10));

    let recorded = queries.lock().unwrap();
    let q = &recorded[0];
    assert!(q.contains("reduce"), "should contain 'reduce': {q}");
    assert!(q.contains("count"), "should contain 'count': {q}");
}

#[tokio::test]
async fn query_with_like_filter() {
    let backend = MockBackend::new(vec![QueryResult::Documents(vec![person_doc("Alice", 30)])]);
    let queries = Arc::clone(&backend.queries);
    let db = Database::with_backend(Box::new(backend), "testdb");

    let manager = EntityManager::<Person>::new(&db);
    let _ = manager
        .query()
        .filter(Expr::like("name", "Ali.*"))
        .execute()
        .await
        .unwrap();

    let recorded = queries.lock().unwrap();
    let q = &recorded[0];
    assert!(q.contains("has name"), "should contain 'has name': {q}");
    assert!(
        q.contains(r#"like "Ali.*""#),
        "should contain 'like \"Ali.*\"': {q}"
    );
}

#[tokio::test]
async fn query_multiple_sort_fields() {
    let backend = MockBackend::new(vec![QueryResult::Documents(vec![person_doc("Alice", 30)])]);
    let queries = Arc::clone(&backend.queries);
    let db = Database::with_backend(Box::new(backend), "testdb");

    let manager = EntityManager::<Person>::new(&db);
    let _ = manager
        .query()
        .order_by("age", SortDir::Desc)
        .order_by("name", SortDir::Asc)
        .execute()
        .await
        .unwrap();

    let recorded = queries.lock().unwrap();
    let q = &recorded[0];
    assert!(q.contains("sort"), "should contain 'sort': {q}");
    assert!(q.contains("desc"), "should contain 'desc': {q}");
    assert!(q.contains("asc"), "should contain 'asc': {q}");
}

// ── Range / startswith / endswith tests ────────────────────────────

#[tokio::test]
async fn query_with_in_range() {
    let backend = MockBackend::new(vec![QueryResult::Documents(vec![person_doc("Alice", 30)])]);
    let queries = Arc::clone(&backend.queries);
    let db = Database::with_backend(Box::new(backend), "testdb");

    let manager = EntityManager::<Person>::new(&db);
    let _ = manager
        .query()
        .filter(Expr::in_range(
            "age",
            AttributeValue::Long(20),
            AttributeValue::Long(40),
        ))
        .execute()
        .await
        .unwrap();

    let recorded = queries.lock().unwrap();
    let q = &recorded[0];
    assert!(q.contains(">= 20"), "should contain '>= 20': {q}");
    assert!(q.contains("<= 40"), "should contain '<= 40': {q}");
}

#[tokio::test]
async fn query_with_startswith() {
    let backend = MockBackend::new(vec![QueryResult::Documents(vec![person_doc("Alice", 30)])]);
    let queries = Arc::clone(&backend.queries);
    let db = Database::with_backend(Box::new(backend), "testdb");

    let manager = EntityManager::<Person>::new(&db);
    let _ = manager
        .query()
        .filter(Expr::startswith("name", "Ali"))
        .execute()
        .await
        .unwrap();

    let recorded = queries.lock().unwrap();
    let q = &recorded[0];
    assert!(q.contains("has name"), "should contain 'has name': {q}");
    assert!(
        q.contains(r#"like "^Ali.*""#),
        "should contain 'like \"^Ali.*\"': {q}"
    );
}

#[tokio::test]
async fn query_with_endswith() {
    let backend = MockBackend::new(vec![QueryResult::Documents(vec![person_doc("Alice", 30)])]);
    let queries = Arc::clone(&backend.queries);
    let db = Database::with_backend(Box::new(backend), "testdb");

    let manager = EntityManager::<Person>::new(&db);
    let _ = manager
        .query()
        .filter(Expr::endswith("name", "ice"))
        .execute()
        .await
        .unwrap();

    let recorded = queries.lock().unwrap();
    let q = &recorded[0];
    assert!(q.contains("has name"), "should contain 'has name': {q}");
    assert!(
        q.contains(r#"like ".*ice$""#),
        "should contain 'like \".*ice$\"': {q}"
    );
}

// ── Group-by tests ──────────────────────────────────────────────────

#[tokio::test]
async fn entity_group_by_aggregate() {
    let backend = MockBackend::new(vec![QueryResult::Rows(vec![
        serde_json::json!({"$group0": "Engineering", "$mean": 35.5}),
        serde_json::json!({"$group0": "Sales", "$mean": 28.3}),
    ])]);
    let queries = Arc::clone(&backend.queries);
    let db = Database::with_backend(Box::new(backend), "testdb");

    let manager = EntityManager::<Person>::new(&db);
    let result = manager
        .query()
        .group_by("department")
        .aggregate(&[Agg::Mean("age".into())])
        .await
        .unwrap();

    assert_eq!(result.len(), 2);
    assert_eq!(
        result.get_by_str("Engineering").unwrap().get_f64("$mean"),
        Some(35.5)
    );
    assert_eq!(
        result.get_by_str("Sales").unwrap().get_f64("$mean"),
        Some(28.3)
    );

    let recorded = queries.lock().unwrap();
    let q = &recorded[0];
    assert!(q.contains("groupby"), "should contain 'groupby': {q}");
    assert!(q.contains("$group0"), "should contain '$group0': {q}");
    assert!(
        q.contains("has department"),
        "should contain 'has department': {q}"
    );
    assert!(q.contains("mean"), "should contain 'mean': {q}");
}

#[tokio::test]
async fn entity_group_by_with_filter() {
    let backend = MockBackend::new(vec![QueryResult::Rows(vec![
        serde_json::json!({"$group0": "Engineering", "$count": 5}),
    ])]);
    let queries = Arc::clone(&backend.queries);
    let db = Database::with_backend(Box::new(backend), "testdb");

    let manager = EntityManager::<Person>::new(&db);
    let result = manager
        .query()
        .filter(Expr::gte("age", AttributeValue::Long(18)))
        .group_by("department")
        .aggregate(&[Agg::Count])
        .await
        .unwrap();

    assert_eq!(result.len(), 1);
    assert_eq!(result.get_by_str("Engineering").unwrap().count(), Some(5));

    let recorded = queries.lock().unwrap();
    let q = &recorded[0];
    assert!(q.contains(">= 18"), "should contain '>= 18': {q}");
    assert!(q.contains("groupby"), "should contain 'groupby': {q}");
}

#[tokio::test]
async fn relation_group_by_aggregate() {
    let backend = MockBackend::new(vec![QueryResult::Rows(vec![
        serde_json::json!({"$group0": "2024", "$count": 3}),
    ])]);
    let queries = Arc::clone(&backend.queries);
    let db = Database::with_backend(Box::new(backend), "testdb");

    let manager = RelationManager::<Friendship>::new(&db);
    let result = manager
        .query()
        .group_by("since")
        .aggregate(&[Agg::Count])
        .await
        .unwrap();

    assert_eq!(result.len(), 1);
    assert_eq!(result.get_by_str("2024").unwrap().count(), Some(3));

    let recorded = queries.lock().unwrap();
    let q = &recorded[0];
    assert!(q.contains("groupby"), "should contain 'groupby': {q}");
}

// ── Role player filter tests ────────────────────────────────────────

#[tokio::test]
async fn relation_query_with_role_player_filter() {
    let backend = MockBackend::new(vec![QueryResult::Documents(vec![friendship_doc(
        "2024-01-01",
    )])]);
    let queries = Arc::clone(&backend.queries);
    let db = Database::with_backend(Box::new(backend), "testdb");

    let manager = RelationManager::<Friendship>::new(&db);
    let _ = manager
        .query()
        .filter(Expr::role_player(
            "friend",
            Expr::gt("age", AttributeValue::Long(30)),
        ))
        .execute()
        .await
        .unwrap();

    let recorded = queries.lock().unwrap();
    let q = &recorded[0];
    // Should bind role player in the relation pattern
    assert!(
        q.contains("friend: $friend"),
        "should contain role binding 'friend: $friend': {q}"
    );
    // Inner expression should target the role player variable
    assert!(
        q.contains("$friend has age"),
        "should contain '$friend has age': {q}"
    );
    assert!(q.contains("> 30"), "should contain '> 30': {q}");
}

#[tokio::test]
async fn relation_query_with_multiple_role_player_filters() {
    let backend = MockBackend::new(vec![QueryResult::Documents(vec![friendship_doc(
        "2024-01-01",
    )])]);
    let queries = Arc::clone(&backend.queries);
    let db = Database::with_backend(Box::new(backend), "testdb");

    let manager = RelationManager::<Friendship>::new(&db);
    let _ = manager
        .query()
        .filter(Expr::role_player(
            "friend",
            Expr::gt("age", AttributeValue::Long(18)),
        ))
        .filter(Expr::eq(
            "since",
            AttributeValue::String("2024-01-01".into()),
        ))
        .execute()
        .await
        .unwrap();

    let recorded = queries.lock().unwrap();
    let q = &recorded[0];
    assert!(
        q.contains("friend: $friend"),
        "should bind role player: {q}"
    );
    assert!(
        q.contains("$friend has age"),
        "role player filter should target $friend: {q}"
    );
    // Also has a direct relation attribute filter
    assert!(q.contains("has since"), "should have direct filter: {q}");
}