vantage-table 2.0.1

Table, Column, and operation traits for the Vantage data 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
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
#![cfg(feature = "mocks")]

//! The write pipeline of `Table`: set confinement, invariants, lifecycle hooks,
//! generated ids and audit timestamps. Expected outcomes come from the write
//! contract on `WritableValueSet` and the record-lifecycle chapter of the book.

use std::future::Future;
use std::pin::Pin;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};

use serde_json::{Value, json};
use vantage_core::Result;
use vantage_dataset::prelude::*;
use vantage_table::prelude::*;
use vantage_table::table::{AfterFn, BeforeDeleteFn, BeforeFn};
use vantage_types::{EmptyEntity, Record};

type MockTable = Table<MockTableSource, EmptyEntity>;
type Log = Arc<Mutex<Vec<String>>>;

fn rec(value: Value) -> Record<Value> {
    Record::from(value)
}

async fn empty() -> MockTable {
    let src = MockTableSource::new().with_data("t", vec![]).await;
    MockTable::new("t", src)
}

async fn with_rows(rows: Vec<Value>) -> MockTable {
    let src = MockTableSource::new().with_data("t", rows).await;
    MockTable::new("t", src).with_id_column("id")
}

/// `all` holds `in1` (parent p1) and `out1` (parent p2); `set` is `all` narrowed
/// by `parent = "p1"`.
async fn sets() -> (MockTable, MockTable) {
    let all = with_rows(vec![
        json!({"id": "in1", "name": "a", "parent": "p1"}),
        json!({"id": "out1", "name": "b", "parent": "p2"}),
    ])
    .await;
    let condition = all
        .data_source()
        .eq_value_condition("parent", json!("p1"))
        .unwrap();
    let set = all.clone().with_condition(condition);
    (all, set)
}

fn recording_before(label: &'static str, log: Log) -> BeforeFn<MockTableSource> {
    Arc::new(
        move |_r: &mut Record<Value>,
              _t: &MockTable|
              -> Pin<Box<dyn Future<Output = Result<()>> + Send + '_>> {
            let log = log.clone();
            Box::pin(async move {
                log.lock().unwrap().push(label.to_string());
                Ok(())
            })
        },
    )
}

fn setting(column: &'static str, value: &'static str) -> BeforeFn<MockTableSource> {
    Arc::new(
        move |r: &mut Record<Value>,
              _t: &MockTable|
              -> Pin<Box<dyn Future<Output = Result<()>> + Send + '_>> {
            r.insert(column.to_string(), json!(value));
            Box::pin(async move { Ok(()) })
        },
    )
}

fn failing_before() -> BeforeFn<MockTableSource> {
    Arc::new(
        |_r: &mut Record<Value>,
         _t: &MockTable|
         -> Pin<Box<dyn Future<Output = Result<()>> + Send + '_>> {
            Box::pin(async move { Err(vantage_core::error!("rejected by hook")) })
        },
    )
}

fn recording_after(label: &'static str, log: Log) -> AfterFn<MockTableSource> {
    Arc::new(
        move |id: &String,
              _rec: &Record<Value>,
              _t: &MockTable|
              -> Pin<Box<dyn Future<Output = Result<()>> + Send + '_>> {
            let log = log.clone();
            let entry = format!("{label}:{id}");
            Box::pin(async move {
                log.lock().unwrap().push(entry);
                Ok(())
            })
        },
    )
}

fn failing_after() -> AfterFn<MockTableSource> {
    Arc::new(
        |_id: &String,
         _rec: &Record<Value>,
         _t: &MockTable|
         -> Pin<Box<dyn Future<Output = Result<()>> + Send + '_>> {
            Box::pin(async move { Err(vantage_core::error!("after-hook failed")) })
        },
    )
}

fn veto() -> BeforeDeleteFn<MockTableSource> {
    Arc::new(
        |_id: &String,
         _rec: &Record<Value>,
         _t: &MockTable|
         -> Pin<Box<dyn Future<Output = Result<HookReturn>> + Send + '_>> {
            Box::pin(async move { Err(vantage_core::error!("deletion not allowed")) })
        },
    )
}

