rustrails-record 0.1.2

ORM layer (ActiveRecord equivalent)
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
use std::collections::HashMap;

use sea_orm::{ColumnTrait, DatabaseConnection, EntityTrait, FromQueryResult, Iterable};
use serde_json::{Value, json};

use crate::{Record, RecordError, Relation};

/// Sort direction for ordered record queries.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OrderDirection {
    /// Sort in ascending order.
    Asc,
    /// Sort in descending order.
    Desc,
}

/// Async query helpers for [`Record`] types. Use `Querying` for the sync API.
#[allow(async_fn_in_trait, dead_code)]
pub(crate) trait AsyncQuerying: Record {
    /// Finds a record by primary key or returns [`RecordError::NotFound`].
    async fn find(id: i64, db: &DatabaseConnection) -> Result<Self, RecordError>
    where
        <Self::Entity as EntityTrait>::Column: ColumnTrait + Iterable,
    {
        Self::find_by_id(id, db).await?.ok_or(RecordError::NotFound)
    }

    /// Finds a record by primary key and returns `None` when missing.
    async fn find_by_id(id: i64, db: &DatabaseConnection) -> Result<Option<Self>, RecordError>
    where
        <Self::Entity as EntityTrait>::Column: ColumnTrait + Iterable,
    {
        let mut conditions = HashMap::new();
        conditions.insert(Self::primary_key_name().to_owned(), json!(id));
        Self::r#where(conditions).first(db).await
    }

    /// Finds the first record matching the provided conditions.
    async fn find_by(
        conditions: HashMap<String, Value>,
        db: &DatabaseConnection,
    ) -> Result<Option<Self>, RecordError>
    where
        <Self::Entity as EntityTrait>::Column: ColumnTrait + Iterable,
    {
        Self::r#where(conditions).first(db).await
    }

    /// Finds the first record matching the provided conditions or returns [`RecordError::NotFound`].
    async fn find_by_bang(
        conditions: HashMap<String, Value>,
        db: &DatabaseConnection,
    ) -> Result<Self, RecordError>
    where
        <Self::Entity as EntityTrait>::Column: ColumnTrait + Iterable,
    {
        Self::find_by(conditions, db)
            .await?
            .ok_or(RecordError::NotFound)
    }

    /// Returns one record without imposing an explicit order.
    async fn take(db: &DatabaseConnection) -> Result<Option<Self>, RecordError>
    where
        <Self::Entity as EntityTrait>::Column: ColumnTrait + Iterable,
    {
        Relation::<Self>::new().first(db).await
    }

    /// Returns one record without imposing an explicit order or raises when none exist.
    async fn take_bang(db: &DatabaseConnection) -> Result<Self, RecordError>
    where
        <Self::Entity as EntityTrait>::Column: ColumnTrait + Iterable,
    {
        Self::take(db).await?.ok_or(RecordError::NotFound)
    }

    /// Returns the only matching row.
    async fn sole(db: &DatabaseConnection) -> Result<Self, RecordError>
    where
        <Self::Entity as EntityTrait>::Column: ColumnTrait + Iterable,
    {
        Relation::<Self>::new().sole(db).await
    }

    /// Returns the only matching row for the provided conditions.
    async fn find_sole_by(
        conditions: HashMap<String, Value>,
        db: &DatabaseConnection,
    ) -> Result<Self, RecordError>
    where
        <Self::Entity as EntityTrait>::Column: ColumnTrait + Iterable,
    {
        Self::r#where(conditions).sole(db).await
    }

    /// Plucks the requested column from matching rows.
    async fn pluck(column: &str, db: &DatabaseConnection) -> Result<Vec<Value>, RecordError>
    where
        Self: serde::Serialize,
        <Self::Entity as EntityTrait>::Column: ColumnTrait + Iterable,
    {
        Relation::<Self>::new().pluck(column, db).await
    }

