es-entity 0.12.6

Event Sourcing Entity Framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
mod helpers;

use es_entity::operation::{
    AtomicOperation, DbOp, OpWithTime,
    hooks::{CommitHook, HookOperation, PreCommitRet},
};
use sqlx::Connection;
use std::sync::{Arc, Mutex};

#[derive(Debug)]
struct FullCommitHook {
    data: String,
    pre_result: Arc<Mutex<Option<chrono::DateTime<chrono::Utc>>>>,
    post_result: Arc<Mutex<String>>,
}

impl CommitHook for FullCommitHook {
    async fn pre_commit(
        self,
        mut op: HookOperation<'_>,
    ) -> Result<PreCommitRet<'_, Self>, sqlx::Error> {
        let result = sqlx::query!("SELECT NOW() as now")
            .fetch_one(op.as_executor())
            .await?;
        *self.pre_result.lock().unwrap() = result.now;
        PreCommitRet::ok(self, op)
    }

    fn post_commit(self) {
        *self.post_result.lock().unwrap() = format!("post:{}", self.data);
    }
}

#[tokio::test]
async fn both_pre_and_post_commit_execute() -> anyhow::Result<()> {
    let pool = helpers::init_pool().await?;
    let mut op = DbOp::init(&pool).await?;

    let pre_result = Arc::new(Mutex::new(None));
    let post_result = Arc::new(Mutex::new(String::new()));

    op.add_commit_hook(FullCommitHook {
        data: "test".to_string(),
        pre_result: pre_result.clone(),
        post_result: post_result.clone(),
    })
    .unwrap();

    assert!(pre_result.lock().unwrap().is_none());
    op.commit().await?;

    let captured_time = pre_result
        .lock()
        .unwrap()
        .expect("should have captured db time");
    let now = chrono::Utc::now();
    assert!(now.signed_duration_since(captured_time).num_seconds().abs() < 5);
    assert_eq!(*post_result.lock().unwrap(), "post:test");

    Ok(())
}

#[derive(Debug)]
struct MergeableEvents {
    events: Vec<String>,
    pre_result: Arc<Mutex<Vec<String>>>,
    post_result: Arc<Mutex<Vec<String>>>,
}

impl CommitHook for MergeableEvents {
    async fn pre_commit(
        self,
        op: HookOperation<'_>,
    ) -> Result<PreCommitRet<'_, Self>, sqlx::Error> {
        *self.pre_result.lock().unwrap() = self.events.clone();
        PreCommitRet::ok(self, op)
    }

    fn post_commit(self) {
        *self.post_result.lock().unwrap() = self.events;
    }

    fn merge(&mut self, other: &mut Self) -> bool {
        self.events.append(&mut other.events);
        true
    }
}

#[tokio::test]
async fn hooks_merge_when_returning_true() -> anyhow::Result<()> {
    let pool = helpers::init_pool().await?;
    let mut op = DbOp::init(&pool).await?;

    let pre_result = Arc::new(Mutex::new(Vec::new()));
    let post_result = Arc::new(Mutex::new(Vec::new()));

    op.add_commit_hook(MergeableEvents {
        events: vec!["e1".into()],
        pre_result: pre_result.clone(),
        post_result: post_result.clone(),
    })
    .unwrap();
    op.add_commit_hook(MergeableEvents {
        events: vec!["e2".into(), "e3".into()],
        pre_result: pre_result.clone(),
        post_result: post_result.clone(),
    })
    .unwrap();

    op.commit().await?;

    assert_eq!(*pre_result.lock().unwrap(), vec!["e1", "e2", "e3"]);
    assert_eq!(*post_result.lock().unwrap(), vec!["e1", "e2", "e3"]);

    Ok(())
}

#[derive(Debug)]
struct NonMergeableHook {
    pre_count: Arc<Mutex<i32>>,
    post_count: Arc<Mutex<i32>>,
}

impl CommitHook for NonMergeableHook {
    async fn pre_commit(
        self,
        op: HookOperation<'_>,
    ) -> Result<PreCommitRet<'_, Self>, sqlx::Error> {
        *self.pre_count.lock().unwrap() += 1;
        PreCommitRet::ok(self, op)
    }

    fn post_commit(self) {
        *self.post_count.lock().unwrap() += 1;
    }
}