fn soft_delete() -> BeforeDeleteFn<MockTableSource> {
    Arc::new(
        |id: &String,
         _rec: &Record<Value>,
         table: &MockTable|
         -> Pin<Box<dyn Future<Output = Result<HookReturn>> + Send + '_>> {
            Box::pin(async move {
                let mut patch = Record::new();
                patch.insert("deleted".to_string(), json!("2026-01-01"));
                table.patch_value(id.clone(), &patch).await?;
                Ok(HookReturn::Handled)
            })
        },
    )
}

fn seeing_former(seen: Arc<Mutex<Vec<Value>>>) -> BeforeDeleteFn<MockTableSource> {
    Arc::new(
        move |_id: &String,
              former: &Record<Value>,
              _t: &MockTable|
              -> Pin<Box<dyn Future<Output = Result<HookReturn>> + Send + '_>> {
            let seen = seen.clone();
            let former = former["name"].clone();
            Box::pin(async move {
                seen.lock().unwrap().push(former);
                Ok(HookReturn::Proceed)
            })
        },
    )
}

fn counting_after(calls: Arc<AtomicUsize>) -> AfterFn<MockTableSource> {
    Arc::new(
        move |_id: &String,
              _rec: &Record<Value>,
              _t: &MockTable|
              -> Pin<Box<dyn Future<Output = Result<()>> + Send + '_>> {
            let calls = calls.clone();
            Box::pin(async move {
                calls.fetch_add(1, Ordering::SeqCst);
                Ok(())
            })
        },
    )
}

// --- the set: confined writes -------------------------------------------------

#[tokio::test]
async fn delete_in_the_set_removes_the_row_and_a_retry_succeeds() {
    let (all, set) = sets().await;
    set.delete("in1").await.unwrap();
    assert!(all.get_value("in1").await.unwrap().is_none());
    set.delete("in1").await.unwrap();
}

#[tokio::test]
async fn delete_outside_the_set_reports_ok_and_leaves_the_row() {
    let (all, set) = sets().await;
    set.delete("out1").await.unwrap();
    assert!(all.get_value("out1").await.unwrap().is_some());
}

#[tokio::test]
async fn delete_of_a_missing_row_reports_ok() {
    let (_, set) = sets().await;
    set.delete("ghost").await.unwrap();
}

#[tokio::test]
async fn patch_that_nulls_the_sets_column_is_a_conflict() {
    let (_, set) = sets().await;
    let err = set
        .patch_value("in1", &rec(json!({"parent": null})))
        .await
        .unwrap_err();
    assert!(err.is_conflict(), "{err}");
}

#[tokio::test]
async fn patch_naming_the_sets_own_value_is_accepted() {
    let (_, set) = sets().await;
    let patched = set
        .patch_value("in1", &rec(json!({"parent": "p1", "name": "q"})))
        .await
        .unwrap();
    assert_eq!(patched["name"], json!("q"));
}

#[tokio::test]
async fn replace_in_the_set_overwrites_the_row_and_fills_the_sets_column() {
    let (all, set) = sets().await;
    set.replace_value("in1", &rec(json!({"name": "r"})))
        .await
        .unwrap();
    let row = all.get_value("in1").await.unwrap().unwrap();
    assert_eq!(row["name"], json!("r"));
    assert_eq!(row["parent"], json!("p1"));
}

#[tokio::test]
async fn replace_drops_attributes_the_new_record_lacks() {
    let all = with_rows(vec![json!({"id": "1", "name": "a", "age": 3})]).await;
    all.replace_value("1", &rec(json!({"name": "b"})))
        .await
        .unwrap();
    let row = all.get_value("1").await.unwrap().unwrap();
    assert_eq!(row["name"], json!("b"));
    assert!(row.get("age").is_none());
}