    /// Picks the first value for the requested column.
    async fn pick(column: &str, db: &DatabaseConnection) -> Result<Option<Value>, RecordError>
    where
        Self: serde::Serialize,
        <Self::Entity as EntityTrait>::Column: ColumnTrait + Iterable,
    {
        Relation::<Self>::new().pick(column, db).await
    }

    /// Returns all primary key values.
    async fn ids(db: &DatabaseConnection) -> Result<Vec<i64>, RecordError>
    where
        Self: serde::Serialize,
        <Self::Entity as EntityTrait>::Column: ColumnTrait + Iterable,
    {
        Relation::<Self>::new().ids(db).await
    }

    /// Loads all records for the entity.
    async fn all(db: &DatabaseConnection) -> Result<Vec<Self>, RecordError>
    where
        <Self::Entity as EntityTrait>::Column: ColumnTrait + Iterable,
    {
        Relation::<Self>::new().load(db).await
    }

    /// Loads the first record ordered by primary key ascending.
    async fn first(db: &DatabaseConnection) -> Result<Option<Self>, RecordError>
    where
        <Self::Entity as EntityTrait>::Column: ColumnTrait + Iterable,
    {
        Self::order(Self::primary_key_name(), OrderDirection::Asc)
            .first(db)
            .await
    }

    /// Loads the last record ordered by primary key descending.
    async fn last(db: &DatabaseConnection) -> Result<Option<Self>, RecordError>
    where
        <Self::Entity as EntityTrait>::Column: ColumnTrait + Iterable,
    {
        Self::order(Self::primary_key_name(), OrderDirection::Desc)
            .first(db)
            .await
    }

    /// Counts all rows for the entity.
    async fn count(db: &DatabaseConnection) -> Result<u64, RecordError>
    where
        <Self::Entity as EntityTrait>::Column: ColumnTrait + Iterable,
        <Self::Entity as EntityTrait>::Model: FromQueryResult + Send + Sync,
    {
        Relation::<Self>::new().count(db).await
    }

    /// Returns `true` when any record matches the provided conditions.
    async fn exists_with_conditions(
        conditions: HashMap<String, Value>,
        db: &DatabaseConnection,
    ) -> Result<bool, RecordError>
    where
        <Self::Entity as EntityTrait>::Column: ColumnTrait + Iterable,
    {
        Self::r#where(conditions).exists(db).await
    }

    /// Returns `true` when any record matches the provided conditions.
    async fn exists(
        conditions: HashMap<String, Value>,
        db: &DatabaseConnection,
    ) -> Result<bool, RecordError>
    where
        <Self::Entity as EntityTrait>::Column: ColumnTrait + Iterable,
    {
        Self::exists_with_conditions(conditions, db).await
    }

    /// Starts a relation scoped by equality conditions.
    fn r#where(conditions: HashMap<String, Value>) -> Relation<Self> {
        Relation::new().r#where(conditions)
    }

    /// Starts a relation scoped by ordering.
    fn order(column: &str, dir: OrderDirection) -> Relation<Self> {
        Relation::new().order(column, dir)
    }

    /// Starts a relation scoped by a limit.
    fn limit(n: u64) -> Relation<Self> {
        Relation::new().limit(n)
    }

    /// Starts a relation scoped by an offset.
    fn offset(n: u64) -> Relation<Self> {
        Relation::new().offset(n)
    }
}

#[cfg(test)]
mod tests {
    use std::collections::HashMap;

    use sea_orm::{ActiveModelTrait, ActiveValue::Set};
    use serde_json::json;

    use super::{AsyncQuerying, OrderDirection};
    use crate::{
        RecordError,
        base::test_support::{TestUser, seed_users, setup_db, test_user},
    };

    #[tokio::test]
    async fn find_returns_matching_record() {
        let db = setup_db().await;
        seed_users(&db).await;

        let user = TestUser::find(2, &db)
            .await
            .expect("find should return a record");

        assert_eq!(user.name, "Bob");
    }