#[tokio::test]
async fn hooks_execute_separately_when_not_merged() -> anyhow::Result<()> {
    let pool = helpers::init_pool().await?;
    let mut op = DbOp::init(&pool).await?;

    let pre_count = Arc::new(Mutex::new(0));
    let post_count = Arc::new(Mutex::new(0));

    op.add_commit_hook(NonMergeableHook {
        pre_count: pre_count.clone(),
        post_count: post_count.clone(),
    })
    .unwrap();
    op.add_commit_hook(NonMergeableHook {
        pre_count: pre_count.clone(),
        post_count: post_count.clone(),
    })
    .unwrap();
    op.add_commit_hook(NonMergeableHook {
        pre_count: pre_count.clone(),
        post_count: post_count.clone(),
    })
    .unwrap();

    op.commit().await?;

    assert_eq!(*pre_count.lock().unwrap(), 3);
    assert_eq!(*post_count.lock().unwrap(), 3);

    Ok(())
}

#[derive(Debug)]
struct MergingGetterHook {
    payloads: Vec<String>,
}

impl CommitHook for MergingGetterHook {
    fn merge(&mut self, other: &mut Self) -> bool {
        self.payloads.append(&mut other.payloads);
        true
    }
}

#[derive(Debug)]
struct NonMergingGetterHook {
    label: &'static str,
}

impl CommitHook for NonMergingGetterHook {}

#[tokio::test]
async fn commit_hook_returns_registered_hook() -> anyhow::Result<()> {
    let pool = helpers::init_pool().await?;
    let mut op = DbOp::init(&pool).await?;

    assert!(op.commit_hook::<MergingGetterHook>().is_none());

    op.add_commit_hook(MergingGetterHook {
        payloads: vec!["e1".into()],
    })
    .unwrap();

    let hook = op
        .commit_hook::<MergingGetterHook>()
        .expect("hook should be registered");
    assert_eq!(hook.payloads, vec!["e1"]);

    op.commit().await?;

    Ok(())
}

#[tokio::test]
async fn commit_hook_returns_none_for_different_type() -> anyhow::Result<()> {
    let pool = helpers::init_pool().await?;
    let mut op = DbOp::init(&pool).await?;

    op.add_commit_hook(MergingGetterHook {
        payloads: vec!["e1".into()],
    })
    .unwrap();

    assert!(op.commit_hook::<NonMergingGetterHook>().is_none());

    op.commit().await?;

    Ok(())
}

#[tokio::test]
async fn commit_hook_sees_merged_contents() -> anyhow::Result<()> {
    let pool = helpers::init_pool().await?;
    let mut op = DbOp::init(&pool).await?;

    op.add_commit_hook(MergingGetterHook {
        payloads: vec!["e1".into()],
    })
    .unwrap();
    op.add_commit_hook(MergingGetterHook {
        payloads: vec!["e2".into(), "e3".into()],
    })
    .unwrap();

    let hook = op
        .commit_hook::<MergingGetterHook>()
        .expect("hook should be registered");
    assert_eq!(hook.payloads, vec!["e1", "e2", "e3"]);

    op.commit().await?;

    Ok(())
}

#[tokio::test]
async fn commit_hook_returns_last_non_merging_hook() -> anyhow::Result<()> {
    let pool = helpers::init_pool().await?;
    let mut op = DbOp::init(&pool).await?;

    op.add_commit_hook(NonMergingGetterHook { label: "first" })
        .unwrap();
    op.add_commit_hook(NonMergingGetterHook { label: "second" })
        .unwrap();

    let hook = op
        .commit_hook::<NonMergingGetterHook>()
        .expect("hook should be registered");
    assert_eq!(hook.label, "second");

    op.commit().await?;

    Ok(())
}

#[tokio::test]
async fn commit_hook_default_returns_none_for_bare_transaction() -> anyhow::Result<()> {
    let pool = helpers::init_pool().await?;
    let tx = pool.begin().await?;

    assert!(tx.commit_hook::<MergingGetterHook>().is_none());

    tx.commit().await?;

    Ok(())
}