#[tokio::test]
async fn replace_of_an_id_held_outside_the_set_is_a_conflict_and_leaves_the_row() {
    let (all, set) = sets().await;
    let err = set
        .replace_value("out1", &rec(json!({"name": "r"})))
        .await
        .unwrap_err();
    assert!(err.is_conflict(), "{err}");
    assert_eq!(
        all.get_value("out1").await.unwrap().unwrap()["parent"],
        json!("p2")
    );
}

#[tokio::test]
async fn replace_that_would_leave_the_set_is_a_conflict() {
    let (_, set) = sets().await;
    let err = set
        .replace_value("in1", &rec(json!({"name": "r", "parent": "p2"})))
        .await
        .unwrap_err();
    assert!(err.is_conflict(), "{err}");
}

#[tokio::test]
async fn replace_creates_a_missing_row_that_fits_the_set() {
    let (all, set) = sets().await;
    set.replace_value("new3", &rec(json!({"name": "r"})))
        .await
        .unwrap();
    assert_eq!(
        all.get_value("new3").await.unwrap().unwrap()["parent"],
        json!("p1")
    );
}

#[tokio::test]
async fn an_unnarrowed_table_writes_anywhere() {
    let all = empty().await;
    all.delete("ghost").await.unwrap();
    all.insert_value("k1", &rec(json!({"name": "a"})))
        .await
        .unwrap();
    let again = all
        .insert_value("k1", &rec(json!({"name": "b"})))
        .await
        .unwrap();
    assert_eq!(again["name"], json!("a"));
    all.replace_value("k2", &rec(json!({"name": "c"})))
        .await
        .unwrap();
    assert!(all.get_value("k2").await.unwrap().is_some());
    let err = all
        .patch_value("ghost", &rec(json!({"name": "x"})))
        .await
        .unwrap_err();
    assert!(err.is_not_found(), "{err}");
}

#[tokio::test]
async fn conditioned_table_refuses_writes_the_source_cannot_confine() {
    let src = MockTableSource::new()
        .without_confined_writes()
        .with_data("t", vec![json!({"id": "1", "parent": "p1"})])
        .await;
    let all = MockTable::new("t", src.clone());
    let set = all
        .clone()
        .with_condition(src.eq_value_condition("parent", json!("p1")).unwrap());

    let r = rec(json!({"name": "x"}));
    assert!(
        set.insert_value("2", &r)
            .await
            .unwrap_err()
            .is_unsupported()
    );
    assert!(
        set.replace_value("1", &r)
            .await
            .unwrap_err()
            .is_unsupported()
    );
    assert!(set.patch_value("1", &r).await.unwrap_err().is_unsupported());
    assert!(set.delete("1").await.unwrap_err().is_unsupported());
    assert!(
        set.insert_return_id_value(&r)
            .await
            .unwrap_err()
            .is_unsupported()
    );
    all.delete("1").await.unwrap();
}

#[tokio::test]
async fn a_condition_the_source_cannot_evaluate_refuses_by_id_writes() {
    let all = with_rows(vec![json!({"id": "1", "price": 5})]).await;
    let set = all.with_condition(vantage_expressions::expr_any!("price > {}", 10));
    let r = rec(json!({"price": 20}));
    assert!(
        set.insert_value("2", &r)
            .await
            .unwrap_err()
            .is_unsupported()
    );
    assert!(set.patch_value("1", &r).await.unwrap_err().is_unsupported());
    assert!(set.delete("1").await.unwrap_err().is_unsupported());
}

// --- invariants ---------------------------------------------------------------

async fn scoped() -> MockTable {
    empty().await.with_invariant("parent_id", json!("p1"))
}

#[tokio::test]
async fn insert_fills_an_absent_invariant_column() {
    let table = scoped().await;
    let id = table
        .insert_return_id_value(&rec(json!({"name": "absent"})))
        .await
        .unwrap();
    assert_eq!(
        table.get_value(id).await.unwrap().unwrap()["parent_id"],
        json!("p1")
    );
}

#[tokio::test]
async fn insert_fills_a_null_invariant_column() {
    let table = scoped().await;
    let id = table
        .insert_return_id_value(&rec(json!({"name": "null", "parent_id": null})))
        .await
        .unwrap();
    assert_eq!(
        table.get_value(id).await.unwrap().unwrap()["parent_id"],
        json!("p1")
    );
}

