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
use std::collections::HashMap;

use sea_orm::{ActiveModelBehavior, ColumnTrait, EntityTrait, IntoActiveModel, Iterable};
use serde::{Serialize, de::DeserializeOwned};
use serde_json::Value;

use crate::{RecordError, persistence::AsyncPersistence};
use rustrails_support::{database, runtime};

/// Synchronous persistence interface for [`Record`] types.
#[allow(private_bounds)]
pub trait Persistence: AsyncPersistence {
    /// Saves the record, inserting or updating based on its current state.
    fn save_sync(&mut self) -> Result<(), RecordError>
    where
        Self: Serialize,
        <Self::Entity as EntityTrait>::Column: ColumnTrait + Iterable,
        <Self::Entity as EntityTrait>::Model:
            IntoActiveModel<<Self::Entity as EntityTrait>::ActiveModel>,
        <Self::Entity as EntityTrait>::ActiveModel: ActiveModelBehavior + Send,
    {
        database::with_db(|db| runtime::block_on(self.save(db)))
    }

    /// Saves the record and preserves validation-style error reporting.
    fn save_bang_sync(&mut self) -> Result<(), RecordError>
    where
        Self: Serialize,
        <Self::Entity as EntityTrait>::Column: ColumnTrait + Iterable,
        <Self::Entity as EntityTrait>::Model:
            IntoActiveModel<<Self::Entity as EntityTrait>::ActiveModel>,
        <Self::Entity as EntityTrait>::ActiveModel: ActiveModelBehavior + Send,
    {
        database::with_db(|db| runtime::block_on(self.save_bang(db)))
    }

    /// Creates a new record from a string-keyed attribute map.
    fn create_sync(attrs: HashMap<String, Value>) -> Result<Self, RecordError>
    where
        Self: Default + Serialize + DeserializeOwned,
        <Self::Entity as EntityTrait>::Column: ColumnTrait + Iterable,
        <Self::Entity as EntityTrait>::Model:
            IntoActiveModel<<Self::Entity as EntityTrait>::ActiveModel>,
        <Self::Entity as EntityTrait>::ActiveModel: ActiveModelBehavior + Send,
    {
        database::with_db(|db| runtime::block_on(Self::create(attrs, db)))
    }

    /// Inserts multiple records at once.
    fn insert_all_sync(records: Vec<HashMap<String, Value>>) -> Result<Vec<Self>, RecordError>
    where
        Self: Default + Serialize + DeserializeOwned,
        <Self::Entity as EntityTrait>::Column: ColumnTrait + Iterable,
        <Self::Entity as EntityTrait>::Model:
            IntoActiveModel<<Self::Entity as EntityTrait>::ActiveModel>,
        <Self::Entity as EntityTrait>::ActiveModel: ActiveModelBehavior + Send,
    {
        database::with_db(|db| runtime::block_on(Self::insert_all(records, db)))
    }

    /// Inserts a record, or updates it if a matching row already exists.
    fn upsert_sync(attrs: HashMap<String, Value>, unique_by: &[&str]) -> Result<Self, RecordError>
    where
        Self: Default + Serialize + DeserializeOwned,
        <Self::Entity as EntityTrait>::Column: ColumnTrait + Iterable,
        <Self::Entity as EntityTrait>::Model:
            IntoActiveModel<<Self::Entity as EntityTrait>::ActiveModel>,
        <Self::Entity as EntityTrait>::ActiveModel: ActiveModelBehavior + Send,
    {
        database::with_db(|db| runtime::block_on(Self::upsert(attrs, unique_by, db)))
    }

    /// Inserts or updates multiple records at once.
    fn upsert_all_sync(
        records: Vec<HashMap<String, Value>>,
        unique_by: &[&str],
    ) -> Result<Vec<Self>, RecordError>
    where
        Self: Default + Serialize + DeserializeOwned,
        <Self::Entity as EntityTrait>::Column: ColumnTrait + Iterable,
        <Self::Entity as EntityTrait>::Model:
            IntoActiveModel<<Self::Entity as EntityTrait>::ActiveModel>,
        <Self::Entity as EntityTrait>::ActiveModel: ActiveModelBehavior + Send,
    {
        database::with_db(|db| runtime::block_on(Self::upsert_all(records, unique_by, db)))
    }