#[tokio::test]
async fn commit_hook_delegates_through_time_wrappers() -> anyhow::Result<()> {
    let pool = helpers::init_pool().await?;
    let op = DbOp::init(&pool).await?;
    let mut op = op.with_db_time().await?;

    op.add_commit_hook(MergingGetterHook {
        payloads: vec!["e1".into()],
    })
    .unwrap();

    let hook = op
        .commit_hook::<MergingGetterHook>()
        .expect("DbOpWithTime should delegate to inner op");
    assert_eq!(hook.payloads, vec!["e1"]);

    let wrapped = OpWithTime::cached_or_clock_time(&mut op);
    let hook = wrapped
        .commit_hook::<MergingGetterHook>()
        .expect("OpWithTime should delegate to wrapped op");
    assert_eq!(hook.payloads, vec!["e1"]);
    drop(wrapped);

    op.commit().await?;

    Ok(())
}

#[derive(Debug)]
struct SiblingProbeHook {
    saw_sibling: Arc<Mutex<Option<bool>>>,
}

impl CommitHook for SiblingProbeHook {
    async fn pre_commit(
        self,
        op: HookOperation<'_>,
    ) -> Result<PreCommitRet<'_, Self>, sqlx::Error> {
        *self.saw_sibling.lock().unwrap() = Some(op.commit_hook::<MergingGetterHook>().is_some());
        PreCommitRet::ok(self, op)
    }
}

#[tokio::test]
async fn commit_hook_not_visible_inside_pre_commit() -> anyhow::Result<()> {
    let pool = helpers::init_pool().await?;
    let mut op = DbOp::init(&pool).await?;

    let saw_sibling = Arc::new(Mutex::new(None));

    op.add_commit_hook(MergingGetterHook {
        payloads: vec!["e1".into()],
    })
    .unwrap();
    op.add_commit_hook(SiblingProbeHook {
        saw_sibling: saw_sibling.clone(),
    })
    .unwrap();

    op.commit().await?;

    assert_eq!(*saw_sibling.lock().unwrap(), Some(false));

    Ok(())
}

#[derive(Debug)]
struct OrderProbe<const N: usize> {
    label: &'static str,
    pre_order: Arc<Mutex<Vec<&'static str>>>,
    post_order: Arc<Mutex<Vec<&'static str>>>,
}

impl<const N: usize> CommitHook for OrderProbe<N> {
    async fn pre_commit(
        self,
        op: HookOperation<'_>,
    ) -> Result<PreCommitRet<'_, Self>, sqlx::Error> {
        self.pre_order.lock().unwrap().push(self.label);
        PreCommitRet::ok(self, op)
    }

    fn post_commit(self) {
        self.post_order.lock().unwrap().push(self.label);
    }
}

#[derive(Debug)]
struct MergingOrderProbe {
    labels: Vec<&'static str>,
    pre_order: Arc<Mutex<Vec<&'static str>>>,
    post_order: Arc<Mutex<Vec<&'static str>>>,
}

impl CommitHook for MergingOrderProbe {
    async fn pre_commit(
        self,
        op: HookOperation<'_>,
    ) -> Result<PreCommitRet<'_, Self>, sqlx::Error> {
        self.pre_order.lock().unwrap().extend(&self.labels);
        PreCommitRet::ok(self, op)
    }

    fn post_commit(self) {
        self.post_order.lock().unwrap().extend(&self.labels);
    }

    fn merge(&mut self, other: &mut Self) -> bool {
        self.labels.append(&mut other.labels);
        true
    }
}

#[tokio::test]
async fn hooks_execute_in_registration_order_across_types() -> anyhow::Result<()> {
    let pool = helpers::init_pool().await?;

    // Repeat to catch nondeterministic ordering: with the previous
    // HashMap-backed storage, cross-type execution order differed between
    // iterations; the registration-order contract must hold on every run.
    for _ in 0..100 {
        let pre_order = Arc::new(Mutex::new(Vec::new()));
        let post_order = Arc::new(Mutex::new(Vec::new()));
        let mut op = DbOp::init(&pool).await?;

        macro_rules! probe {
            ($n:literal, $label:literal) => {
                op.add_commit_hook(OrderProbe::<$n> {
                    label: $label,
                    pre_order: pre_order.clone(),
                    post_order: post_order.clone(),
                })
                .unwrap();
            };
        }
        probe!(1, "one");
        probe!(2, "two");
        probe!(3, "three");
        probe!(4, "four");
        probe!(5, "five");

        op.commit().await?;

        let expected = vec!["one", "two", "three", "four", "five"];
        assert_eq!(*pre_order.lock().unwrap(), expected);
        assert_eq!(*post_order.lock().unwrap(), expected);
    }

    Ok(())
}