#[tokio::test]
async fn insert_keeps_an_equal_invariant_value() {
    let table = scoped().await;
    let id = table
        .insert_return_id_value(&rec(json!({"name": "match", "parent_id": "p1"})))
        .await
        .unwrap();
    assert_eq!(
        table.get_value(id).await.unwrap().unwrap()["parent_id"],
        json!("p1")
    );
}

#[tokio::test]
async fn insert_with_a_conflicting_invariant_value_is_rejected() {
    let table = scoped().await;
    let err = table
        .insert_return_id_value(&rec(json!({"name": "wrong", "parent_id": "other"})))
        .await
        .unwrap_err();
    assert!(err.is_conflict(), "{err}");
    assert!(table.list_values().await.unwrap().is_empty());
}

#[tokio::test]
async fn a_later_invariant_for_the_same_column_overwrites_the_earlier_one() {
    let table = scoped().await.with_invariant("parent_id", json!("p9"));
    assert_eq!(table.invariants().get("parent_id"), Some(&json!("p9")));
    assert_eq!(table.invariants().len(), 1);
}

#[tokio::test]
async fn with_id_narrows_to_the_row_and_makes_inserts_conform_to_the_id() {
    let base = with_rows(vec![
        json!({"id": "1", "name": "a"}),
        json!({"id": "2", "name": "b"}),
    ])
    .await;
    let one = base.clone().with_id(json!("1")).unwrap();
    assert_eq!(one.invariants().get("id"), Some(&json!("1")));
    let rows = one.list_values().await.unwrap();
    assert_eq!(rows.keys().collect::<Vec<_>>(), ["1"]);

    let patched = one
        .patch_value("1", &rec(json!({"name": "b2"})))
        .await
        .unwrap();
    assert_eq!(patched["name"], json!("b2"));
}

#[tokio::test]
async fn with_id_without_an_id_field_is_an_error() {
    assert!(empty().await.with_id(json!("1")).is_err());
}

// --- lifecycle hooks ----------------------------------------------------------

#[tokio::test]
async fn before_insert_hook_mutates_the_record_before_it_is_written() {
    let table = empty().await.with_hook(Hook::BeforeInsert(
        Phase::Populate,
        setting("created", "yes"),
    ));
    let id = table
        .insert_return_id_value(&rec(json!({"name": "a"})))
        .await
        .unwrap();
    assert_eq!(
        table.get_value(id).await.unwrap().unwrap()["created"],
        json!("yes")
    );
}

#[tokio::test]
async fn before_insert_hook_runs_for_insert_value_too() {
    let table = empty().await.with_hook(Hook::BeforeInsert(
        Phase::Populate,
        setting("created", "yes"),
    ));
    let stored = table
        .insert_value("1", &rec(json!({"name": "a"})))
        .await
        .unwrap();
    assert_eq!(stored["created"], json!("yes"));
}

#[tokio::test]
async fn before_insert_hook_does_not_run_on_replace_or_patch() {
    let table = with_rows(vec![json!({"id": "1", "name": "a"})])
        .await
        .with_hook(Hook::BeforeInsert(
            Phase::Populate,
            setting("created", "yes"),
        ));
    table
        .patch_value("1", &rec(json!({"name": "b"})))
        .await
        .unwrap();
    table
        .replace_value("1", &rec(json!({"name": "c"})))
        .await
        .unwrap();
    assert!(
        table
            .get_value("1")
            .await
            .unwrap()
            .unwrap()
            .get("created")
            .is_none()
    );
}

#[tokio::test]
async fn before_update_hook_runs_on_replace_and_patch_but_not_insert() {
    let table = with_rows(vec![json!({"id": "1", "name": "a"})])
        .await
        .with_hook(Hook::BeforeUpdate(
            Phase::Populate,
            setting("touched", "yes"),
        ));
    let patched = table
        .patch_value("1", &rec(json!({"name": "b"})))
        .await
        .unwrap();
    assert_eq!(patched["touched"], json!("yes"));
    let replaced = table
        .replace_value("1", &rec(json!({"name": "c"})))
        .await
        .unwrap();
    assert_eq!(replaced["touched"], json!("yes"));
    let inserted = table
        .insert_value("2", &rec(json!({"name": "d"})))
        .await
        .unwrap();
    assert!(inserted.get("touched").is_none());
}