    /// Updates the record with the provided attributes and saves the result.
    fn update_attributes_sync(&mut self, attrs: HashMap<String, Value>) -> Result<(), RecordError>
    where
        Self: Serialize + DeserializeOwned,
        <Self::Entity as EntityTrait>::Column: ColumnTrait + Iterable,
        <Self::Entity as EntityTrait>::Model:
            IntoActiveModel<<Self::Entity as EntityTrait>::ActiveModel>,
        <Self::Entity as EntityTrait>::ActiveModel: ActiveModelBehavior + Send,
    {
        database::with_db(|db| runtime::block_on(self.update_attributes(attrs, db)))
    }

    /// Deletes the record from the database and marks it destroyed.
    fn destroy_sync(&mut self) -> Result<(), RecordError>
    where
        <Self::Entity as EntityTrait>::Column: ColumnTrait + Iterable,
    {
        database::with_db(|db| runtime::block_on(self.destroy(db)))
    }

    /// Reloads the record from the database.
    fn reload_sync(&mut self) -> Result<(), RecordError>
    where
        <Self::Entity as EntityTrait>::Column: ColumnTrait + Iterable,
    {
        database::with_db(|db| runtime::block_on(self.reload(db)))
    }

    /// Deletes a row by primary key without instantiating a wrapper value.
    fn delete_sync(id: i64) -> Result<(), RecordError>
    where
        <Self::Entity as EntityTrait>::Column: ColumnTrait + Iterable,
    {
        database::with_db(|db| runtime::block_on(Self::delete(id, db)))
    }

    /// Updates all rows matching the provided conditions and returns the affected row count.
    fn update_all_sync(
        conditions: HashMap<String, Value>,
        updates: HashMap<String, Value>,
    ) -> Result<u64, RecordError>
    where
        <Self::Entity as EntityTrait>::Column: ColumnTrait + Iterable,
    {
        database::with_db(|db| runtime::block_on(Self::update_all(conditions, updates, db)))
    }

    /// Deletes all rows matching the provided conditions and returns the affected row count.
    fn destroy_all_sync(conditions: HashMap<String, Value>) -> Result<u64, RecordError>
    where
        <Self::Entity as EntityTrait>::Column: ColumnTrait + Iterable,
    {
        database::with_db(|db| runtime::block_on(Self::destroy_all(conditions, db)))
    }
}