#[tokio::test]
async fn merged_hook_executes_at_position_of_first_registration() -> anyhow::Result<()> {
    let pool = helpers::init_pool().await?;
    let mut op = DbOp::init(&pool).await?;

    let pre_order = Arc::new(Mutex::new(Vec::new()));
    let post_order = Arc::new(Mutex::new(Vec::new()));

    // A, B, A′ where A′ merges into A: the merged hook keeps A's position.
    op.add_commit_hook(MergingOrderProbe {
        labels: vec!["a1"],
        pre_order: pre_order.clone(),
        post_order: post_order.clone(),
    })
    .unwrap();
    op.add_commit_hook(OrderProbe::<10> {
        label: "b",
        pre_order: pre_order.clone(),
        post_order: post_order.clone(),
    })
    .unwrap();
    op.add_commit_hook(MergingOrderProbe {
        labels: vec!["a2"],
        pre_order: pre_order.clone(),
        post_order: post_order.clone(),
    })
    .unwrap();

    op.commit().await?;

    let expected = vec!["a1", "a2", "b"];
    assert_eq!(*pre_order.lock().unwrap(), expected);
    assert_eq!(*post_order.lock().unwrap(), expected);

    Ok(())
}

#[tokio::test]
async fn non_merging_hook_executes_at_own_registration_position() -> anyhow::Result<()> {
    let pool = helpers::init_pool().await?;
    let mut op = DbOp::init(&pool).await?;

    let pre_order = Arc::new(Mutex::new(Vec::new()));
    let post_order = Arc::new(Mutex::new(Vec::new()));

    // A, B, A″ where A″ refuses to merge (default merge() == false): A″ runs at
    // its own later position instead of being grouped with A.
    op.add_commit_hook(OrderProbe::<20> {
        label: "a1",
        pre_order: pre_order.clone(),
        post_order: post_order.clone(),
    })
    .unwrap();
    op.add_commit_hook(OrderProbe::<21> {
        label: "b",
        pre_order: pre_order.clone(),
        post_order: post_order.clone(),
    })
    .unwrap();
    op.add_commit_hook(OrderProbe::<20> {
        label: "a2",
        pre_order: pre_order.clone(),
        post_order: post_order.clone(),
    })
    .unwrap();

    op.commit().await?;

    let expected = vec!["a1", "b", "a2"];
    assert_eq!(*pre_order.lock().unwrap(), expected);
    assert_eq!(*post_order.lock().unwrap(), expected);

    Ok(())
}

#[tokio::test]
async fn post_commit_order_mirrors_pre_commit_order() -> anyhow::Result<()> {
    let pool = helpers::init_pool().await?;
    let mut op = DbOp::init(&pool).await?;

    let pre_order = Arc::new(Mutex::new(Vec::new()));
    let post_order = Arc::new(Mutex::new(Vec::new()));

    // Mixed merging and non-merging registrations.
    op.add_commit_hook(OrderProbe::<30> {
        label: "x",
        pre_order: pre_order.clone(),
        post_order: post_order.clone(),
    })
    .unwrap();
    op.add_commit_hook(MergingOrderProbe {
        labels: vec!["m1"],
        pre_order: pre_order.clone(),
        post_order: post_order.clone(),
    })
    .unwrap();
    op.add_commit_hook(OrderProbe::<31> {
        label: "y",
        pre_order: pre_order.clone(),
        post_order: post_order.clone(),
    })
    .unwrap();
    op.add_commit_hook(MergingOrderProbe {
        labels: vec!["m2"],
        pre_order: pre_order.clone(),
        post_order: post_order.clone(),
    })
    .unwrap();

    op.commit().await?;

    let pre = pre_order.lock().unwrap().clone();
    let post = post_order.lock().unwrap().clone();
    assert_eq!(pre, vec!["x", "m1", "m2", "y"]);
    assert_eq!(post, pre);

    Ok(())
}