#[tokio::test]
async fn before_save_hook_runs_on_insert_and_update() {
    let table = with_rows(vec![json!({"id": "1", "name": "a"})])
        .await
        .with_hook(Hook::BeforeSave(Phase::Populate, setting("saved", "yes")));
    let inserted = table
        .insert_value("2", &rec(json!({"name": "d"})))
        .await
        .unwrap();
    assert_eq!(inserted["saved"], json!("yes"));
    let patched = table
        .patch_value("1", &rec(json!({"name": "b"})))
        .await
        .unwrap();
    assert_eq!(patched["saved"], json!("yes"));
}

#[tokio::test]
async fn before_hooks_run_in_phase_order_then_registration_order() {
    let log: Log = Arc::default();
    let table = empty()
        .await
        .with_hook(Hook::BeforeInsert(
            Phase::Validate,
            recording_before("validate", log.clone()),
        ))
        .with_hook(Hook::BeforeInsert(
            Phase::Populate,
            recording_before("populate-1", log.clone()),
        ))
        .with_hook(Hook::BeforeInsert(
            Phase::Normalize,
            recording_before("normalize", log.clone()),
        ))
        .with_hook(Hook::BeforeInsert(
            Phase::Populate,
            recording_before("populate-2", log.clone()),
        ));
    table
        .insert_return_id_value(&rec(json!({"name": "a"})))
        .await
        .unwrap();
    assert_eq!(
        *log.lock().unwrap(),
        ["normalize", "populate-1", "populate-2", "validate"]
    );
}

#[test]
fn phases_order_normalize_then_populate_then_validate() {
    assert!(Phase::Normalize < Phase::Populate);
    assert!(Phase::Populate < Phase::Validate);
}

#[tokio::test]
async fn an_erroring_before_hook_cancels_the_write() {
    let table = empty()
        .await
        .with_hook(Hook::BeforeInsert(Phase::Populate, failing_before()));
    assert!(
        table
            .insert_value("1", &rec(json!({"name": "a"})))
            .await
            .is_err()
    );
    assert!(table.list_values().await.unwrap().is_empty());
}

#[tokio::test]
async fn before_hooks_run_ahead_of_invariant_enforcement() {
    let table = scoped().await.with_hook(Hook::BeforeInsert(
        Phase::Populate,
        setting("parent_id", "other"),
    ));
    let err = table
        .insert_return_id_value(&rec(json!({"name": "a"})))
        .await
        .unwrap_err();
    assert!(err.is_conflict(), "{err}");
}

#[tokio::test]
async fn before_delete_hook_error_vetoes_the_delete() {
    let table = with_rows(vec![json!({"id": "1", "name": "a"})])
        .await
        .with_hook(Hook::BeforeDelete(veto()));
    assert!(table.delete("1").await.is_err());
    assert!(table.get_value("1").await.unwrap().is_some());
}

#[tokio::test]
async fn before_delete_handled_skips_the_real_delete_and_reports_success() {
    let table = with_rows(vec![json!({"id": "1", "name": "a"})])
        .await
        .with_hook(Hook::BeforeDelete(soft_delete()));
    table.delete("1").await.unwrap();
    let row = table.get_value("1").await.unwrap().unwrap();
    assert_eq!(row["deleted"], json!("2026-01-01"));
}

#[tokio::test]
async fn before_delete_hook_sees_the_former_row() {
    let seen = Arc::new(Mutex::new(Vec::new()));
    let table = with_rows(vec![json!({"id": "1", "name": "a"})])
        .await
        .with_hook(Hook::BeforeDelete(seeing_former(seen.clone())));
    table.delete("1").await.unwrap();
    assert_eq!(*seen.lock().unwrap(), [json!("a")]);
    assert!(table.get_value("1").await.unwrap().is_none());
}