    #[tokio::test]
    async fn find_missing_returns_not_found() {
        let db = setup_db().await;

        let error = TestUser::find(404, &db)
            .await
            .expect_err("missing row should return an error");

        assert!(matches!(error, RecordError::NotFound));
    }

    #[tokio::test]
    async fn find_by_id_returns_none_when_missing() {
        let db = setup_db().await;

        let user = TestUser::find_by_id(404, &db)
            .await
            .expect("query should succeed");

        assert!(user.is_none());
    }

    #[tokio::test]
    async fn find_by_filters_by_conditions() {
        let db = setup_db().await;
        seed_users(&db).await;

        let mut conditions = HashMap::new();
        conditions.insert("email".to_owned(), json!("carol@example.com"));

        let user = TestUser::find_by(conditions, &db)
            .await
            .expect("query should succeed")
            .expect("row should exist");

        assert_eq!(user.name, "Carol");
    }

    #[tokio::test]
    async fn all_returns_every_row() {
        let db = setup_db().await;
        seed_users(&db).await;

        let users = TestUser::all(&db).await.expect("all should succeed");

        assert_eq!(users.len(), 3);
    }

    #[tokio::test]
    async fn first_returns_lowest_primary_key() {
        let db = setup_db().await;
        seed_users(&db).await;

        let user = TestUser::first(&db)
            .await
            .expect("query should succeed")
            .expect("row should exist");

        assert_eq!(user.name, "Alice");
    }

    #[tokio::test]
    async fn last_returns_highest_primary_key() {
        let db = setup_db().await;
        seed_users(&db).await;

        let user = TestUser::last(&db)
            .await
            .expect("query should succeed")
            .expect("row should exist");

        assert_eq!(user.name, "Carol");
    }

    #[tokio::test]
    async fn count_returns_row_total() {
        let db = setup_db().await;
        seed_users(&db).await;

        assert_eq!(TestUser::count(&db).await.expect("count should succeed"), 3);
    }

    #[tokio::test]
    async fn exists_returns_true_for_matching_conditions() {
        let db = setup_db().await;
        seed_users(&db).await;

        let mut conditions = HashMap::new();
        conditions.insert("name".to_owned(), json!("Bob"));

        assert!(
            TestUser::exists(conditions, &db)
                .await
                .expect("exists should succeed")
        );
    }

    #[tokio::test]
    async fn exists_returns_false_for_missing_conditions() {
        let db = setup_db().await;
        seed_users(&db).await;

        let mut conditions = HashMap::new();
        conditions.insert("name".to_owned(), json!("Nobody"));

        assert!(
            !TestUser::exists(conditions, &db)
                .await
                .expect("exists should succeed")
        );
    }

    #[tokio::test]
    async fn query_builder_helpers_start_relations() {
        let db = setup_db().await;
        seed_users(&db).await;

        let ordered = TestUser::order("id", OrderDirection::Desc)
            .first(&db)
            .await
            .expect("query should succeed")
            .expect("row should exist");
        let limited = TestUser::limit(2)
            .load(&db)
            .await
            .expect("limit should load");
        let offset = TestUser::offset(2)
            .order("id", OrderDirection::Asc)
            .load(&db)
            .await
            .expect("offset should load");

        assert_eq!(ordered.name, "Carol");
        assert_eq!(limited.len(), 2);
        assert_eq!(offset.len(), 1);
        assert_eq!(offset[0].name, "Carol");
    }
    #[tokio::test]
    async fn find_by_id_returns_matching_record_when_present() {
        let db = setup_db().await;
        seed_users(&db).await;

        let user = TestUser::find_by_id(3, &db)
            .await
            .expect("query should succeed")
            .expect("row should exist");

        assert_eq!(user.name, "Carol");
    }