#[tokio::test]
async fn supports_hooks_reflects_op_capability() -> anyhow::Result<()> {
    let pool = helpers::init_pool().await?;

    // A DbOp is backed by a commit-hook buffer.
    let op = DbOp::init(&pool).await?;
    assert!(op.supports_hooks());

    // Time wrappers delegate to the inner op. (The `OpWithTime` temporary
    // borrows `with_time` only for the duration of the statement.)
    let mut with_time = op.with_db_time().await?;
    assert!(with_time.supports_hooks());
    assert!(OpWithTime::cached_or_clock_time(&mut with_time).supports_hooks());
    with_time.commit().await?;

    // A bare sqlx::Transaction has no hook buffer, so it reports no support —
    // distinct from a hook-capable op that merely has nothing registered yet
    // (both of which `commit_hook` would report as `None`).
    let tx = pool.begin().await?;
    assert!(!tx.supports_hooks());
    tx.rollback().await?;

    Ok(())
}

// ===========================================================================
// on_rollback tests
// ===========================================================================

/// Records lifecycle callbacks by label. Optionally fails its own `pre_commit`
/// (to drive the rollback path for the *other*, earlier hooks).
#[derive(Debug)]
struct RollbackProbe {
    label: &'static str,
    fail_pre: bool,
    pre_order: Arc<Mutex<Vec<&'static str>>>,
    post_order: Arc<Mutex<Vec<&'static str>>>,
    rollback_order: Arc<Mutex<Vec<&'static str>>>,
}

impl CommitHook for RollbackProbe {
    async fn pre_commit(
        self,
        op: HookOperation<'_>,
    ) -> Result<PreCommitRet<'_, Self>, sqlx::Error> {
        self.pre_order.lock().unwrap().push(self.label);
        if self.fail_pre {
            return Err(sqlx::Error::Protocol(format!(
                "hook '{}' intentionally fails pre_commit",
                self.label
            )));
        }
        PreCommitRet::ok(self, op)
    }

    fn post_commit(self) {
        self.post_order.lock().unwrap().push(self.label);
    }

    fn on_rollback(self) {
        self.rollback_order.lock().unwrap().push(self.label);
    }
}

#[tokio::test]
async fn on_rollback_fires_for_earlier_hooks_when_later_hook_fails() -> anyhow::Result<()> {
    let pool = helpers::init_pool().await?;
    let mut op = DbOp::init(&pool).await?;

    let pre = Arc::new(Mutex::new(Vec::new()));
    let post = Arc::new(Mutex::new(Vec::new()));
    let rollback = Arc::new(Mutex::new(Vec::new()));

    let mk = |label: &'static str, fail_pre: bool| RollbackProbe {
        label,
        fail_pre,
        pre_order: pre.clone(),
        post_order: post.clone(),
        rollback_order: rollback.clone(),
    };

    op.add_commit_hook(mk("a", false)).unwrap();
    op.add_commit_hook(mk("b", true)).unwrap();
    // Registered after the failing hook: its pre_commit never runs.
    op.add_commit_hook(mk("c", false)).unwrap();

    let result = op.commit().await;
    assert!(
        result.is_err(),
        "commit must fail because hook 'b' fails pre_commit"
    );

    // 'a' and 'b' ran pre_commit; 'c' never did (the loop stops at the failure).
    assert_eq!(*pre.lock().unwrap(), vec!["a", "b"]);
    // Only 'a' is notified: 'b' is consumed by its own failing pre_commit and
    // signals from that branch; 'c' never ran.
    assert_eq!(*rollback.lock().unwrap(), vec!["a"]);
    // No post_commit on the failure path.
    assert!(post.lock().unwrap().is_empty());

    Ok(())
}