#[tokio::test]
async fn after_insert_after_update_and_after_delete_hooks_fire_with_the_id() {
    let log: Log = Arc::default();
    let table = with_rows(vec![json!({"id": "1", "name": "a"})])
        .await
        .with_hook(Hook::AfterInsert(recording_after("ins", log.clone())))
        .with_hook(Hook::AfterUpdate(recording_after("upd", log.clone())))
        .with_hook(Hook::AfterDelete(recording_after("del", log.clone())));
    table
        .insert_value("2", &rec(json!({"name": "b"})))
        .await
        .unwrap();
    table
        .patch_value("1", &rec(json!({"name": "c"})))
        .await
        .unwrap();
    table
        .replace_value("1", &rec(json!({"name": "d"})))
        .await
        .unwrap();
    table.delete("2").await.unwrap();
    assert_eq!(*log.lock().unwrap(), ["ins:2", "upd:1", "upd:1", "del:2"]);
}

#[tokio::test]
async fn after_save_hook_fires_on_insert_and_update() {
    let log: Log = Arc::default();
    let table = with_rows(vec![json!({"id": "1", "name": "a"})])
        .await
        .with_hook(Hook::AfterSave(recording_after("save", log.clone())));
    table
        .insert_value("2", &rec(json!({"name": "b"})))
        .await
        .unwrap();
    table
        .patch_value("1", &rec(json!({"name": "c"})))
        .await
        .unwrap();
    assert_eq!(*log.lock().unwrap(), ["save:2", "save:1"]);
}

#[tokio::test]
async fn delete_all_fires_no_hooks() {
    let calls = Arc::new(AtomicUsize::new(0));
    let table = with_rows(vec![json!({"id": "1", "name": "a"})])
        .await
        .with_hook(Hook::AfterDelete(counting_after(calls.clone())))
        .with_hook(Hook::BeforeDelete(veto()));
    table.delete_all().await.unwrap();
    assert_eq!(calls.load(Ordering::SeqCst), 0);
    assert!(table.list_values().await.unwrap().is_empty());
}

#[tokio::test]
async fn delete_outside_the_set_runs_no_hooks_and_deletes_nothing() {
    let (all, set) = sets().await;
    let calls = Arc::new(AtomicUsize::new(0));
    let set = set.with_hook(Hook::AfterDelete(counting_after(calls.clone())));

    set.delete("out1").await.unwrap();
    assert_eq!(calls.load(Ordering::SeqCst), 0);
    assert!(all.get_value("out1").await.unwrap().is_some());

    set.delete("in1").await.unwrap();
    assert_eq!(calls.load(Ordering::SeqCst), 1);
    set.delete("in1").await.unwrap();
    assert_eq!(
        calls.load(Ordering::SeqCst),
        1,
        "a missing row runs no hooks"
    );
}

#[tokio::test]
async fn a_failing_after_hook_surfaces_an_error_but_the_write_stays_committed() {
    let table = empty().await.with_hook(Hook::AfterInsert(failing_after()));
    assert!(
        table
            .insert_value("1", &rec(json!({"name": "a"})))
            .await
            .is_err()
    );
    assert!(table.get_value("1").await.unwrap().is_some());
}

#[tokio::test]
async fn prepare_insert_runs_hooks_and_invariants_without_writing() {
    let table = scoped().await.with_hook(Hook::BeforeInsert(
        Phase::Populate,
        setting("created", "yes"),
    ));
    let prepared = table
        .prepare_insert(&rec(json!({"name": "a"})))
        .await
        .unwrap();
    assert_eq!(prepared["created"], json!("yes"));
    assert_eq!(prepared["parent_id"], json!("p1"));
    assert!(table.list_values().await.unwrap().is_empty());
}