    #[tokio::test]
    async fn find_by_returns_none_when_no_match_exists() {
        let db = setup_db().await;
        seed_users(&db).await;

        let user = TestUser::find_by(
            HashMap::from([("email".to_owned(), json!("missing@example.com"))]),
            &db,
        )
        .await
        .expect("query should succeed");

        assert!(user.is_none());
    }

    #[tokio::test]
    async fn find_by_with_multiple_conditions_requires_all_matches() {
        let db = setup_db().await;
        seed_users(&db).await;

        let user = TestUser::find_by(
            HashMap::from([
                ("name".to_owned(), json!("Bob")),
                ("email".to_owned(), json!("bob@example.com")),
            ]),
            &db,
        )
        .await
        .expect("query should succeed")
        .expect("row should exist");

        assert_eq!(user.id, Some(2));
    }

    #[tokio::test]
    async fn all_marks_loaded_rows_persisted() {
        let db = setup_db().await;
        seed_users(&db).await;

        let users = TestUser::all(&db).await.expect("all should succeed");

        assert!(
            users
                .iter()
                .all(|user| user.state == crate::RecordState::Persisted)
        );
    }

    #[tokio::test]
    async fn first_returns_none_when_table_is_empty() {
        let db = setup_db().await;

        let user = TestUser::first(&db).await.expect("query should succeed");

        assert!(user.is_none());
    }

    #[tokio::test]
    async fn last_returns_none_when_table_is_empty() {
        let db = setup_db().await;

        let user = TestUser::last(&db).await.expect("query should succeed");

        assert!(user.is_none());
    }

    #[tokio::test]
    async fn count_returns_zero_when_table_is_empty() {
        let db = setup_db().await;

        assert_eq!(TestUser::count(&db).await.expect("count should succeed"), 0);
    }

    #[tokio::test]
    async fn exists_with_empty_conditions_is_false_without_rows() {
        let db = setup_db().await;

        assert!(
            !TestUser::exists(HashMap::new(), &db)
                .await
                .expect("exists should succeed")
        );
    }

    #[tokio::test]
    async fn exists_with_empty_conditions_is_true_when_rows_exist() {
        let db = setup_db().await;
        seed_users(&db).await;

        assert!(
            TestUser::exists(HashMap::new(), &db)
                .await
                .expect("exists should succeed")
        );
    }

    #[tokio::test]
    async fn exists_with_multiple_conditions_requires_all_conditions() {
        let db = setup_db().await;
        seed_users(&db).await;

        assert!(
            !TestUser::exists(
                HashMap::from([
                    ("name".to_owned(), json!("Bob")),
                    ("email".to_owned(), json!("alice@example.com")),
                ]),
                &db,
            )
            .await
            .expect("exists should succeed")
        );
    }

    #[tokio::test]
    async fn where_helper_loads_matching_rows() {
        let db = setup_db().await;
        seed_users(&db).await;

        let users = TestUser::r#where(HashMap::from([("name".to_owned(), json!("Bob"))]))
            .load(&db)
            .await
            .expect("where relation should load");

        assert_eq!(users.len(), 1);
        assert_eq!(users[0].email, "bob@example.com");
    }