#[tokio::test]
async fn on_rollback_not_fired_on_commit_success() -> anyhow::Result<()> {
    let pool = helpers::init_pool().await?;
    let mut op = DbOp::init(&pool).await?;

    let pre = Arc::new(Mutex::new(Vec::new()));
    let post = Arc::new(Mutex::new(Vec::new()));
    let rollback = Arc::new(Mutex::new(Vec::new()));

    op.add_commit_hook(RollbackProbe {
        label: "a",
        fail_pre: false,
        pre_order: pre.clone(),
        post_order: post.clone(),
        rollback_order: rollback.clone(),
    })
    .unwrap();

    op.commit().await?;

    assert_eq!(*pre.lock().unwrap(), vec!["a"]);
    assert_eq!(*post.lock().unwrap(), vec!["a"]);
    assert!(
        rollback.lock().unwrap().is_empty(),
        "on_rollback must not fire on a successful commit"
    );

    Ok(())
}

#[tokio::test]
async fn on_rollback_not_fired_when_op_dropped_without_commit() -> anyhow::Result<()> {
    let pool = helpers::init_pool().await?;

    let pre = Arc::new(Mutex::new(Vec::new()));
    let post = Arc::new(Mutex::new(Vec::new()));
    let rollback = Arc::new(Mutex::new(Vec::new()));

    {
        let mut op = DbOp::init(&pool).await?;
        op.add_commit_hook(RollbackProbe {
            label: "a",
            fail_pre: false,
            pre_order: pre.clone(),
            post_order: post.clone(),
            rollback_order: rollback.clone(),
        })
        .unwrap();
        // `op` is dropped here without commit(): pre_commit never ran, so there
        // is nothing to compensate.
    }

    assert!(
        pre.lock().unwrap().is_empty(),
        "pre_commit only runs at commit()"
    );
    assert!(post.lock().unwrap().is_empty());
    assert!(
        rollback.lock().unwrap().is_empty(),
        "on_rollback must not fire for an op dropped without commit()"
    );

    Ok(())
}

#[tokio::test]
async fn on_rollback_fires_in_registration_order() -> anyhow::Result<()> {
    let pool = helpers::init_pool().await?;
    let mut op = DbOp::init(&pool).await?;

    let pre = Arc::new(Mutex::new(Vec::new()));
    let post = Arc::new(Mutex::new(Vec::new()));
    let rollback = Arc::new(Mutex::new(Vec::new()));

    let mk = |label: &'static str, fail_pre: bool| RollbackProbe {
        label,
        fail_pre,
        pre_order: pre.clone(),
        post_order: post.clone(),
        rollback_order: rollback.clone(),
    };

    op.add_commit_hook(mk("a1", false)).unwrap();
    op.add_commit_hook(mk("a2", false)).unwrap();
    op.add_commit_hook(mk("a3", false)).unwrap();
    op.add_commit_hook(mk("boom", true)).unwrap();

    assert!(op.commit().await.is_err());

    // on_rollback mirrors post_commit's registration order.
    assert_eq!(*rollback.lock().unwrap(), vec!["a1", "a2", "a3"]);
    assert!(post.lock().unwrap().is_empty());

    Ok(())
}

/// A hook that does NOT override `on_rollback`, exercising the defaulted no-op.
#[derive(Debug)]
struct DefaultOnRollbackHook {
    pre_order: Arc<Mutex<Vec<&'static str>>>,
}

impl CommitHook for DefaultOnRollbackHook {
    async fn pre_commit(
        self,
        op: HookOperation<'_>,
    ) -> Result<PreCommitRet<'_, Self>, sqlx::Error> {
        self.pre_order.lock().unwrap().push("default");
        PreCommitRet::ok(self, op)
    }
    // `on_rollback` intentionally not overridden — uses the default no-op.
}