#[tokio::test]
async fn prepare_insert_refuses_a_table_whose_source_cannot_confine_writes() {
    let src = MockTableSource::new().without_confined_writes();
    let condition = src.eq_value_condition("parent", json!("p1")).unwrap();
    let set = MockTable::new("t", src).with_condition(condition);
    let err = set
        .prepare_insert(&rec(json!({"name": "a"})))
        .await
        .unwrap_err();
    assert!(err.is_unsupported(), "{err}");
}

#[tokio::test]
async fn finish_insert_runs_the_after_insert_hooks() {
    let log: Log = Arc::default();
    let table = empty()
        .await
        .with_hook(Hook::AfterInsert(recording_after("ins", log.clone())));
    table
        .finish_insert(&"7".to_string(), &rec(json!({"name": "a"})))
        .await
        .unwrap();
    assert_eq!(*log.lock().unwrap(), ["ins:7"]);
}

// --- generated ids ------------------------------------------------------------

#[test]
fn uuid_generators_make_fresh_hyphenated_uuids_of_their_version() {
    let v7 = IdGenerator::UuidV7;
    let (a, b) = (v7.generate(), v7.generate());
    assert_ne!(a, b);
    assert_eq!(a.len(), 36);
    assert_eq!(a.as_bytes()[14], b'7');

    let v4 = IdGenerator::UuidV4;
    let c = v4.generate();
    assert_eq!(c.len(), 36);
    assert_eq!(c.as_bytes()[14], b'4');
}

#[test]
fn uuid_v7_ids_sort_by_creation_time() {
    let ids: Vec<String> = (0..3)
        .map(|_| {
            let id = IdGenerator::UuidV7.generate();
            std::thread::sleep(std::time::Duration::from_millis(2));
            id
        })
        .collect();
    let mut sorted = ids.clone();
    sorted.sort();
    assert_eq!(ids, sorted);
}

#[test]
fn custom_generator_calls_the_closure() {
    assert_eq!(
        IdGenerator::custom(|| "made-up".into()).generate(),
        "made-up"
    );
}

#[tokio::test]
async fn with_generated_id_fills_a_missing_id_on_insert() {
    let table = empty().await.with_generated_id(IdGenerator::UuidV7);
    let id = table
        .insert_return_id_value(&rec(json!({"name": "a"})))
        .await
        .unwrap();
    assert_eq!(id.len(), 36);
    assert_eq!(
        table.get_value(id).await.unwrap().unwrap()["name"],
        json!("a")
    );
}

#[tokio::test]
async fn with_generated_id_fills_a_null_id() {
    let table = empty().await.with_generated_id(IdGenerator::UuidV4);
    let id = table
        .insert_return_id_value(&rec(json!({"id": null, "name": "a"})))
        .await
        .unwrap();
    assert_eq!(id.len(), 36);
}

#[tokio::test]
async fn with_generated_id_keeps_a_caller_supplied_id() {
    let table = empty().await.with_generated_id(IdGenerator::UuidV7);
    let id = table
        .insert_return_id_value(&rec(json!({"id": "fixed-1", "name": "a"})))
        .await
        .unwrap();
    assert_eq!(id, "fixed-1");
}

#[tokio::test]
async fn with_generated_id_uses_the_custom_generator() {
    let table = empty()
        .await
        .with_generated_id(IdGenerator::custom(|| "made-up".into()));
    let id = table
        .insert_return_id_value(&rec(json!({"name": "a"})))
        .await
        .unwrap();
    assert_eq!(id, "made-up");
}

#[tokio::test]
async fn add_generated_id_is_the_mutable_form() {
    let mut table = empty().await;
    table.add_generated_id(IdGenerator::custom(|| "made-up".into()));
    let id = table
        .insert_return_id_value(&rec(json!({"name": "a"})))
        .await
        .unwrap();
    assert_eq!(id, "made-up");
}

#[tokio::test]
async fn generated_ids_never_touch_patch_or_replace() {
    let table = with_rows(vec![json!({"id": "1", "name": "a"})])
        .await
        .with_generated_id(IdGenerator::custom(|| "made-up".into()));
    table
        .patch_value("1", &rec(json!({"name": "b"})))
        .await
        .unwrap();
    table
        .replace_value("1", &rec(json!({"name": "c"})))
        .await
        .unwrap();
    let row = table.get_value("1").await.unwrap().unwrap();
    assert_eq!(row["name"], json!("c"));
    assert!(table.get_value("made-up").await.unwrap().is_none());
}

