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
use std::sync::{
    Arc,
    atomic::{AtomicBool, Ordering},
};

use crate::{
    base::test_support::{TestUser, seed_users, with_sync_test_user_db as with_sync_db},
    locking::{LockOption, pessimistic::PessimisticLocking},
    persistence::AsyncPersistence,
    querying::AsyncQuerying,
};
use rustrails_support::{database, ignored_rails_test, runtime};

fn seed_sync_users() {
    runtime::block_on(async {
        let db = database::db();
        seed_users(&db).await;
    });
}

ignored_rails_test!(
    test_quote_value_passed_lock_col,
    "Rails-specific: TestUser does not expose an optimistic lock column"
);
ignored_rails_test!(
    test_non_integer_lock_existing,
    "Rails-specific: TestUser does not expose an optimistic lock column"
);
ignored_rails_test!(
    test_non_integer_lock_destroy,
    "Rails-specific: TestUser does not expose an optimistic lock column"
);

#[test]
fn test_lock_existing() {
    with_sync_db(|| {
        seed_sync_users();

        let user = runtime::block_on(async {
            let db = database::db();
            TestUser::lock(1, &db).await
        })
        .expect("locking should load the seeded row");

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

ignored_rails_test!(
    test_lock_destroy,
    "Rails-specific: TestUser does not expose optimistic stale-destroy semantics"
);

#[test]
fn test_lock_repeating() {
    with_sync_db(|| {
        seed_sync_users();

        let first = runtime::block_on(async {
            let db = database::db();
            TestUser::lock(1, &db).await
        })
        .expect("first lock should succeed");
        let second = runtime::block_on(async {
            let db = database::db();
            TestUser::lock(1, &db).await
        })
        .expect("second lock should succeed");

        assert_eq!(first, second);
    });
}

ignored_rails_test!(
    test_lock_new,
    "Rails-specific: rustrails-record only exposes locking by persisted primary key"
);
ignored_rails_test!(
    test_lock_exception_record,
    "Rails-specific: TestUser does not expose an optimistic lock column"
);
ignored_rails_test!(
    test_lock_new_when_explicitly_passing_nil,
    "Rails-specific: rustrails-record only exposes locking by persisted primary key"
);
ignored_rails_test!(
    test_lock_new_when_explicitly_passing_value,
    "Rails-specific: rustrails-record only exposes locking by persisted primary key"
);
ignored_rails_test!(
    test_touch_existing_lock,
    "Rails-specific: TestUser does not expose optimistic lock-version touch semantics"
);
ignored_rails_test!(
    test_touch_stale_object,
    "Rails-specific: TestUser does not expose optimistic stale-object touch semantics"
);
ignored_rails_test!(
    test_update_with_dirty_primary_key,
    "Rails-specific: TestUser does not expose optimistic lock-version updates"
);
ignored_rails_test!(
    test_delete_with_dirty_primary_key,
    "Rails-specific: TestUser does not expose optimistic lock-version deletes"
);
ignored_rails_test!(
    test_destroy_with_dirty_primary_key,
    "Rails-specific: TestUser does not expose optimistic lock-version destroys"
);
ignored_rails_test!(
    test_explicit_update_lock_column_raise_error,
    "Rails-specific: TestUser does not expose an optimistic lock column"
);
ignored_rails_test!(
    test_lock_column_name_existing,
    "Rails-specific: TestUser does not expose a configurable optimistic lock column"
);
ignored_rails_test!(
    test_lock_column_is_mass_assignable,
    "Rails-specific: TestUser does not expose a mass-assignable optimistic lock column"
);
ignored_rails_test!(
    test_lock_without_default_sets_version_to_zero,
    "Rails-specific: TestUser does not expose optimistic lock-version defaults"
);
ignored_rails_test!(
    test_touch_existing_lock_without_default_should_work_with_null_in_the_database,
    "Rails-specific: TestUser does not expose optimistic lock-version touch semantics"
);
ignored_rails_test!(
    test_update_lock_version_to_nil_without_validation_or_constraint_raises_error,
    "Rails-specific: TestUser does not expose optimistic lock-version validation"
);
ignored_rails_test!(
    test_update_lock_version_to_nil_without_validation_raises,
    "Rails-specific: TestUser does not expose optimistic lock-version validation"
);
ignored_rails_test!(
    test_update_lock_version_to_nil_with_validation_does_not_raise_runtime_lock_version_error,
    "Rails-specific: TestUser does not expose optimistic lock-version validation"
);
ignored_rails_test!(
    test_update_bang_lock_version_to_nil_with_validation_does_not_raise_runtime_lock_version_error,
    "Rails-specific: TestUser does not expose optimistic lock-version validation"
);
ignored_rails_test!(
    test_touch_stale_object_with_lock_without_default,
    "Rails-specific: TestUser does not expose optimistic stale-object touch semantics"
);
ignored_rails_test!(
    test_lock_without_default_should_work_with_null_in_the_database,
    "Rails-specific: TestUser does not expose optimistic lock-version defaults"
);
ignored_rails_test!(
    test_update_with_lock_version_without_default_should_work_on_dirty_value_before_type_cast,
    "Rails-specific: TestUser does not expose optimistic lock-version updates"
);
ignored_rails_test!(
    test_destroy_with_lock_version_without_default_should_work_on_dirty_value_before_type_cast,
    "Rails-specific: TestUser does not expose optimistic lock-version destroys"
);
ignored_rails_test!(
    test_lock_without_default_queries_count,
    "Rails-specific: TestUser does not expose optimistic lock-version query behavior"
);
ignored_rails_test!(
    test_lock_with_custom_column_without_default_sets_version_to_zero,
    "Rails-specific: TestUser does not expose a configurable optimistic lock column"
);
ignored_rails_test!(
    test_lock_with_custom_column_without_default_should_work_with_null_in_the_database,
    "Rails-specific: TestUser does not expose a configurable optimistic lock column"
);
ignored_rails_test!(
    test_lock_with_custom_column_without_default_queries_count,
    "Rails-specific: TestUser does not expose a configurable optimistic lock column"
);
ignored_rails_test!(
    test_readonly_attributes,
    "Rails-specific: readonly lock-version attributes are not modeled on TestUser"
);
ignored_rails_test!(
    test_quote_table_name_reserved_word_references,
    "Rails-specific: adapter-specific reserved-word locking fixtures are not available for TestUser"
);
ignored_rails_test!(
    test_update_without_attributes_does_not_only_update_lock_version,
    "Rails-specific: TestUser does not expose optimistic lock-version updates"
);
ignored_rails_test!(
    test_counter_cache_with_touch_and_lock_version,
    "Rails-specific: TestUser has no counter-cache lock-version integration"
);
ignored_rails_test!(
    test_polymorphic_destroy_with_dependencies_and_lock_version,
    "Rails-specific: TestUser has no polymorphic dependency graph or lock-version integration"
);
ignored_rails_test!(
    test_removing_has_and_belongs_to_many_associations_upon_destroy,
    "Rails-specific: TestUser has no HABTM association cleanup with lock-version semantics"
);
ignored_rails_test!(
    test_yaml_dumping_with_lock_column,
    "Rails-specific: YAML serialization of optimistic lock columns is not modeled on TestUser"
);
ignored_rails_test!(
    test_destroy_dependents,
    "Rails-specific: TestUser has no dependent-destroy locking fixtures"
);
ignored_rails_test!(
    test_destroy_existing_object_with_locking_column_value_null_in_the_database,
    "Rails-specific: TestUser does not expose optimistic lock-version destroy semantics"
);
ignored_rails_test!(
    test_destroy_stale_object,
    "Rails-specific: TestUser does not expose optimistic stale-object destroy semantics"
);

#[test]
fn test_typical_find_with_lock() {
    with_sync_db(|| {
        seed_sync_users();

        let locked = runtime::block_on(async {
            let db = database::db();
            TestUser::lock(2, &db).await
        })
        .expect("locking should load the row");
        let found = runtime::block_on(async {
            let db = database::db();
            TestUser::find(2, &db).await
        })
        .expect("plain find should load the same row");

        assert_eq!(locked, found);
    });
}

ignored_rails_test!(
    test_eager_find_with_lock,
    "Rails-specific: TestUser has no eager-load association graph to combine with locking"
);
#[test]
fn test_lock_does_not_raise_when_the_object_is_not_dirty() {
    with_sync_db(|| {
        seed_sync_users();

        let user = runtime::block_on(async {
            let db = database::db();
            let mut user = TestUser::find(1, &db).await.expect("row should exist");
            user.lock_bang(&db)
                .await
                .expect("clean rows should reload without error");
            user
        });

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

ignored_rails_test!(
    test_lock_raises_when_the_record_is_dirty,
    "rustrails-record reloads dirty records on lock_bang instead of raising a dirty-state error"
);
ignored_rails_test!(
    test_locking_in_after_save_callback,
    "Rails-specific: ActiveRecord after_save callback locking is not modeled by rustrails-record"
);

#[test]
fn test_with_lock_commits_transaction() {
    with_sync_db(|| {
        seed_sync_users();

        let updated_name = runtime::block_on(async {
            let db = database::db();
            let mut user = TestUser::find(1, &db).await.expect("row should exist");
            user.with_lock(&db, LockOption::ForUpdate, |locked, txn| {
                Box::pin(async move {
                    locked.name = "Locked Alice".to_owned();
                    locked.save(txn).await?;
                    Ok::<String, crate::RecordError>(locked.name.clone())
                })
            })
            .await
            .expect("with_lock should commit successful changes")
        });

        let reloaded = runtime::block_on(async {
            let db = database::db();
            TestUser::find(1, &db)
                .await
                .expect("row should still exist")
        });
        assert_eq!(updated_name, "Locked Alice");
        assert_eq!(reloaded.name, "Locked Alice");
    });
}

#[test]
fn test_with_lock_rolls_back_transaction() {
    with_sync_db(|| {
        seed_sync_users();

        let error = runtime::block_on(async {
            let db = database::db();
            let mut user = TestUser::find(1, &db).await.expect("row should exist");
            user.with_lock(&db, LockOption::ForUpdate, |locked, txn| {
                Box::pin(async move {
                    locked.name = "Should Roll Back".to_owned();
                    locked.save(txn).await?;
                    Err::<(), crate::RecordError>(crate::RecordError::Invalid(
                        "force rollback".to_owned(),
                    ))
                })
            })
            .await
        })
        .expect_err("errors should trigger with_lock rollbacks");

        assert!(
            matches!(error, crate::RecordError::Invalid(message) if message == "force rollback")
        );
        let reloaded = runtime::block_on(async {
            let db = database::db();
            TestUser::find(1, &db)
                .await
                .expect("row should still exist")
        });
        assert_eq!(reloaded.name, "Alice");
    });
}

ignored_rails_test!(
    test_with_lock_configures_transaction,
    "Rails-specific: rustrails-record does not expose joinable or requires_new transaction options"
);
ignored_rails_test!(
    test_lock_sending_custom_lock_statement,
    "Rails-specific: rustrails-record does not expose custom SQL lock clauses"
);
ignored_rails_test!(
    test_with_lock_sets_isolation,
    "Rails-specific: rustrails-record does not expose with_lock isolation options"
);
ignored_rails_test!(
    test_with_lock_locks_with_no_args,
    "rustrails-record requires an explicit LockOption when calling with_lock"
);

#[test]
fn test_with_lock_yields_transaction() {
    with_sync_db(|| {
        seed_sync_users();

        let count = runtime::block_on(async {
            let db = database::db();
            let mut user = TestUser::find(1, &db).await.expect("row should exist");
            user.with_lock(&db, LockOption::ForUpdate, |locked, txn| {
                Box::pin(async move {
                    assert_eq!(locked.id, Some(1));
                    TestUser::count(txn).await
                })
            })
            .await
        })
        .expect("with_lock should yield the active transaction connection");

        assert_eq!(count, 3);
    });
}
ignored_rails_test!(
    test_no_locks_no_wait,
    "Rails-specific: this Rails check depends on concurrent blocking-lock timing, but rustrails-record's SQLite API only offers explicit LockOption values and rejects LockOption::Nowait up front"
);
#[test]
fn test_lock_when_not_preventing_writes() {
    with_sync_db(|| {
        seed_sync_users();

        let user = runtime::block_on(async {
            let db = database::db();
            let mut user = TestUser::find(3, &db).await.expect("row should exist");
            user.lock_bang(&db)
                .await
                .expect("ordinary lock_bang should succeed when writes are allowed");
            user
        });

        assert_eq!(user.id, Some(3));
        assert_eq!(user.name, "Carol");
        assert_eq!(user.email, "carol@example.com");
    });
}
ignored_rails_test!(
    test_lock_when_preventing_writes,
    "Rails-specific: rustrails-record has no write-prevention mode that rejects lock_bang"
);
#[test]
fn test_lock_when_not_preventing_writes_nested() {
    with_sync_db(|| {
        seed_sync_users();

        let locked_user = runtime::block_on(async {
            let db = database::db();
            crate::transactions::transaction(&db, |txn| {
                let txn = txn.clone();
                Box::pin(async move {
                    let outer_id = crate::transactions::current_transaction_id()
                        .expect("outer transaction should expose an id");
                    assert_eq!(crate::transactions::open_transactions(), 1);

                    let mut user = TestUser::find(3, &txn).await?;
                    user.lock_bang(&txn).await?;

                    assert_eq!(
                        crate::transactions::current_transaction_id(),
                        Some(outer_id)
                    );
                    assert_eq!(crate::transactions::open_transactions(), 1);

                    Ok::<(Option<i64>, String, String), crate::RecordError>((
                        user.id,
                        user.name.clone(),
                        user.email.clone(),
                    ))
                })
            })
            .await
            .expect("nested lock_bang should reuse the active transaction")
        });

        assert_eq!(locked_user.0, Some(3));
        assert_eq!(locked_user.1, "Carol");
        assert_eq!(locked_user.2, "carol@example.com");
        assert_eq!(crate::transactions::current_transaction_id(), None);
        assert_eq!(crate::transactions::open_transactions(), 0);
    });
}
ignored_rails_test!(
    test_custom_lock_when_preventing_writes,
    "Rails-specific: write-prevention modes and custom lock clauses are not implemented"
);
#[test]
fn test_with_lock_when_not_preventing_writes() {
    with_sync_db(|| {
        seed_sync_users();

        let result = runtime::block_on(async {
            let db = database::db();
            let mut user = TestUser::find(3, &db).await.expect("row should exist");
            user.with_lock(&db, LockOption::ForUpdate, |locked, _| {
                Box::pin(async move { Ok::<Option<i64>, crate::RecordError>(locked.id) })
            })
            .await
            .expect("ordinary with_lock should succeed when writes are allowed")
        });

        assert_eq!(result, Some(3));
    });
}
ignored_rails_test!(
    test_with_lock_when_preventing_writes,
    "Rails-specific: rustrails-record has no write-prevention mode that rejects with_lock"
);
ignored_rails_test!(
    test_custom_with_lock_when_preventing_writes,
    "Rails-specific: write-prevention modes and custom with_lock clauses are not implemented"
);
ignored_rails_test!(
    test_relation_lock_when_not_preventing_writes,
    "Rails-specific: relation-level lock clauses are not implemented"
);
ignored_rails_test!(
    test_relation_lock_when_preventing_writes,
    "Rails-specific: rustrails-record has no write-prevention mode for relation-level locks"
);
ignored_rails_test!(
    test_relation_lock_when_not_preventing_writes_nested,
    "Rails-specific: rustrails-record has no nested write-prevention override API"
);
ignored_rails_test!(
    test_custom_relation_lock_when_preventing_writes,
    "Rails-specific: relation-level custom lock clauses are not implemented"
);

#[test]
fn test_lock_returns_not_found_for_missing_row() {
    with_sync_db(|| {
        let error = runtime::block_on(async {
            let db = database::db();
            TestUser::lock(404, &db).await
        })
        .expect_err("missing rows should fail lock lookups");

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

#[test]
fn test_lock_marks_record_as_persisted() {
    with_sync_db(|| {
        seed_sync_users();

        let user = runtime::block_on(async {
            let db = database::db();
            TestUser::lock(1, &db).await
        })
        .expect("lock should load the seeded row");

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

#[test]
fn test_lock_preserves_identifier_and_email() {
    with_sync_db(|| {
        seed_sync_users();

        let user = runtime::block_on(async {
            let db = database::db();
            TestUser::lock(2, &db).await
        })
        .expect("lock should load the seeded row");

        assert_eq!(user.id, Some(2));
        assert_eq!(user.email, "bob@example.com");
    });
}

#[test]
fn test_lock_does_not_change_row_count() {
    with_sync_db(|| {
        seed_sync_users();

        let count = runtime::block_on(async {
            let db = database::db();
            let _ = TestUser::lock(3, &db)
                .await
                .expect("lock should load the row");
            TestUser::count(&db).await
        })
        .expect("count should succeed after lock");

        assert_eq!(count, 3);
    });
}

#[test]
fn test_lock_matches_plain_find_for_same_row() {
    with_sync_db(|| {
        seed_sync_users();

        let (locked, found) = runtime::block_on(async {
            let db = database::db();
            let locked = TestUser::lock(3, &db)
                .await
                .expect("lock should load the row");
            let found = TestUser::find(3, &db)
                .await
                .expect("find should load the same row");
            (locked, found)
        });

        assert_eq!(locked, found);
    });
}

#[test]
fn test_lock_with_option_skip_locked_degrades_on_sqlite() {
    with_sync_db(|| {
        seed_sync_users();

        let user = runtime::block_on(async {
            let db = database::db();
            TestUser::lock_with_option(1, LockOption::SkipLocked, &db).await
        })
        .expect("skip-locked should degrade to a plain lookup on sqlite");

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

#[test]
fn test_lock_with_option_nowait_returns_informative_error_on_sqlite() {
    with_sync_db(|| {
        seed_sync_users();

        let error = runtime::block_on(async {
            let db = database::db();
            TestUser::lock_with_option(1, LockOption::Nowait, &db).await
        })
        .expect_err("sqlite should reject NOWAIT row locks");

        assert!(
            matches!(error, crate::RecordError::Invalid(message) if message.contains("NOWAIT"))
        );
    });
}

#[test]
fn test_lock_with_option_returns_not_found_for_missing_row() {
    with_sync_db(|| {
        let error = runtime::block_on(async {
            let db = database::db();
            TestUser::lock_with_option(99, LockOption::SkipLocked, &db).await
        })
        .expect_err("missing rows should remain missing with lock options");

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

#[test]
fn test_lock_bang_reloads_latest_persisted_state() {
    with_sync_db(|| {
        seed_sync_users();

        let user = runtime::block_on(async {
            let db = database::db();
            let mut user = TestUser::find(1, &db).await.expect("row should exist");
            let mut other = TestUser::find(1, &db).await.expect("row should exist");
            other.name = "Alicia".to_owned();
            other
                .save(&db)
                .await
                .expect("save should persist the change");

            user.lock_bang(&db)
                .await
                .expect("lock_bang should reload latest state");
            user
        });

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

#[test]
fn test_lock_bang_noops_for_new_records() {
    with_sync_db(|| {
        let user = runtime::block_on(async {
            let db = database::db();
            let mut user = TestUser::default();
            user.lock_bang(&db).await.expect("new records should no-op");
            user
        });

        assert_eq!(user.state, crate::RecordState::New);
        assert_eq!(user.id, None);
    });
}

#[test]
fn test_with_lock_when_not_preventing_writes_nested() {
    with_sync_db(|| {
        seed_sync_users();

        let locked_id = runtime::block_on(async {
            let db = database::db();
            crate::transactions::transaction(&db, |txn| {
                let txn = txn.clone();
                Box::pin(async move {
                    let outer_id = crate::transactions::current_transaction_id()
                        .expect("outer transaction should expose an id");
                    assert_eq!(crate::transactions::open_transactions(), 1);

                    let mut user = TestUser::find(2, &txn).await?;
                    let expected_outer_id = outer_id.clone();
                    let locked_id = user
                        .with_lock(&txn, LockOption::ForUpdate, move |locked, inner| {
                            let expected_outer_id = expected_outer_id.clone();
                            Box::pin(async move {
                                assert_eq!(
                                    crate::transactions::current_transaction_id(),
                                    Some(expected_outer_id)
                                );
                                assert_eq!(crate::transactions::open_transactions(), 1);

                                locked.name = "Nested Bob".to_owned();
                                locked.save(inner).await?;
                                Ok::<Option<i64>, crate::RecordError>(locked.id)
                            })
                        })
                        .await?;

                    assert_eq!(
                        crate::transactions::current_transaction_id(),
                        Some(outer_id)
                    );
                    assert_eq!(crate::transactions::open_transactions(), 1);
                    Ok::<Option<i64>, crate::RecordError>(locked_id)
                })
            })
            .await
            .expect("nested with_lock should reuse the active transaction")
        });

        assert_eq!(locked_id, Some(2));
        assert_eq!(
            runtime::block_on(async {
                let db = database::db();
                TestUser::find(2, &db)
                    .await
                    .expect("row should still exist")
                    .name
            }),
            "Nested Bob"
        );
        assert_eq!(crate::transactions::current_transaction_id(), None);
        assert_eq!(crate::transactions::open_transactions(), 0);
    });
}

#[test]
fn test_with_lock_skip_locked_still_executes_closure_on_sqlite() {
    with_sync_db(|| {
        seed_sync_users();

        let (result, name) = runtime::block_on(async {
            let db = database::db();
            let mut user = TestUser::find(3, &db).await.expect("row should exist");
            let result = user
                .with_lock(&db, LockOption::SkipLocked, |locked, _| {
                    Box::pin(async move {
                        locked.name.push_str("-seen");
                        Ok::<String, crate::RecordError>(locked.name.clone())
                    })
                })
                .await
                .expect("skip-locked should still yield the record on sqlite");
            (result, user.name)
        });

        assert_eq!(result, "Carol-seen");
        assert_eq!(name, "Carol-seen");
    });
}

#[test]
fn test_with_lock_nowait_returns_error_before_running_closure() {
    with_sync_db(|| {
        seed_sync_users();
        let ran = Arc::new(AtomicBool::new(false));

        let error = runtime::block_on(async {
            let db = database::db();
            let mut user = TestUser::find(1, &db).await.expect("row should exist");
            user.with_lock(&db, LockOption::Nowait, {
                let ran = Arc::clone(&ran);
                move |_locked, _| {
                    ran.store(true, Ordering::SeqCst);
                    Box::pin(async { Ok::<(), crate::RecordError>(()) })
                }
            })
            .await
        })
        .expect_err("sqlite NOWAIT should fail before entering the closure");

        assert!(
            matches!(error, crate::RecordError::Invalid(message) if message.contains("NOWAIT"))
        );
        assert!(!ran.load(Ordering::SeqCst));
    });
}

#[test]
fn test_lock_reads_latest_persisted_values_after_update() {
    with_sync_db(|| {
        seed_sync_users();

        let refreshed = runtime::block_on(async {
            let db = database::db();
            let mut user = TestUser::lock(2, &db).await.expect("row should lock");
            user.name = "Bobby".to_owned();
            user.save(&db)
                .await
                .expect("save should persist the change");

            TestUser::lock(2, &db)
                .await
                .expect("updated row should lock")
        });

        assert_eq!(refreshed.name, "Bobby");
        assert_eq!(refreshed.email, "bob@example.com");
        assert_eq!(refreshed.state, crate::RecordState::Persisted);
    });
}