impl<T: AsyncPersistence> Persistence for T {}

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

    use sea_orm::{ConnectionTrait, Schema};
    use serde_json::{Value, json};

    use super::Persistence;
    use crate::{
        Querying, Record, RecordError, RecordState,
        base::test_support::{TestUser, test_user},
    };
    use rustrails_support::{database, runtime};

    fn setup_sync_db() -> tokio::runtime::Runtime {
        let runtime_handle = runtime::init_runtime();
        database::establish("sqlite::memory:").expect("sqlite in-memory connection should succeed");
        runtime::block_on(async {
            let db = database::db();
            let schema = Schema::new(db.get_database_backend());
            db.execute(&schema.create_table_from_entity(test_user::Entity))
                .await
                .expect("test_users table should be created");
        });
        runtime_handle
    }

    fn user_attrs(name: &str, email: &str) -> HashMap<String, Value> {
        HashMap::from([
            ("name".to_owned(), json!(name)),
            ("email".to_owned(), json!(email)),
        ])
    }

    fn run_sync_test(test: impl FnOnce() + Send + 'static) {
        let handle = std::thread::spawn(test);
        if let Err(payload) = handle.join() {
            std::panic::resume_unwind(payload);
        }
    }

    fn with_sync_db(test: impl FnOnce(&tokio::runtime::Runtime) + Send + 'static) {
        run_sync_test(move || {
            let runtime_handle = setup_sync_db();
            test(&runtime_handle);
        });
    }

    #[test]
    fn create_sync_inserts_a_row_and_returns_it() {
        with_sync_db(|_| {
            let user = TestUser::create_sync(user_attrs("Alice", "alice@example.com"))
                .expect("create_sync should succeed");

            assert!(user.id().is_some());
            assert!(user.persisted());
            assert_eq!(
                TestUser::count_sync().expect("count_sync should succeed"),
                1
            );
        });
    }

    #[test]
    fn create_sync_preserves_supplied_attributes() {
        with_sync_db(|_| {
            let user = TestUser::create_sync(user_attrs("Dana", "dana@example.com"))
                .expect("create_sync should succeed");

            assert_eq!(user.name, "Dana");
            assert_eq!(user.email, "dana@example.com");
        });
    }

    #[test]
    fn create_sync_allows_explicit_primary_key() {
        with_sync_db(|_| {
            let user = TestUser::create_sync(HashMap::from([
                ("id".to_owned(), json!(42)),
                ("name".to_owned(), json!("Dana")),
                ("email".to_owned(), json!("dana@example.com")),
            ]))
            .expect("create_sync should succeed");

            assert_eq!(user.id(), Some(42));
            assert!(user.persisted());
        });
    }

    #[test]
    fn create_sync_with_empty_attributes_uses_defaults_and_persists() {
        with_sync_db(|_| {
            let user =
                TestUser::create_sync(HashMap::new()).expect("empty create_sync should succeed");

            assert!(user.id().is_some());
            assert_eq!(user.name, "");
            assert_eq!(user.email, "");
            assert!(user.persisted());
        });
    }

    #[test]
    fn create_sync_rejects_unknown_attributes() {
        with_sync_db(|_| {
            let error = TestUser::create_sync(HashMap::from([
                ("name".to_owned(), json!("Dana")),
                ("email".to_owned(), json!("dana@example.com")),
                ("role".to_owned(), json!("admin")),
            ]))
            .expect_err("unknown attributes should fail");

            assert!(matches!(error, RecordError::Invalid(_)));
        });
    }

    #[test]
    fn create_sync_with_invalid_attributes_fails() {
        with_sync_db(|_| {
            let error = TestUser::create_sync(HashMap::from([
                ("name".to_owned(), json!(123)),
                ("email".to_owned(), json!("alice@example.com")),
            ]))
            .expect_err("invalid attributes should fail");

            assert!(matches!(error, RecordError::Invalid(_)));
        });
    }

    #[test]
    fn create_sync_with_duplicate_primary_key_returns_database_error() {
        with_sync_db(|_| {
            let duplicate_id = 70_001;
            let _existing = TestUser::create_sync(HashMap::from([
                ("id".to_owned(), json!(duplicate_id)),
                ("name".to_owned(), json!("Alice")),
                ("email".to_owned(), json!("alice@example.com")),
            ]))
            .expect("initial create_sync should succeed");

            let error = TestUser::create_sync(HashMap::from([
                ("id".to_owned(), json!(duplicate_id)),
                ("name".to_owned(), json!("Dana")),
                ("email".to_owned(), json!("dana@example.com")),
            ]))
            .expect_err("duplicate ids should fail");

            assert!(matches!(error, RecordError::Database(_)));
        });
    }

    #[test]
    fn save_sync_inserts_new_records() {
        with_sync_db(|_| {
            let mut user = TestUser {
                name: "Alice".to_owned(),
                email: "alice@example.com".to_owned(),
                ..Default::default()
            };

            user.save_sync().expect("save_sync should insert");

            assert!(user.id().is_some());
            assert!(user.persisted());
            assert_eq!(
                TestUser::count_sync().expect("count_sync should succeed"),
                1
            );
        });
    }

    #[test]
    fn save_sync_updates_existing_records() {
        with_sync_db(|_| {
            let mut user = TestUser::create_sync(user_attrs("Alice", "alice@example.com"))
                .expect("create_sync should succeed");

            user.name = "Alicia".to_owned();
            user.save_sync().expect("save_sync should update");

            let reloaded = TestUser::find_sync(user.id().expect("saved user should have id"))
                .expect("find_sync should succeed");
            assert_eq!(reloaded.name, "Alicia");
        });
    }

    #[test]
    fn save_sync_preserves_existing_primary_key_when_updating() {
        with_sync_db(|_| {
            let mut user = TestUser::create_sync(user_attrs("Dana", "dana@example.com"))
                .expect("create_sync should succeed");
            let id = user.id().expect("created user should have id");

            user.email = "updated@example.com".to_owned();
            user.save_sync().expect("save_sync should update");

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

    #[test]
    fn save_sync_on_destroyed_state_returns_not_saved() {
        with_sync_db(|_| {
            let mut user = TestUser::persisted(1, "Dana", "dana@example.com");
            user.set_record_state(RecordState::Destroyed);

            let error = user
                .save_sync()
                .expect_err("destroyed records cannot be saved");

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

    #[test]
    fn save_sync_with_duplicate_primary_key_returns_database_error() {
        with_sync_db(|_| {
            let duplicate_id = 70_002;
            let _existing = TestUser::create_sync(HashMap::from([
                ("id".to_owned(), json!(duplicate_id)),
                ("name".to_owned(), json!("Alice")),
                ("email".to_owned(), json!("alice@example.com")),
            ]))
            .expect("initial create_sync should succeed");

            let mut user = TestUser {
                id: Some(duplicate_id),
                name: "Dana".to_owned(),
                email: "dana@example.com".to_owned(),
                ..Default::default()
            };

            let error = user.save_sync().expect_err("duplicate ids should fail");

            assert!(matches!(error, RecordError::Database(_)));
        });
    }

    #[test]
    fn save_bang_sync_behaves_like_save_sync() {
        with_sync_db(|_| {
            let mut user = TestUser {
                name: "Alice".to_owned(),
                email: "alice@example.com".to_owned(),
                ..Default::default()
            };

            user.save_bang_sync()
                .expect("save_bang_sync should succeed");

            assert!(user.persisted());
            assert_eq!(
                TestUser::count_sync().expect("count_sync should succeed"),
                1
            );
        });
    }

    #[test]
    fn save_bang_sync_on_destroyed_state_returns_not_saved() {
        with_sync_db(|_| {
            let mut user = TestUser::persisted(1, "Dana", "dana@example.com");
            user.set_record_state(RecordState::Destroyed);

            let error = user
                .save_bang_sync()
                .expect_err("destroyed records cannot be saved");

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

    #[test]
    fn save_bang_sync_propagates_duplicate_primary_key_errors() {
        with_sync_db(|_| {
            let duplicate_id = 70_003;
            let _existing = TestUser::create_sync(HashMap::from([
                ("id".to_owned(), json!(duplicate_id)),
                ("name".to_owned(), json!("Alice")),
                ("email".to_owned(), json!("alice@example.com")),
            ]))
            .expect("initial create_sync should succeed");

            let mut user = TestUser {
                id: Some(duplicate_id),
                name: "Dana".to_owned(),
                email: "dana@example.com".to_owned(),
                ..Default::default()
            };

            let error = user
                .save_bang_sync()
                .expect_err("duplicate ids should fail");

            assert!(matches!(error, RecordError::Database(_)));
        });
    }

    #[test]
    fn update_attributes_sync_merges_and_persists_changes() {
        with_sync_db(|_| {
            let mut user = TestUser::create_sync(user_attrs("Alice", "alice@example.com"))
                .expect("create_sync should succeed");

            user.update_attributes_sync(HashMap::from([("name".to_owned(), json!("Alicia"))]))
                .expect("update_attributes_sync should succeed");

            assert_eq!(user.name, "Alicia");
            let from_db = TestUser::find_sync(user.id().expect("user should have id"))
                .expect("find_sync should succeed");
            assert_eq!(from_db.name, "Alicia");
        });
    }

    #[test]
    fn update_attributes_sync_preserves_unspecified_fields() {
        with_sync_db(|_| {
            let mut user = TestUser::create_sync(user_attrs("Dana", "dana@example.com"))
                .expect("create_sync should succeed");

            user.update_attributes_sync(HashMap::from([("name".to_owned(), json!("Dani"))]))
                .expect("update_attributes_sync should succeed");

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

    #[test]
    fn update_attributes_sync_keeps_record_persisted() {
        with_sync_db(|_| {
            let mut user = TestUser::create_sync(user_attrs("Dana", "dana@example.com"))
                .expect("create_sync should succeed");

            user.update_attributes_sync(HashMap::from([("name".to_owned(), json!("Dani"))]))
                .expect("update_attributes_sync should succeed");

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

    #[test]
    fn update_attributes_sync_on_new_record_inserts_and_persists() {
        with_sync_db(|_| {
            let mut user = TestUser::default();

            user.update_attributes_sync(user_attrs("Dana", "dana@example.com"))
                .expect("update_attributes_sync should insert new records");

            assert!(user.id().is_some());
            assert!(user.persisted());
        });
    }

    #[test]
    fn update_attributes_sync_rejects_unknown_fields() {
        with_sync_db(|_| {
            let mut user = TestUser::create_sync(user_attrs("Alice", "alice@example.com"))
                .expect("create_sync should succeed");

            let error = user
                .update_attributes_sync(HashMap::from([("missing".to_owned(), json!(true))]))
                .expect_err("unknown field should fail");

            assert!(matches!(error, RecordError::Invalid(_)));
        });
    }

    #[test]
    fn update_attributes_sync_on_destroyed_record_returns_not_saved() {
        with_sync_db(|_| {
            let mut user = TestUser::persisted(1, "Dana", "dana@example.com");
            user.set_record_state(RecordState::Destroyed);

            let error = user
                .update_attributes_sync(HashMap::from([("name".to_owned(), json!("Dani"))]))
                .expect_err("destroyed records cannot be updated");

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

    #[test]
    fn update_attributes_sync_with_type_mismatch_returns_invalid() {
        with_sync_db(|_| {
            let mut user = TestUser::create_sync(user_attrs("Dana", "dana@example.com"))
                .expect("create_sync should succeed");

            let error = user
                .update_attributes_sync(HashMap::from([("id".to_owned(), json!("oops"))]))
                .expect_err("type mismatches should fail");

            assert!(matches!(error, RecordError::Invalid(_)));
        });
    }

    #[test]
    fn destroy_sync_deletes_rows_and_marks_records_destroyed() {
        with_sync_db(|_| {
            let mut user = TestUser::create_sync(user_attrs("Alice", "alice@example.com"))
                .expect("create_sync should succeed");
            let id = user.id().expect("created user should have id");

            user.destroy_sync().expect("destroy_sync should succeed");

            assert_eq!(user.record_state(), RecordState::Destroyed);
            assert!(matches!(
                TestUser::find_sync(id),
                Err(RecordError::NotFound)
            ));
            assert_eq!(
                TestUser::count_sync().expect("count_sync should succeed"),
                0
            );
        });
    }

    #[test]
    fn destroyed_record_cannot_be_saved_again() {
        with_sync_db(|_| {
            let mut user = TestUser::create_sync(user_attrs("Alice", "alice@example.com"))
                .expect("create_sync should succeed");

            user.destroy_sync().expect("destroy_sync should succeed");
            let error = user
                .save_sync()
                .expect_err("saving destroyed record should fail");

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

    #[test]
    fn destroy_sync_without_id_returns_not_saved() {
        with_sync_db(|_| {
            let mut user = TestUser::default();

            let error = user
                .destroy_sync()
                .expect_err("unsaved records cannot be destroyed");

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

    #[test]
    fn destroy_sync_after_row_is_missing_returns_not_found() {
        with_sync_db(|_| {
            let mut user = TestUser::create_sync(user_attrs("Dana", "dana@example.com"))
                .expect("create_sync should succeed");
            let id = user.id().expect("created user should have id");

            TestUser::delete_sync(id).expect("delete_sync should remove row");
            let error = user
                .destroy_sync()
                .expect_err("missing rows should fail destroy_sync");

            assert!(matches!(error, RecordError::NotFound));
            assert_eq!(user.record_state(), RecordState::Persisted);
        });
    }

    #[test]
    fn reload_sync_refreshes_from_the_database() {
        with_sync_db(|_| {
            let mut user = TestUser::create_sync(user_attrs("Alice", "alice@example.com"))
                .expect("create_sync should succeed");
            let id = user.id().expect("created user should have id");

            TestUser::update_all_sync(
                HashMap::from([("id".to_owned(), json!(id))]),
                HashMap::from([("name".to_owned(), json!("Alicia"))]),
            )
            .expect("update_all_sync should succeed");
            user.reload_sync().expect("reload_sync should succeed");

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

    #[test]
    fn reload_sync_without_id_returns_not_saved() {
        with_sync_db(|_| {
            let mut user = TestUser::default();

            let error = user
                .reload_sync()
                .expect_err("unsaved records cannot reload");

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

    #[test]
    fn reload_sync_after_row_is_deleted_returns_not_found() {
        with_sync_db(|_| {
            let mut user = TestUser::create_sync(user_attrs("Dana", "dana@example.com"))
                .expect("create_sync should succeed");
            let id = user.id().expect("created user should have id");

            TestUser::delete_sync(id).expect("delete_sync should remove row");
            let error = user
                .reload_sync()
                .expect_err("missing rows should fail reload_sync");

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

    #[test]
    fn reload_sync_restores_persisted_state_from_database() {
        with_sync_db(|_| {
            let mut user = TestUser::create_sync(user_attrs("Dana", "dana@example.com"))
                .expect("create_sync should succeed");
            user.set_record_state(RecordState::Destroyed);

            user.reload_sync().expect("reload_sync should succeed");

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

    #[test]
    fn delete_sync_removes_rows_by_id_without_loading_record() {
        with_sync_db(|_| {
            let id = TestUser::create_sync(user_attrs("Alice", "alice@example.com"))
                .expect("create_sync should succeed")
                .id()
                .expect("created user should have id");

            TestUser::delete_sync(id).expect("delete_sync should succeed");

            assert!(matches!(
                TestUser::find_sync(id),
                Err(RecordError::NotFound)
            ));
            assert_eq!(
                TestUser::count_sync().expect("count_sync should succeed"),
                0
            );
        });
    }

    #[test]
    fn delete_sync_missing_id_returns_not_found() {
        with_sync_db(|_| {
            let error = TestUser::delete_sync(999).expect_err("missing delete_sync should fail");

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

    #[test]
    fn sync_persistence_helpers_can_run_inside_the_same_async_runtime() {
        with_sync_db(|runtime_handle| {
            let user = runtime_handle.block_on(async {
                TestUser::create_sync(user_attrs("Dana", "dana@example.com"))
                    .expect("create_sync should work inside async context")
            });

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

    #[test]
    fn persistence_trait_is_the_sync_api() {
        run_sync_test(|| {
            fn assert_sync_api<T: Persistence>() {}
            assert_sync_api::<crate::base::test_support::TestUser>();
        });
    }

    #[test]
    fn upsert_sync_creates_a_new_record_when_none_exists() {
        with_sync_db(|_| {
            let user = TestUser::upsert_sync(user_attrs("Alice", "alice@example.com"), &["email"])
                .expect("upsert_sync should create a missing row");

            assert!(user.id().is_some());
            assert!(user.persisted());
            assert_eq!(
                TestUser::count_sync().expect("count_sync should succeed"),
                1
            );
        });
    }

    #[test]
    fn upsert_sync_updates_an_existing_record_when_match_exists() {
        with_sync_db(|_| {
            let existing = TestUser::create_sync(user_attrs("Alice", "alice@example.com"))
                .expect("seed create_sync should succeed");

            let user =
                TestUser::upsert_sync(user_attrs("Updated Alice", "alice@example.com"), &["email"])
                    .expect("upsert_sync should update the matching row");

            assert_eq!(user.id(), existing.id());
            assert_eq!(
                TestUser::count_sync().expect("count_sync should succeed"),
                1
            );

            let reloaded =
                TestUser::find_sync(existing.id().expect("existing record should have id"))
                    .expect("find_sync should reload the updated row");
            assert_eq!(reloaded.name, "Updated Alice");
            assert_eq!(reloaded.email, "alice@example.com");
        });
    }

    #[test]
    fn upsert_all_sync_handles_mixed_new_and_existing_records() {
        with_sync_db(|_| {
            let existing = TestUser::create_sync(user_attrs("Alice", "alice@example.com"))
                .expect("seed create_sync should succeed");

            let users = TestUser::upsert_all_sync(
                vec![
                    user_attrs("Updated Alice", "alice@example.com"),
                    user_attrs("Bob", "bob@example.com"),
                ],
                &["email"],
            )
            .expect("upsert_all_sync should handle mixed rows");

            assert_eq!(users.len(), 2);
            assert_eq!(
                TestUser::count_sync().expect("count_sync should succeed"),
                2
            );

            let updated =
                TestUser::find_sync(existing.id().expect("existing record should have id"))
                    .expect("find_sync should reload the updated row");
            assert_eq!(updated.name, "Updated Alice");

            let inserted = TestUser::find_by_sync(HashMap::from([(
                "email".to_owned(),
                json!("bob@example.com"),
            )]))
            .expect("find_by_sync should succeed")
            .expect("new row should exist");
            assert_eq!(inserted.name, "Bob");
        });
    }
}