// --- audit timestamps ---------------------------------------------------------

fn is_rfc3339_utc_seconds(v: &Value) -> bool {
    v.as_str().is_some_and(|s| {
        s.len() == 20
            && s.ends_with('Z')
            && s.as_bytes()[4] == b'-'
            && s.as_bytes()[10] == b'T'
            && s.as_bytes()[13] == b':'
    })
}

#[tokio::test]
async fn with_timestamps_stamps_created_and_updated_on_insert() {
    let table = empty().await.with_timestamps();
    let id = table
        .insert_return_id_value(&rec(json!({"id": "1", "name": "a"})))
        .await
        .unwrap();
    let row = table.get_value(id).await.unwrap().unwrap();
    assert!(is_rfc3339_utc_seconds(&row["created_at"]), "{row:?}");
    assert!(is_rfc3339_utc_seconds(&row["updated_at"]), "{row:?}");
}

#[tokio::test]
async fn with_timestamps_keeps_a_caller_supplied_created_at() {
    let table = empty().await.with_timestamps();
    let stored = table
        .insert_value(
            "1",
            &rec(json!({"name": "a", "created_at": "2000-01-01T00:00:00Z"})),
        )
        .await
        .unwrap();
    assert_eq!(stored["created_at"], json!("2000-01-01T00:00:00Z"));
    assert!(is_rfc3339_utc_seconds(&stored["updated_at"]));
}

#[tokio::test]
async fn with_timestamps_stamps_a_null_created_at() {
    let table = empty().await.with_timestamps();
    let stored = table
        .insert_value("1", &rec(json!({"name": "a", "created_at": null})))
        .await
        .unwrap();
    assert!(is_rfc3339_utc_seconds(&stored["created_at"]));
}

#[tokio::test]
async fn with_timestamps_updates_only_updated_at_on_patch() {
    let table = with_rows(vec![
        json!({"id": "1", "name": "a", "created_at": "2000-01-01T00:00:00Z"}),
    ])
    .await
    .with_timestamps();
    let patched = table
        .patch_value("1", &rec(json!({"name": "b"})))
        .await
        .unwrap();
    assert_eq!(patched["created_at"], json!("2000-01-01T00:00:00Z"));
    assert!(is_rfc3339_utc_seconds(&patched["updated_at"]));
    assert_eq!(patched["name"], json!("b"));
}

#[tokio::test]
async fn with_timestamps_rewrites_updated_at_on_every_write() {
    let table = with_rows(vec![
        json!({"id": "1", "name": "a", "updated_at": "2000-01-01T00:00:00Z"}),
    ])
    .await
    .with_timestamps();
    let replaced = table
        .replace_value(
            "1",
            &rec(json!({"name": "b", "updated_at": "2000-01-01T00:00:00Z"})),
        )
        .await
        .unwrap();
    assert_ne!(replaced["updated_at"], json!("2000-01-01T00:00:00Z"));
}

#[tokio::test]
async fn with_audit_stamps_the_named_columns() {
    let table = empty()
        .await
        .with_audit(Timestamps::new().created("inserted").updated("touched"));
    let stored = table
        .insert_value("1", &rec(json!({"name": "a"})))
        .await
        .unwrap();
    assert!(is_rfc3339_utc_seconds(&stored["inserted"]));
    assert!(is_rfc3339_utc_seconds(&stored["touched"]));
    assert!(stored.get("created_at").is_none());
    assert!(stored.get("updated_at").is_none());
}

#[tokio::test]
async fn timestamps_default_to_created_at_and_updated_at() {
    let table = empty().await.with_audit(Timestamps::default());
    let stored = table
        .insert_value("1", &rec(json!({"name": "a"})))
        .await
        .unwrap();
    assert!(stored.contains_key("created_at"));
    assert!(stored.contains_key("updated_at"));
}