#[tokio::test]
async fn default_on_rollback_is_a_harmless_noop() -> anyhow::Result<()> {
    let pool = helpers::init_pool().await?;
    let mut op = DbOp::init(&pool).await?;

    let pre = Arc::new(Mutex::new(Vec::new()));
    let rollback = Arc::new(Mutex::new(Vec::new()));

    // Earlier hook relies on the DEFAULT on_rollback (no override).
    op.add_commit_hook(DefaultOnRollbackHook {
        pre_order: pre.clone(),
    })
    .unwrap();
    // Later hook fails, so the earlier hook's default no-op on_rollback fires.
    op.add_commit_hook(RollbackProbe {
        label: "boom",
        fail_pre: true,
        pre_order: pre.clone(),
        post_order: Arc::new(Mutex::new(Vec::new())),
        rollback_order: rollback.clone(),
    })
    .unwrap();

    assert!(op.commit().await.is_err());

    // The default hook ran pre_commit and its default no-op on_rollback did not
    // panic; the failing hook is consumed by its own failure.
    assert_eq!(*pre.lock().unwrap(), vec!["default", "boom"]);
    assert!(rollback.lock().unwrap().is_empty());

    Ok(())
}

/// Holds a transaction-scoped advisory lock in `pre_commit`; when its
/// `on_rollback` fires it probes, from a *separate* connection, whether the lock
/// is free — which it can only be if the operation's transaction has already
/// been rolled back. Proves `on_rollback` runs strictly after the rollback.
#[derive(Debug)]
struct AdvisoryLockProbe {
    lock_key: i64,
    /// `Some(true)` iff the second connection acquired the lock inside on_rollback.
    acquired_after_rollback: Arc<Mutex<Option<bool>>>,
}

impl CommitHook for AdvisoryLockProbe {
    async fn pre_commit(
        self,
        mut op: HookOperation<'_>,
    ) -> Result<PreCommitRet<'_, Self>, sqlx::Error> {
        // Transaction-scoped: auto-released only when this operation's tx ends.
        sqlx::query("SELECT pg_advisory_xact_lock($1)")
            .bind(self.lock_key)
            .execute(op.as_executor())
            .await?;
        PreCommitRet::ok(self, op)
    }

    fn on_rollback(self) {
        // The callback is sync, so run the async probe on its own thread with a
        // dedicated runtime and a fresh connection — fully independent of the
        // test's runtime and connection pool. A plain SELECT of the row is not a
        // valid probe (under READ COMMITTED an uncommitted row is invisible to
        // other sessions whether the tx is open or rolled back); lock contention
        // is what distinguishes the two.
        let key = self.lock_key;
        let acquired = std::thread::spawn(move || {
            let pg_con = std::env::var("PG_CON").expect("PG_CON must be set");
            let rt = tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build()
                .expect("build probe runtime");
            rt.block_on(async move {
                let mut conn = sqlx::PgConnection::connect(&pg_con)
                    .await
                    .expect("probe connection");
                let got: bool = sqlx::query_scalar("SELECT pg_try_advisory_lock($1)")
                    .bind(key)
                    .fetch_one(&mut conn)
                    .await
                    .expect("advisory lock probe");
                // `conn` drops at scope end, releasing any session lock acquired.
                got
            })
        })
        .join()
        .expect("probe thread panicked");

        *self.acquired_after_rollback.lock().unwrap() = Some(acquired);
    }
}

#[tokio::test]
async fn on_rollback_runs_after_transaction_is_rolled_back() -> anyhow::Result<()> {
    let pool = helpers::init_pool().await?;
    let mut op = DbOp::init(&pool).await?;

    // A distinctive key unlikely to collide with concurrent tests.
    let lock_key: i64 = 728_192_374_651;
    let acquired = Arc::new(Mutex::new(None));

    op.add_commit_hook(AdvisoryLockProbe {
        lock_key,
        acquired_after_rollback: acquired.clone(),
    })
    .unwrap();

    // A later hook fails, forcing the rollback-then-notify path for the probe.
    let sink = Arc::new(Mutex::new(Vec::new()));
    op.add_commit_hook(RollbackProbe {
        label: "boom",
        fail_pre: true,
        pre_order: sink.clone(),
        post_order: sink.clone(),
        rollback_order: sink.clone(),
    })
    .unwrap();

    let result = op.commit().await;
    assert!(
        result.is_err(),
        "commit must fail due to the later failing hook"
    );

    let acquired = acquired
        .lock()
        .unwrap()
        .expect("on_rollback should have run and probed the advisory lock");
    assert!(
        acquired,
        "the second connection must acquire the advisory lock inside on_rollback — \
         proving the operation's transaction had already rolled back (releasing the lock) \
         before on_rollback fired"
    );

    Ok(())
}