    #[tokio::test]
    async fn where_helper_with_multiple_conditions_loads_match() {
        let db = setup_db().await;
        seed_users(&db).await;

        let users = TestUser::r#where(HashMap::from([
            ("name".to_owned(), json!("Carol")),
            ("email".to_owned(), json!("carol@example.com")),
        ]))
        .load(&db)
        .await
        .expect("where relation should load");

        assert_eq!(users.len(), 1);
        assert_eq!(users[0].id, Some(3));
    }

    #[tokio::test]
    async fn where_helper_with_empty_conditions_loads_all_rows() {
        let db = setup_db().await;
        seed_users(&db).await;

        let users = TestUser::r#where(HashMap::new())
            .load(&db)
            .await
            .expect("where relation should load");

        assert_eq!(users.len(), 3);
    }

    #[tokio::test]
    async fn order_helper_descending_returns_expected_sequence() {
        let db = setup_db().await;
        seed_users(&db).await;

        let users = TestUser::order("id", OrderDirection::Desc)
            .load(&db)
            .await
            .expect("ordered relation should load");
        let names = users.into_iter().map(|user| user.name).collect::<Vec<_>>();

        assert_eq!(names, vec!["Carol", "Bob", "Alice"]);
    }

    #[tokio::test]
    async fn order_helper_ascending_returns_expected_sequence() {
        let db = setup_db().await;
        seed_users(&db).await;

        let users = TestUser::order("id", OrderDirection::Asc)
            .load(&db)
            .await
            .expect("ordered relation should load");
        let names = users.into_iter().map(|user| user.name).collect::<Vec<_>>();

        assert_eq!(names, vec!["Alice", "Bob", "Carol"]);
    }

    #[tokio::test]
    async fn limit_helper_zero_returns_no_rows() {
        let db = setup_db().await;
        seed_users(&db).await;

        let users = TestUser::limit(0)
            .load(&db)
            .await
            .expect("limit should load");

        assert!(users.is_empty());
    }

    #[tokio::test]
    async fn limit_helper_can_chain_with_order() {
        let db = setup_db().await;
        seed_users(&db).await;

        let users = TestUser::limit(2)
            .order("id", OrderDirection::Desc)
            .load(&db)
            .await
            .expect("relation should load");
        let names = users.into_iter().map(|user| user.name).collect::<Vec<_>>();

        assert_eq!(names, vec!["Carol", "Bob"]);
    }

    #[tokio::test]
    async fn offset_helper_beyond_row_count_returns_empty() {
        let db = setup_db().await;
        seed_users(&db).await;

        let users = TestUser::offset(10)
            .order("id", OrderDirection::Asc)
            .load(&db)
            .await
            .expect("relation should load");

        assert!(users.is_empty());
    }

    #[tokio::test]
    async fn offset_helper_can_chain_with_limit_and_order() {
        let db = setup_db().await;
        seed_users(&db).await;

        let users = TestUser::offset(1)
            .order("id", OrderDirection::Asc)
            .limit(1)
            .load(&db)
            .await
            .expect("relation should load");

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

    #[tokio::test]
    async fn find_by_id_returns_persisted_record() {
        let db = setup_db().await;
        seed_users(&db).await;

        let user = TestUser::find_by_id(1, &db)
            .await
            .expect("query should succeed")
            .expect("row should exist");

        assert_eq!(user.state, crate::RecordState::Persisted);
    }

    #[tokio::test]
    async fn find_by_bang_returns_matching_record() {
        let db = setup_db().await;
        seed_users(&db).await;

        let user = TestUser::find_by_bang(
            HashMap::from([("email".to_owned(), json!("bob@example.com"))]),
            &db,
        )
        .await
        .expect("row should exist");

        assert_eq!(user.name, "Bob");
    }

    #[tokio::test]
    async fn find_by_bang_returns_not_found_when_missing() {
        let db = setup_db().await;

        let error = TestUser::find_by_bang(
            HashMap::from([("email".to_owned(), json!("missing@example.com"))]),
            &db,
        )
        .await
        .expect_err("missing row should return an error");

        assert!(matches!(error, RecordError::NotFound));
    }

    #[tokio::test]
    async fn take_returns_first_available_row_without_order() {
        let db = setup_db().await;
        seed_users(&db).await;

        let user = TestUser::take(&db)
            .await
            .expect("take should succeed")
            .expect("row should exist");

        assert_eq!(user.id, Some(1));
    }

    #[tokio::test]
    async fn take_returns_none_when_table_is_empty() {
        let db = setup_db().await;

        let user = TestUser::take(&db).await.expect("take should succeed");

        assert!(user.is_none());
    }

    #[tokio::test]
    async fn take_bang_returns_not_found_when_table_is_empty() {
        let db = setup_db().await;

        let error = TestUser::take_bang(&db)
            .await
            .expect_err("empty tables should fail");

        assert!(matches!(error, RecordError::NotFound));
    }

    #[tokio::test]
    async fn sole_returns_only_row_when_table_has_one_record() {
        let db = setup_db().await;
        test_user::ActiveModel {
            name: Set("Solo".to_owned()),
            email: Set("solo@example.com".to_owned()),
            ..Default::default()
        }
        .insert(&db)
        .await
        .expect("fixture insert should succeed");

        let user = TestUser::sole(&db)
            .await
            .expect("sole should return the row");

        assert_eq!(user.name, "Solo");
    }

    #[tokio::test]
    async fn sole_returns_not_found_when_table_is_empty() {
        let db = setup_db().await;

        let error = TestUser::sole(&db)
            .await
            .expect_err("empty tables should fail");

        assert!(matches!(error, RecordError::NotFound));
    }

    #[tokio::test]
    async fn sole_returns_exceeded_when_multiple_rows_match() {
        let db = setup_db().await;
        seed_users(&db).await;

        let error = TestUser::sole(&db)
            .await
            .expect_err("multiple rows should fail sole");

        assert!(matches!(error, RecordError::SoleRecordExceeded));
    }

    #[tokio::test]
    async fn find_sole_by_returns_matching_row() {
        let db = setup_db().await;
        seed_users(&db).await;

        let user =
            TestUser::find_sole_by(HashMap::from([("name".to_owned(), json!("Alice"))]), &db)
                .await
                .expect("single matching row should exist");

        assert_eq!(user.email, "alice@example.com");
    }

    #[tokio::test]
    async fn find_sole_by_returns_exceeded_when_multiple_rows_match() {
        let db = setup_db().await;
        seed_users(&db).await;
        test_user::ActiveModel {
            name: Set("Bob".to_owned()),
            email: Set("bobby@example.com".to_owned()),
            ..Default::default()
        }
        .insert(&db)
        .await
        .expect("fixture insert should succeed");

        let error = TestUser::find_sole_by(HashMap::from([("name".to_owned(), json!("Bob"))]), &db)
            .await
            .expect_err("multiple matches should fail");

        assert!(matches!(error, RecordError::SoleRecordExceeded));
    }

    #[tokio::test]
    async fn pluck_returns_requested_column_values() {
        let db = setup_db().await;
        seed_users(&db).await;

        let values = TestUser::pluck("name", &db)
            .await
            .expect("pluck should succeed");

        assert_eq!(values, vec![json!("Alice"), json!("Bob"), json!("Carol")]);
    }

    #[tokio::test]
    async fn pick_returns_first_requested_column_value() {
        let db = setup_db().await;
        seed_users(&db).await;

        let value = TestUser::pick("email", &db)
            .await
            .expect("pick should succeed");

        assert_eq!(value, Some(json!("alice@example.com")));
    }

    #[tokio::test]
    async fn ids_returns_primary_keys() {
        let db = setup_db().await;
        seed_users(&db).await;

        let ids = TestUser::ids(&db).await.expect("ids should succeed");

        assert_eq!(ids, vec![1, 2, 3]);
    }

    #[tokio::test]
    async fn exists_with_conditions_matches_rows() {
        let db = setup_db().await;
        seed_users(&db).await;

        assert!(
            TestUser::exists_with_conditions(
                HashMap::from([("name".to_owned(), json!("Carol"))]),
                &db,
            )
            .await
            .expect("exists_with_conditions should succeed")
        );
    }

    #[tokio::test]
    async fn exists_with_conditions_returns_false_when_missing() {
        let db = setup_db().await;

        assert!(
            !TestUser::exists_with_conditions(
                HashMap::from([("name".to_owned(), json!("Nobody"))]),
                &db,
            )
            .await
            .expect("exists_with_conditions should succeed")
        );
    }
}