mentat_script 1.18.0

Backend-independent mino mentat.store/* scripting glue for Mentat
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
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
//! The Datomic-model test suite for the `mentat.store/*` scripting surface,
//! written once and run against every [`ScriptBackend`] (plan § 1.19).
//!
//! Each function takes a `&mut mino_rs::Interpreter` that already has the store
//! prims installed (via [`crate::install`]) over some backend. The `mentat`
//! crate and `pg_mentat` each build such an interpreter over their real
//! storage and call these; `crates/script/tests/model.rs` runs them against an
//! in-memory fake. One suite, three backends — so the two real backends stop
//! drifting.
//!
//! This module is compiled into the library (not gated) so downstream test
//! crates can depend on it without a dev-dependency dance; it pulls in nothing
//! but the interpreter it is handed.

use mino_rs::Interpreter;

/// Seed a store-installed interpreter with the schema and Alice, binding `c` to
/// the conn handle. Backend-agnostic: it only evals the shared script.
pub fn seed(it: &mut Interpreter) {
    it.eval("(def c (mentat.store/open))").expect("open");
    it.eval_to_string(
        "(mentat.store/transact c \
           [{:db/ident :person/name :db/valueType :db.type/string \
             :db/cardinality :db.cardinality/one}])",
    )
    .expect("schema transact");
    it.eval_to_string("(mentat.store/transact c [{:person/name \"Alice\"}])")
        .expect("data transact");
}

/// The eid of the person named `name`, as a scalar-query result string.
pub fn eid_of(it: &mut Interpreter, name: &str) -> String {
    it.eval_to_string(&format!(
        "(mentat.store/q (mentat.store/db c) '[:find ?e . :where [?e :person/name \"{name}\"]])"
    ))
    .expect("eid query")
}

/// The first synthetic tx id (Mentat's `TX0`); real basis ids exceed it.
pub const TX0: i64 = 0x1000_0000;

pub fn db_is_an_immutable_value_not_the_conn(it: &mut Interpreter) {
    seed(it);
    assert_eq!(it.eval_to_string("c").unwrap(), "1");
    let db = it.eval_to_string("(mentat.store/db c)").unwrap();
    assert!(db.contains(":mentat.store/db true"), "{db}");
    assert!(db.contains(":mentat.store/basis-tx"), "{db}");
    assert!(db.contains(":mentat.store/conn 1"), "{db}");
    assert_ne!(db, "1");
    let basis = it
        .eval_to_string("(:mentat.store/basis-tx (mentat.store/db c))")
        .unwrap();
    assert!(basis.parse::<i64>().unwrap() > TX0, "basis {basis}");
}

pub fn q_takes_a_db_value(it: &mut Interpreter) {
    seed(it);
    assert_eq!(
        it.eval_to_string(
            "(mentat.store/q (mentat.store/db c) '[:find ?n :where [?e :person/name ?n]])"
        )
        .unwrap(),
        "#{[\"Alice\"]}"
    );
    assert_eq!(
        it.eval_to_string("(mentat.store/q c '[:find ?n :where [?e :person/name ?n]])")
            .unwrap(),
        "#{[\"Alice\"]}"
    );
}

pub fn pull_returns_a_map(it: &mut Interpreter) {
    seed(it);
    let eid = eid_of(it, "Alice");
    let pulled = it
        .eval_to_string(&format!(
            "(mentat.store/pull (mentat.store/db c) {eid} [:person/name])"
        ))
        .unwrap();
    // A keyword-keyed map carrying the pulled value. (The exact map shape is
    // backend-specific — pg may include extra keys — so assert the content.)
    assert!(pulled.starts_with('{'), "pull -> map: {pulled}");
    assert!(pulled.contains(":person/name \"Alice\""), "pull: {pulled}");
}

pub fn entity_returns_an_entity_map(it: &mut Interpreter) {
    seed(it);
    let eid = eid_of(it, "Alice");
    let ent = it
        .eval_to_string(&format!("(mentat.store/entity (mentat.store/db c) {eid})"))
        .unwrap();
    assert!(ent.contains(&format!(":db/id {eid}")), "{ent}");
    assert!(ent.contains(":person/name \"Alice\""), "{ent}");
}

pub fn read_returns_the_scalar(it: &mut Interpreter) {
    seed(it);
    let eid = eid_of(it, "Alice");
    assert_eq!(
        it.eval_to_string(&format!(
            "(mentat.store/read (mentat.store/db c) {eid} :person/name)"
        ))
        .unwrap(),
        "\"Alice\""
    );
}

pub fn datoms_returns_tuples(it: &mut Interpreter) {
    seed(it);
    let ds = it
        .eval_to_string("(mentat.store/datoms (mentat.store/db c))")
        .unwrap();
    // A vector of tuples that includes the Alice name assertion's value. (The
    // attribute place is a keyword on SQLite and an entid on pg — a real
    // backend difference — so assert only the portable facts.)
    assert!(ds.starts_with('['), "datoms: {ds}");
    assert!(
        ds.contains("\"Alice\""),
        "datoms should include Alice: {ds}"
    );
}

pub fn with_is_speculative_and_does_not_commit(it: &mut Interpreter) {
    seed(it);
    let before = it
        .eval_to_string("(mentat.store/q c '[:find ?n :where [?e :person/name ?n]])")
        .unwrap();
    assert_eq!(before, "#{[\"Alice\"]}");
    let with_result = it
        .eval_to_string("(mentat.store/with (mentat.store/db c) [{:person/name \"Bob\"}])")
        .unwrap();
    assert!(
        with_result.contains(":mentat.store/db-after"),
        "{with_result}"
    );
    assert!(
        with_result.contains(":mentat.store/tx-report"),
        "{with_result}"
    );
    let basis_now: i64 = it
        .eval_to_string("(:mentat.store/basis-tx (mentat.store/db c))")
        .unwrap()
        .parse()
        .unwrap();
    let db_after_basis: i64 = it
        .eval_to_string(
            "(:mentat.store/basis-tx (:mentat.store/db-after \
               (mentat.store/with (mentat.store/db c) [{:person/name \"Bob\"}])))",
        )
        .unwrap()
        .parse()
        .unwrap();
    assert!(db_after_basis > basis_now, "{db_after_basis} > {basis_now}");
    let after = it
        .eval_to_string(
            "(mentat.store/q (mentat.store/db c) '[:find ?n :where [?e :person/name ?n]])",
        )
        .unwrap();
    assert_eq!(after, "#{[\"Alice\"]}", "with must not commit");
}

pub fn as_of_and_since_reflect_the_basis(it: &mut Interpreter) {
    seed(it);
    let basis_alice: i64 = it
        .eval_to_string("(:mentat.store/basis-tx (mentat.store/db c))")
        .unwrap()
        .parse()
        .unwrap();
    it.eval_to_string("(mentat.store/transact c [{:person/name \"Bob\"}])")
        .unwrap();
    let basis_bob: i64 = it
        .eval_to_string("(:mentat.store/basis-tx (mentat.store/db c))")
        .unwrap()
        .parse()
        .unwrap();
    assert!(basis_bob > basis_alice);

    let as_of_alice = it
        .eval_to_string(&format!(
            "(mentat.store/datoms (mentat.store/as-of (mentat.store/db c) {basis_alice}))"
        ))
        .unwrap();
    assert!(as_of_alice.contains("Alice"), "{as_of_alice}");
    assert!(!as_of_alice.contains("Bob"), "{as_of_alice}");

    let as_of_bob = it
        .eval_to_string(&format!(
            "(mentat.store/datoms (mentat.store/as-of (mentat.store/db c) {basis_bob}))"
        ))
        .unwrap();
    assert!(
        as_of_bob.contains("Alice") && as_of_bob.contains("Bob"),
        "{as_of_bob}"
    );

    let since_alice = it
        .eval_to_string(&format!(
            "(mentat.store/datoms (mentat.store/since (mentat.store/db c) {basis_alice}))"
        ))
        .unwrap();
    assert!(since_alice.contains("Bob"), "{since_alice}");
    assert!(!since_alice.contains("Alice"), "{since_alice}");

    let as_of_db = it
        .eval_to_string(&format!(
            "(mentat.store/as-of (mentat.store/db c) {basis_alice})"
        ))
        .unwrap();
    assert!(
        as_of_db.contains(&format!(":mentat.store/as-of {basis_alice}")),
        "{as_of_db}"
    );
    let since_db = it
        .eval_to_string(&format!(
            "(mentat.store/since (mentat.store/db c) {basis_alice})"
        ))
        .unwrap();
    assert!(
        since_db.contains(&format!(":mentat.store/since {basis_alice}")),
        "{since_db}"
    );
}

/// Issue #328: `q` against an as-of / since db value runs the query on that
/// basis (temporal Datalog), on every backend, instead of erroring.
pub fn q_runs_against_as_of_and_since(it: &mut Interpreter) {
    seed(it);
    let basis_alice: i64 = it
        .eval_to_string("(:mentat.store/basis-tx (mentat.store/db c))")
        .unwrap()
        .parse()
        .unwrap();
    it.eval_to_string("(mentat.store/transact c [{:person/name \"Bob\"}])")
        .unwrap();

    let names = "'[:find ?n :where [?e :person/name ?n]]";
    let now = it
        .eval_to_string(&format!("(mentat.store/q (mentat.store/db c) {names})"))
        .unwrap();
    assert!(now.contains("Alice") && now.contains("Bob"), "{now}");

    let then = it
        .eval_to_string(&format!(
            "(mentat.store/q (mentat.store/as-of (mentat.store/db c) {basis_alice}) {names})"
        ))
        .unwrap();
    assert_eq!(then, "#{[\"Alice\"]}", "as-of must hide later facts");

    // q with :in inputs works on a historical basis too.
    let with_in = it
        .eval_to_string(&format!(
            "(mentat.store/q (mentat.store/as-of (mentat.store/db c) {basis_alice}) \
             '[:find ?e :in $ ?n :where [?e :person/name ?n]] \"Bob\")"
        ))
        .unwrap();
    assert_eq!(
        with_in, "#{}",
        "Bob did not exist as of Alice's basis: {with_in}"
    );
}

pub fn tx_report_has_the_datomic_shape(it: &mut Interpreter) {
    seed(it);
    let report = it
        .eval_to_string("(mentat.store/transact c [{:person/name \"Carol\"}])")
        .unwrap();
    assert!(report.contains(":mentat.store/tx-id"), "{report}");
    assert!(report.contains(":mentat.store/tempids"), "{report}");
    assert!(report.contains(":mentat.store/db-after"), "{report}");
}

/// The inst/uuid VALUE BUILDERS emit values that round-trip through the mino
/// reader. Backend-independent (no interpreter needed).
pub fn inst_and_uuid_builders_round_trip_through_the_reader() {
    use mino_rs::printer::print_str;
    use mino_rs::reader::read_one;
    let uuid = crate::values::uuid_value("12345678-1234-5678-1234-567812345678");
    assert_eq!(
        print_str(&uuid),
        "#uuid \"12345678-1234-5678-1234-567812345678\""
    );
    let inst = crate::values::inst_value("2017-01-01T00:00:00Z");
    assert_eq!(
        print_str(&inst),
        "(clojure.instant/read-instant-date \"2017-01-01T00:00:00Z\")"
    );
    for v in [uuid, inst] {
        let (v2, _) = read_one(&print_str(&v)).unwrap();
        assert_eq!(print_str(&v), print_str(&v2));
    }
}

// ---------------------------------------------------------------------------
// :in inputs, history, cas / retractEntity (Datomic-like layer, 1.10).
// ---------------------------------------------------------------------------

/// `(q db query arg ...)`: Datomic's `:in $ ?x` with the args after the query.
/// A scalar input filters the value place. Runs on every backend (the fake
/// understands `:in $ ?x` and `:in $ [?x ...]` on one clause).
pub fn q_takes_in_inputs(it: &mut Interpreter) {
    seed(it);
    it.eval_to_string("(mentat.store/transact c [{:person/name \"Bob\"}])")
        .unwrap();
    assert_eq!(
        it.eval_to_string(
            "(mentat.store/q (mentat.store/db c) \
               '[:find ?n :in $ ?n :where [?e :person/name ?n]] \"Bob\")"
        )
        .unwrap(),
        "#{[\"Bob\"]}"
    );
    // A collection input binds any of its values.
    let both = it
        .eval_to_string(
            "(mentat.store/q (mentat.store/db c) \
               '[:find ?n :in $ [?n ...] :where [?e :person/name ?n]] [\"Alice\" \"Bob\" \"Zed\"])",
        )
        .unwrap();
    assert!(
        both.contains("\"Alice\"") && both.contains("\"Bob\"") && !both.contains("Zed"),
        "{both}"
    );
    // A missing input is an error, not a silently unbound variable.
    assert!(it
        .eval(
            "(mentat.store/q (mentat.store/db c) '[:find ?n :in $ ?n :where [?e :person/name ?n]])"
        )
        .is_err());
}

/// Seed people with ages, bound to `c`. Real engines only (the fake is a toy).
fn seed_people(it: &mut Interpreter) {
    it.eval("(def c (mentat.store/open))").expect("open");
    it.eval_to_string(
        "(mentat.store/transact c \
           [{:db/ident :person/name :db/valueType :db.type/string \
             :db/cardinality :db.cardinality/one :db/unique :db.unique/identity :db/index true} \
            {:db/ident :person/age :db/valueType :db.type/long :db/cardinality :db.cardinality/one} \
            {:db/ident :person/friend :db/valueType :db.type/ref :db/cardinality :db.cardinality/many}])",
    )
    .expect("schema");
    it.eval_to_string(
        "(mentat.store/transact c \
           [{:db/id \"a\" :person/name \"Alice\" :person/age 30 :person/friend \"b\"} \
            {:db/id \"b\" :person/name \"Bob\" :person/age 40}])",
    )
    .expect("people");
}

/// Mixed inputs on a real engine: a ref-typed scalar, a collection, and a
/// relation, bound by position; an entity-position integer is a ref.
pub fn q_mixed_inputs(it: &mut Interpreter) {
    seed_people(it);
    let bob = it
        .eval_to_string(
            "(mentat.store/q (mentat.store/db c) '[:find ?e . :where [?e :person/name \"Bob\"]])",
        )
        .unwrap();
    assert_eq!(
        it.eval_to_string(&format!(
            "(mentat.store/q (mentat.store/db c) \
               '[:find ?n . :in $ ?f [?a ...] :where [?e :person/friend ?f] [?e :person/age ?a] [?e :person/name ?n]] \
               {bob} [30 31])"
        ))
        .unwrap(),
        "\"Alice\""
    );
    let rel = it
        .eval_to_string(
            "(mentat.store/q (mentat.store/db c) \
               '[:find ?n :in $ [[?n ?a]] :where [?e :person/name ?n] [?e :person/age ?a]] \
               [[\"Alice\" 30] [\"Bob\" 41]])",
        )
        .unwrap();
    assert_eq!(rel, "#{[\"Alice\"]}");
}

/// The eid of a seeded person, as a number string.
fn person(it: &mut Interpreter, name: &str) -> String {
    it.eval_to_string(&format!(
        "(mentat.store/q (mentat.store/db c) '[:find ?e . :where [?e :person/name \"{name}\"]])"
    ))
    .unwrap()
}

/// History patterns: `[?e ?a ?v ?tx ?added]` sees retractions (`false`) and
/// assertions (`true`) across transactions.
pub fn history_patterns_see_added(it: &mut Interpreter) {
    seed_people(it);
    let alice = person(it, "Alice");
    it.eval_to_string(&format!(
        "(mentat.store/transact c [[:db/add {alice} :person/age 31]])"
    ))
    .unwrap();
    let h = it
        .eval_to_string(
            "(mentat.store/q (mentat.store/db c) \
               '[:find ?v ?added :where [?e :person/age ?v ?tx ?added] [?e :person/name \"Alice\"]])",
        )
        .unwrap();
    for want in ["[30 true]", "[30 false]", "[31 true]"] {
        assert!(h.contains(want), "history should contain {want}: {h}");
    }
}

/// `:db/cas` swaps only from the expected old value; `:db/retractEntity`
/// removes every datom of the entity AND every ref pointing at it (Datomic's
/// semantics; issue #326). Both accept a lookup ref `[:unique/attr v]` in the
/// entity place (issue #327).
pub fn cas_and_retract_entity(it: &mut Interpreter) {
    seed_people(it);
    let (alice, bob) = (person(it, "Alice"), person(it, "Bob"));
    let age = "(mentat.store/q (mentat.store/db c) \
               '[:find ?a . :where [?e :person/name \"Alice\"] [?e :person/age ?a]])";
    it.eval_to_string(&format!(
        "(mentat.store/transact c [[:db/cas {alice} :person/age 30 31]])"
    ))
    .expect("cas from the right value");
    assert_eq!(it.eval_to_string(age).unwrap(), "31");
    assert!(
        it.eval(&format!(
            "(mentat.store/transact c [[:db/cas {alice} :person/age 30 32]])"
        ))
        .is_err(),
        "cas from a stale value must fail"
    );
    assert_eq!(it.eval_to_string(age).unwrap(), "31");

    // A lookup ref names Alice in the entity place of cas.
    it.eval_to_string(
        "(mentat.store/transact c [[:db/cas [:person/name \"Alice\"] :person/age 31 32]])",
    )
    .expect("cas via a lookup ref");
    assert_eq!(it.eval_to_string(age).unwrap(), "32");

    // Alice -> :person/friend -> Bob is an inbound ref to Bob.
    let friends = "(mentat.store/q (mentat.store/db c) \
                   '[:find ?f . :where [?e :person/name \"Alice\"] [?e :person/friend ?f]])";
    assert_eq!(it.eval_to_string(friends).unwrap(), bob);

    // retractEntity via a lookup ref.
    it.eval_to_string("(mentat.store/transact c [[:db/retractEntity [:person/name \"Bob\"]]])")
        .expect("retractEntity via a lookup ref");
    assert_eq!(person(it, "Bob"), "nil");
    // Bob's own datoms are all gone:
    assert_eq!(
        it.eval_to_string(&format!(
            "(mentat.store/q (mentat.store/db c) '[:find ?a . :where [{bob} :person/age ?a]])"
        ))
        .unwrap(),
        "nil"
    );
    // ...and so is the ref TO him, while Alice herself remains.
    assert_eq!(
        it.eval_to_string(friends).unwrap(),
        "nil",
        "inbound ref retracted"
    );
    assert_eq!(person(it, "Alice"), alice);
}

/// User-defined transaction functions (issues #325, #333): an ident carrying
/// `:db/fn` (mino source of `(fn [db & args] ...)` returning tx-data) is
/// invoked as `[:my/fn arg ...]` inside a transaction, on every backend.
pub fn transaction_functions(it: &mut Interpreter) {
    seed_people(it);
    let age = |it: &mut Interpreter, who: &str| {
        it.eval_to_string(&format!(
            "(mentat.store/q (mentat.store/db c) \
               '[:find ?a . :where [?e :person/name \"{who}\"] [?e :person/age ?a]])"
        ))
        .unwrap()
    };

    // Install: a fn that reads the db (as of the start of the tx) with q and
    // returns a lookup-ref cas, so a stale call aborts.
    it.eval_to_string(
        "(mentat.store/transact c \
           [{:db/ident :person/birthday \
             :db/fn \"(fn [db who] \
                        (let [a (ffirst (mentat.store/q db \
                                  '[:find ?a :in $ ?n :where [?e :person/name ?n] [?e :person/age ?a]] \
                                  who))] \
                          [[:db/cas [:person/name who] :person/age a (inc a)]]))\"}])",
    )
    .expect("install :person/birthday");

    it.eval_to_string("(mentat.store/transact c [[:person/birthday \"Alice\"]])")
        .expect("invoke");
    assert_eq!(age(it, "Alice"), "31");

    // Spliced with other tx-data in the same transaction, and nested: a fn
    // that returns a call to another fn.
    it.eval_to_string(
        "(mentat.store/transact c \
           [{:db/ident :person/two-birthdays \
             :db/fn \"(fn [db who] [[:person/birthday who]])\"}])",
    )
    .expect("install nested fn");
    it.eval_to_string(
        "(mentat.store/transact c [[:person/two-birthdays \"Bob\"] {:person/name \"Carol\" :person/age 7}])",
    )
    .expect("nested invoke");
    assert_eq!(age(it, "Bob"), "41");
    assert_eq!(age(it, "Carol"), "7");

    // A fn that throws aborts the whole transaction, with the fn named.
    it.eval_to_string(
        "(mentat.store/transact c [{:db/ident :person/boom :db/fn \"(fn [db] (throw (ex-info \\\"nope\\\" {})))\"}])",
    )
    .expect("install :person/boom");
    let err = it
        .eval_to_string(
            "(mentat.store/transact c [[:person/boom] {:person/name \"Dan\" :person/age 1}])",
        )
        .expect_err("a throwing tx-fn aborts the tx");
    assert!(
        err.contains("txfn-error") && err.contains(":person/boom"),
        "{err}"
    );
    assert_eq!(age(it, "Dan"), "nil", "nothing from the aborted tx");

    // Self-recursion is bounded.
    it.eval_to_string(
        "(mentat.store/transact c [{:db/ident :person/forever :db/fn \"(fn [db] [[:person/forever]])\"}])",
    )
    .expect("install :person/forever");
    let err = it
        .eval_to_string("(mentat.store/transact c [[:person/forever]])")
        .expect_err("unbounded recursion");
    assert!(err.contains("txfn-depth"), "{err}");

    // Sandboxed: no host filesystem.
    it.eval_to_string(
        "(mentat.store/transact c [{:db/ident :person/escape :db/fn \"(fn [db] (slurp \\\"/etc/passwd\\\") [])\"}])",
    )
    .expect("install :person/escape");
    let err = it
        .eval_to_string("(mentat.store/transact c [[:person/escape]])")
        .expect_err("slurp must be unavailable");
    assert!(err.contains("txfn-error"), "{err}");
}

/// `pull`, `entities` and a find-pull `q` on an as-of / since db read that
/// basis. Alice's age changes after T: as-of T must show the old value, since
/// T only the new one. Before 1.18.0 pg and DuckDB returned the current value
/// here and the embedded engine refused.
pub fn pull_reads_the_as_of_and_since_basis(it: &mut Interpreter) {
    seed_people(it);
    let alice = person(it, "Alice");
    let t: i64 = it
        .eval_to_string("(:mentat.store/basis-tx (mentat.store/db c))")
        .unwrap()
        .parse()
        .unwrap();
    it.eval_to_string(&format!(
        "(mentat.store/transact c [[:db/add {alice} :person/age 31] {{:person/name \"Carol\"}}])"
    ))
    .unwrap();
    let as_of = format!("(mentat.store/as-of (mentat.store/db c) {t})");
    let since = format!("(mentat.store/since (mentat.store/db c) {t})");

    let now = it
        .eval_to_string(&format!(
            "(:person/age (mentat.store/pull (mentat.store/db c) {alice} '[:person/age]))"
        ))
        .unwrap();
    assert_eq!(now, "31");
    let then = it
        .eval_to_string(&format!(
            "(:person/age (mentat.store/pull {as_of} {alice} '[:person/name :person/age]))"
        ))
        .unwrap();
    assert_eq!(then, "30", "as-of T pulls the value before the change");
    let then_name = it
        .eval_to_string(&format!(
            "(:person/name (mentat.store/pull {as_of} {alice} '[:person/name]))"
        ))
        .unwrap();
    assert_eq!(then_name, "\"Alice\"");

    // since T: only what was asserted after T, so the new age and no name.
    let later = it
        .eval_to_string(&format!(
            "(mentat.store/pull {since} {alice} '[:person/name :person/age])"
        ))
        .unwrap();
    assert!(later.contains(":person/age 31"), "{later}");
    assert!(!later.contains("Alice"), "{later}");

    // entity on an as-of db shows the old value too.
    let ent = it
        .eval_to_string(&format!(
            "(:person/age (mentat.store/entity {as_of} {alice}))"
        ))
        .unwrap();
    assert_eq!(ent, "30", "entity as of T");

    // A find-pull inside q reads the db's basis too.
    let q_then = it
        .eval_to_string(&format!(
            "(:person/age (mentat.store/q {as_of} \
               '[:find (pull ?e [:person/age]) . :where [?e :person/name \"Alice\"]]))"
        ))
        .unwrap();
    assert_eq!(q_then, "30", "find-pull under as-of");

    // entities: Carol did not exist as of T.
    let ents = |it: &mut Interpreter, db: &str| {
        it.eval_to_string(&format!(
            "(count (mentat.store/entities {db} :person/name))"
        ))
        .unwrap()
    };
    assert_eq!(ents(it, "(mentat.store/db c)"), "3");
    assert_eq!(ents(it, &as_of), "2");
    assert_eq!(ents(it, &since), "1");
}

/// Map specs in a pull pattern, `{:attr [sub-pattern]}`, forward
/// (cardinality-one and -many) and reverse, nested, on every backend. Each
/// nested map carries `:db/id`; on an as-of db the nesting reads that basis.
pub fn pull_nested_map_specs(it: &mut Interpreter) {
    seed_people(it);
    it.eval_to_string(
        "(mentat.store/transact c [{:db/ident :person/best :db/valueType :db.type/ref \
           :db/cardinality :db.cardinality/one}])",
    )
    .unwrap();
    let (alice, bob) = (person(it, "Alice"), person(it, "Bob"));
    it.eval_to_string(&format!(
        "(mentat.store/transact c [[:db/add {bob} :person/best {alice}]])"
    ))
    .unwrap();
    let t: i64 = it
        .eval_to_string("(:mentat.store/basis-tx (mentat.store/db c))")
        .unwrap()
        .parse()
        .unwrap();
    it.eval_to_string(&format!(
        "(mentat.store/transact c [[:db/add {alice} :person/age 31]])"
    ))
    .unwrap();
    let pull = |it: &mut Interpreter, db: &str, e: &str, pat: &str, path: &str| {
        it.eval_to_string(&format!(
            "(get-in (mentat.store/pull {db} {e} '{pat}) {path})"
        ))
        .unwrap()
    };
    let now = "(mentat.store/db c)";
    let then = format!("(mentat.store/as-of (mentat.store/db c) {t})");

    // Cardinality-many forward: a vector of maps.
    let pat = "[:person/name {:person/friend [:person/name :person/age]}]";
    assert_eq!(
        pull(it, now, &alice, pat, "[:person/friend 0 :person/name]"),
        "\"Bob\""
    );
    assert_eq!(pull(it, now, &alice, pat, "[:person/friend 0 :db/id]"), bob);
    assert_eq!(pull(it, now, &alice, pat, "[:person/name]"), "\"Alice\"");
    // Cardinality-one forward: one map, nested two deep.
    let pat = "[{:person/best [:person/age {:person/friend [:person/name]}]}]";
    assert_eq!(pull(it, now, &bob, pat, "[:person/best :db/id]"), alice);
    assert_eq!(pull(it, now, &bob, pat, "[:person/best :person/age]"), "31");
    assert_eq!(
        pull(
            it,
            now,
            &bob,
            pat,
            "[:person/best :person/friend 0 :person/name]"
        ),
        "\"Bob\""
    );
    // ...and on an as-of db: Alice's age before the change.
    assert_eq!(
        pull(it, &then, &bob, pat, "[:person/best :person/age]"),
        "30"
    );
    // Reverse: who has Bob as a friend.
    let pat = "[{:person/_friend [:person/name]}]";
    assert_eq!(
        pull(it, now, &bob, pat, "[:person/_friend 0 :person/name]"),
        "\"Alice\""
    );
    assert_eq!(
        pull(it, now, &bob, pat, "[:person/_friend 0 :db/id]"),
        alice
    );
    // No ref: the key is absent.
    assert_eq!(
        pull(
            it,
            now,
            &alice,
            "[{:person/best [:person/name]}]",
            "[:person/best]"
        ),
        "nil"
    );
    // A find-pull with a map spec.
    assert_eq!(
        it.eval_to_string(
            "(get-in (mentat.store/q (mentat.store/db c) \
               '[:find (pull ?e [{:person/best [:person/name]}]) . :where [?e :person/name \"Bob\"]]) \
               [:person/best :person/name])"
        )
        .unwrap(),
        "\"Alice\""
    );
}

/// t1: n 1, tags p q, s "a"; t2: n 2, tag p retracted, s retracted;
/// t3: n 3, tag r. Returns (x, t1, t2, t3).
fn seed_t364(it: &mut Interpreter) -> (String, i64, i64, i64) {
    it.eval("(def c (mentat.store/open))").expect("open");
    it.eval_to_string(
        "(mentat.store/transact c \
           [{:db/ident :t364/n :db/valueType :db.type/long :db/cardinality :db.cardinality/one} \
            {:db/ident :t364/tag :db/valueType :db.type/string :db/cardinality :db.cardinality/many} \
            {:db/ident :t364/s :db/valueType :db.type/string :db/cardinality :db.cardinality/one}])",
    )
    .expect("schema");
    let basis = |it: &mut Interpreter| -> i64 {
        it.eval_to_string("(:mentat.store/basis-tx (mentat.store/db c))")
            .unwrap()
            .parse()
            .unwrap()
    };
    it.eval_to_string(
        "(mentat.store/transact c [{:db/id \"x\" :t364/n 1 :t364/s \"a\"} \
           [:db/add \"x\" :t364/tag \"p\"] [:db/add \"x\" :t364/tag \"q\"]])",
    )
    .unwrap();
    let t1 = basis(it);
    let x = it
        .eval_to_string("(mentat.store/q (mentat.store/db c) '[:find ?e . :where [?e :t364/n _]])")
        .unwrap();
    it.eval_to_string(&format!(
        "(mentat.store/transact c [[:db/add {x} :t364/n 2] [:db/retract {x} :t364/tag \"p\"] \
           [:db/retract {x} :t364/s \"a\"]])"
    ))
    .unwrap();
    let t2 = basis(it);
    it.eval_to_string(&format!(
        "(mentat.store/transact c [[:db/add {x} :t364/n 3] [:db/add {x} :t364/tag \"r\"]])"
    ))
    .unwrap();
    (x, t1, t2, basis(it))
}

/// `(as-of (since db S) T)` etc.: `None` leaves that bound off.
fn db_on(as_of: Option<i64>, since: Option<i64>) -> String {
    let mut d = "(mentat.store/db c)".to_string();
    if let Some(t) = as_of {
        d = format!("(mentat.store/as-of {d} {t})");
    }
    if let Some(s) = since {
        d = format!("(mentat.store/since {d} {s})");
    }
    d
}

/// `q` as a sorted vector, so expected values are exact.
fn q_sorted(it: &mut Interpreter, d: &str, query: &str) -> String {
    it.eval_to_string(&format!("(vec (sort (mentat.store/q {d} '{query})))"))
        .unwrap_or_else(|e| panic!("{d} {query}: {e}"))
}

const Q364_N: &str = "[:find [?v ...] :where [_ :t364/n ?v]]";
const Q364_TAG: &str = "[:find [?v ...] :where [_ :t364/tag ?v]]";
const Q364_S: &str = "[:find [?v ...] :where [_ :t364/s ?v]]";
const Q364_HIST: &str = "[:find ?v ?added :where [_ :t364/n ?v _ ?added]]";

fn check_q364(it: &mut Interpreter, d: &str, n: &str, tag: &str, s: &str) {
    assert_eq!(q_sorted(it, d, Q364_N), n, "{d} :t364/n");
    assert_eq!(q_sorted(it, d, Q364_TAG), tag, "{d} :t364/tag");
    assert_eq!(q_sorted(it, d, Q364_S), s, "{d} :t364/s");
}

/// As of T hides a value retracted at or before T, cardinality-one and
/// -many, replaced or plainly retracted (Datomic's as-of). Before 1.18.0
/// pg's edn_q showed retracted values unless a newer cardinality-one value
/// replaced them.
pub fn as_of_hides_retracted_values(it: &mut Interpreter) {
    let (_, t1, t2, t3) = seed_t364(it);
    check_q364(
        it,
        &db_on(Some(t1), None),
        "[1]",
        "[\"p\" \"q\"]",
        "[\"a\"]",
    );
    check_q364(it, &db_on(Some(t2), None), "[2]", "[\"q\"]", "[]");
    check_q364(it, &db_on(Some(t3), None), "[3]", "[\"q\" \"r\"]", "[]");
    // A history pattern as of T is the log up to T, retractions included.
    assert_eq!(
        q_sorted(it, &db_on(Some(t2), None), Q364_HIST),
        "[[1 false] [1 true] [2 true]]"
    );
}

/// A value retracted and asserted again later: hidden as of the retraction,
/// visible again as of the re-assertion, and `since` the retraction shows it
/// (the live assertion is the later one).
pub fn as_of_sees_a_value_reasserted_after_retraction(it: &mut Interpreter) {
    let (x, t1, t2, t3) = seed_t364(it);
    // t4: tag "p" (retracted at t2) is asserted again.
    it.eval_to_string(&format!(
        "(mentat.store/transact c [[:db/add {x} :t364/tag \"p\"]])"
    ))
    .unwrap();
    let t4: i64 = it
        .eval_to_string("(:mentat.store/basis-tx (mentat.store/db c))")
        .unwrap()
        .parse()
        .unwrap();
    let tags = |it: &mut Interpreter, d: &str| q_sorted(it, d, Q364_TAG);
    assert_eq!(tags(it, &db_on(Some(t1), None)), "[\"p\" \"q\"]");
    assert_eq!(tags(it, &db_on(Some(t2), None)), "[\"q\"]");
    assert_eq!(tags(it, &db_on(Some(t3), None)), "[\"q\" \"r\"]");
    assert_eq!(tags(it, &db_on(Some(t4), None)), "[\"p\" \"q\" \"r\"]");
    assert_eq!(tags(it, &db_on(None, Some(t3))), "[\"p\"]");
    assert_eq!(tags(it, &db_on(None, Some(t1))), "[\"p\" \"r\"]");
    assert_eq!(tags(it, &db_on(Some(t4), Some(t2))), "[\"p\" \"r\"]");
    assert_eq!(tags(it, &db_on(Some(t3), Some(t1))), "[\"r\"]");

    // Retract and re-assert "q" in one transaction. Datomic and the embedded
    // transactor refuse it (add/retract conflict); pg accepts it and the
    // retraction wins (a transactor difference, not a read-rule one). Either
    // way, as of that transaction reads what current state reads.
    let same = it.eval_to_string(&format!(
        "(mentat.store/transact c [[:db/retract {x} :t364/tag \"q\"] [:db/add {x} :t364/tag \"q\"]])"
    ));
    if same.is_ok() {
        let now = "(mentat.store/db c)";
        let t5: i64 = it
            .eval_to_string(&format!("(:mentat.store/basis-tx {now})"))
            .unwrap()
            .parse()
            .unwrap();
        assert_eq!(tags(it, &db_on(Some(t5), None)), tags(it, now));
    }
}

/// `missing?` and `get-else` read the db's basis like any pattern: as of t1
/// :t364/s is "a"; it was retracted at t2. Since S they see only the current
/// datoms transacted after S, so a value asserted at or before S is missing.
pub fn missing_and_get_else_read_the_basis(it: &mut Interpreter) {
    let (x, t1, t2, _) = seed_t364(it);
    let missing = "[:find [?e ...] :where [?e :t364/n _] [(missing? $ ?e :t364/s)]]";
    let get_else = "[:find [?s ...] :where [?e :t364/n _] [(get-else $ ?e :t364/s \"none\") ?s]]";
    let ex = format!("[{x}]");
    assert_eq!(q_sorted(it, &db_on(Some(t1), None), missing), "[]");
    assert_eq!(q_sorted(it, &db_on(Some(t2), None), missing), ex);
    assert_eq!(q_sorted(it, &db_on(Some(t1), None), get_else), "[\"a\"]");
    assert_eq!(q_sorted(it, &db_on(Some(t2), None), get_else), "[\"none\"]");

    // t4: :t364/s "b"; t5: :t364/n 4. Now s is live, so since t4 (s asserted
    // at t4, n at t5) differs from current state.
    let basis = |it: &mut Interpreter| -> i64 {
        it.eval_to_string("(:mentat.store/basis-tx (mentat.store/db c))")
            .unwrap()
            .parse()
            .unwrap()
    };
    it.eval_to_string(&format!(
        "(mentat.store/transact c [[:db/add {x} :t364/s \"b\"]])"
    ))
    .unwrap();
    let t4 = basis(it);
    it.eval_to_string(&format!(
        "(mentat.store/transact c [[:db/add {x} :t364/n 4]])"
    ))
    .unwrap();
    let t5 = basis(it);
    assert_eq!(q_sorted(it, &db_on(None, None), get_else), "[\"b\"]");
    assert_eq!(q_sorted(it, &db_on(None, None), missing), "[]");
    assert_eq!(q_sorted(it, &db_on(None, Some(t4)), get_else), "[\"none\"]");
    assert_eq!(q_sorted(it, &db_on(None, Some(t4)), missing), ex);
    assert_eq!(
        q_sorted(it, &db_on(None, Some(t4 - 1)), get_else),
        "[\"b\"]"
    );
    assert_eq!(q_sorted(it, &db_on(None, Some(t4 - 1)), missing), "[]");
    // Both bounds: as of t5, since t4.
    assert_eq!(
        q_sorted(it, &db_on(Some(t5), Some(t4)), get_else),
        "[\"none\"]"
    );
    assert_eq!(q_sorted(it, &db_on(Some(t5), Some(t4)), missing), ex);
}

/// Datomic's `since S` (issue #364): the current datoms whose tx is after S,
/// so a value added after S and since replaced is gone. Before 1.18.0
/// `since t1` below returned [1 2 3] on SQLite and DuckDB (retraction rows
/// counted) and [2 3] on pg (replaced values counted). A 5-place history
/// pattern under since still reads the log after S, retractions included.
pub fn since_reads_current_datoms_added_after_t(it: &mut Interpreter) {
    let (x, t1, t2, t3) = seed_t364(it);
    check_q364(it, &db_on(None, Some(t1)), "[3]", "[\"r\"]", "[]");
    check_q364(it, &db_on(None, Some(t2)), "[3]", "[\"r\"]", "[]");
    check_q364(it, &db_on(None, Some(t3)), "[]", "[]", "[]");
    assert_eq!(
        q_sorted(it, &db_on(None, Some(t1)), Q364_HIST),
        "[[1 false] [2 false] [2 true] [3 true]]"
    );
    // read and pull agree with q.
    let since = db_on(None, Some(t1));
    assert_eq!(
        it.eval_to_string(&format!("(mentat.store/read {since} {x} :t364/n)"))
            .unwrap(),
        "3"
    );
    assert_eq!(
        it.eval_to_string(&format!(
            "(let [m (mentat.store/pull {since} {x} '[:t364/n :t364/tag :t364/s])] \
               [(:t364/n m) (vec (sort (:t364/tag m))) (:t364/s m)])"
        ))
        .unwrap(),
        "[3 [\"r\"] nil]"
    );
}

/// `(since (as-of db T) S)`: the assertions with S < tx <= T not retracted by
/// T, in either order, for q, pull, read and entities; a history pattern sees
/// the log with S < tx <= T. Before 1.18.0 pg raised "mutually exclusive" and
/// SQLite and DuckDB dropped `since`.
pub fn as_of_and_since_together(it: &mut Interpreter) {
    let (x, t1, t2, t3) = seed_t364(it);
    check_q364(it, &db_on(Some(t2), Some(t1)), "[2]", "[]", "[]");
    check_q364(it, &db_on(Some(t3), Some(t1)), "[3]", "[\"r\"]", "[]");
    check_q364(it, &db_on(Some(t3), Some(t2)), "[3]", "[\"r\"]", "[]");
    check_q364(it, &db_on(Some(t1), Some(t1)), "[]", "[]", "[]");
    // Order doesn't matter.
    let swapped =
        format!("(mentat.store/as-of (mentat.store/since (mentat.store/db c) {t1}) {t2})");
    assert_eq!(q_sorted(it, &swapped, Q364_N), "[2]");
    assert_eq!(
        q_sorted(it, &db_on(Some(t2), Some(t1)), Q364_HIST),
        "[[1 false] [2 true]]"
    );

    let pull = |it: &mut Interpreter, d: &str| {
        it.eval_to_string(&format!(
            "(let [m (mentat.store/pull {d} {x} '[:t364/n :t364/tag :t364/s])] \
               [(:t364/n m) (vec (sort (:t364/tag m))) (:t364/s m)])"
        ))
        .unwrap_or_else(|e| panic!("pull {d}: {e}"))
    };
    assert_eq!(pull(it, &db_on(Some(t2), Some(t1))), "[2 [] nil]");
    assert_eq!(pull(it, &db_on(Some(t3), Some(t1))), "[3 [\"r\"] nil]");
    let ents = |it: &mut Interpreter, d: &str| {
        it.eval_to_string(&format!("(count (mentat.store/entities {d} :t364/tag))"))
            .unwrap()
    };
    assert_eq!(ents(it, &db_on(Some(t2), Some(t1))), "0");
    assert_eq!(ents(it, &db_on(Some(t3), Some(t1))), "1");
    let read = |it: &mut Interpreter, d: &str| {
        it.eval_to_string(&format!("(mentat.store/read {d} {x} :t364/n)"))
            .unwrap()
    };
    assert_eq!(read(it, &db_on(Some(t2), Some(t1))), "2");
    assert_eq!(read(it, &db_on(Some(t1), Some(t1))), "nil");
    let entity = it
        .eval_to_string(&format!(
            "(:t364/n (mentat.store/entity {} {x}))",
            db_on(Some(t2), Some(t1))
        ))
        .unwrap();
    assert_eq!(entity, "2");
}

/// A pull pattern naming an attribute the schema doesn't have pulls nothing
/// for it, on every backend (Datomic does the same). Before 1.18.0 the
/// embedded backend's script `pull` raised "unknown attribute".
pub fn pull_of_an_unknown_attribute_is_empty(it: &mut Interpreter) {
    seed(it);
    let eid = eid_of(it, "Alice");
    let pulled = it
        .eval_to_string(&format!(
            "(dissoc (mentat.store/pull (mentat.store/db c) {eid} '[:no/such :person/name]) :db/id)"
        ))
        .unwrap();
    assert_eq!(pulled, "{:person/name \"Alice\"}");
    let none = it
        .eval_to_string(&format!(
            "(dissoc (mentat.store/pull (mentat.store/db c) {eid} '[:no/such]) :db/id)"
        ))
        .unwrap();
    assert_eq!(none, "{}");
}

/// t1: :t364or/n 1, :t364or/m 10; t2: n 2; t3: n 3; t4: n 1 again.
/// Returns (x, [t1, t2, t3, t4]).
fn seed_t364_or(it: &mut Interpreter) -> (String, [i64; 4]) {
    it.eval("(def c (mentat.store/open))").expect("open");
    it.eval_to_string(
        "(mentat.store/transact c \
           [{:db/ident :t364or/n :db/valueType :db.type/long :db/cardinality :db.cardinality/one} \
            {:db/ident :t364or/m :db/valueType :db.type/long :db/cardinality :db.cardinality/one}])",
    )
    .expect("schema");
    let basis = |it: &mut Interpreter| -> i64 {
        it.eval_to_string("(:mentat.store/basis-tx (mentat.store/db c))")
            .unwrap()
            .parse()
            .unwrap()
    };
    it.eval_to_string("(mentat.store/transact c [{:db/id \"x\" :t364or/n 1 :t364or/m 10}])")
        .unwrap();
    let t1 = basis(it);
    let x = it
        .eval_to_string(
            "(mentat.store/q (mentat.store/db c) '[:find ?e . :where [?e :t364or/m _]])",
        )
        .unwrap();
    let mut ts = [t1, 0, 0, 0];
    for (i, n) in [2, 3, 1].into_iter().enumerate() {
        it.eval_to_string(&format!(
            "(mentat.store/transact c [[:db/add {x} :t364or/n {n}]])"
        ))
        .unwrap();
        ts[i + 1] = basis(it);
    }
    (x, ts)
}

/// An `or` (and an `or-join`, and an `or` inside `not`) reads the db's
/// basis like any pattern, with Datomic's as-of / since meaning. Before
/// 1.18.0 SQLite and DuckDB answered an `or` whose arms are plain patterns
/// on the same table from current state under as-of and since.
pub fn or_reads_the_basis(it: &mut Interpreter) {
    let (x, [t1, t2, t3, t4]) = seed_t364_or(it);
    let or = "[:find [?v ...] :where (or [?e :t364or/n ?v] [?e :t364or/m ?v])]";
    let cases: [(Option<i64>, Option<i64>, &str); 9] = [
        (None, None, "[1 10]"),
        (Some(t1), None, "[1 10]"),
        (Some(t2), None, "[2 10]"),
        (Some(t3), None, "[3 10]"),
        (None, Some(t1), "[1]"),
        (None, Some(t3), "[1]"),
        (None, Some(t4), "[]"),
        (Some(t2), Some(t1), "[2]"),
        (Some(t3), Some(t2), "[3]"),
    ];
    for (as_of, since, want) in cases {
        assert_eq!(
            q_sorted(it, &db_on(as_of, since), or),
            want,
            "{as_of:?} {since:?}"
        );
    }

    // A fully unified or-join (the same shape as an `or`).
    let or_join = "[:find [?e ...] :where (or-join [?e] [?e :t364or/n 2] [?e :t364or/n 3])]";
    let ex = format!("[{x}]");
    assert_eq!(q_sorted(it, &db_on(None, None), or_join), "[]");
    assert_eq!(q_sorted(it, &db_on(Some(t1), None), or_join), "[]");
    assert_eq!(q_sorted(it, &db_on(Some(t2), None), or_join), ex);
    assert_eq!(q_sorted(it, &db_on(Some(t3), None), or_join), ex);
    assert_eq!(q_sorted(it, &db_on(None, Some(t1)), or_join), "[]");
    assert_eq!(q_sorted(it, &db_on(Some(t3), Some(t2)), or_join), ex);
    assert_eq!(q_sorted(it, &db_on(Some(t3), Some(t3)), or_join), "[]");
}

/// An `or` inside `not` reads the db's basis (as [`or_reads_the_basis`]).
/// Not run on pg, which refuses `(not (or ...))` on any basis.
pub fn not_or_reads_the_basis(it: &mut Interpreter) {
    let (x, [t1, t2, t3, _]) = seed_t364_or(it);
    let ex = format!("[{x}]");
    let not_n =
        "[:find [?e ...] :where [?e :t364or/m _] (not (or [?e :t364or/n 2] [?e :t364or/n 3]))]";
    assert_eq!(q_sorted(it, &db_on(None, None), not_n), ex);
    assert_eq!(q_sorted(it, &db_on(Some(t1), None), not_n), ex);
    assert_eq!(q_sorted(it, &db_on(Some(t2), None), not_n), "[]");
    assert_eq!(q_sorted(it, &db_on(Some(t3), None), not_n), "[]");
    // Since t3 :t364or/m (asserted at t1) is outside the window, so the `or`
    // can't match and `not` keeps x.
    let not_m =
        "[:find [?e ...] :where [?e :t364or/n _] (not (or [?e :t364or/m 10] [?e :t364or/m 11]))]";
    assert_eq!(q_sorted(it, &db_on(None, None), not_m), "[]");
    assert_eq!(q_sorted(it, &db_on(None, Some(t3)), not_m), ex);
    assert_eq!(q_sorted(it, &db_on(Some(t3), Some(t1)), not_m), ex);
    assert_eq!(q_sorted(it, &db_on(Some(t3), None), not_m), "[]");
}

/// Issue #362: retracting a value an attribute doesn't have changes nothing: on a
/// cardinality-one attribute (it used to retract the current value on the embedded
/// engine), on a cardinality-many attribute, and on a ref given as a lookup ref. No
/// retraction is logged (pg_mentat used to log one) and the report counts nothing.
pub fn retracting_an_absent_value_is_a_no_op(it: &mut Interpreter) {
    seed_people(it);
    it.eval_to_string(
        "(mentat.store/transact c \
           [{:db/ident :person/best :db/valueType :db.type/ref :db/cardinality :db.cardinality/one} \
            {:db/ident :person/tag :db/valueType :db.type/string :db/cardinality :db.cardinality/many}])",
    )
    .expect("schema");
    it.eval_to_string(
        "(mentat.store/transact c [{:db/id [:person/name \"Alice\"] \
           :person/best [:person/name \"Bob\"] :person/tag [\"x\" \"y\"]}])",
    )
    .expect("data");
    let q = |it: &mut Interpreter, query: &str| {
        it.eval_to_string(&format!("(mentat.store/q (mentat.store/db c) '{query})"))
            .unwrap()
    };
    // A tuple find, one tag at a time: a set's print order differs by backend.
    let state = "[:find [?a ?b] :where [?e :person/name \"Alice\"] [?e :person/age ?a] \
                 [?e :person/best ?f] [?f :person/name ?b]]";
    let tags = "[:find ?t :where [?e :person/name \"Alice\"] [?e :person/tag ?t]]";
    let before = q(it, state);
    assert_eq!(before, "[30 \"Bob\"]");
    let tag_count = |it: &mut Interpreter| {
        it.eval_to_string(&format!(
            "(count (mentat.store/q (mentat.store/db c) '{tags}))"
        ))
        .unwrap()
    };
    assert_eq!(tag_count(it), "2");
    let report = it
        .eval_to_string(
            "(mentat.store/transact c \
               [[:db/retract [:person/name \"Alice\"] :person/age 99] \
                [:db/retract [:person/name \"Alice\"] :person/tag \"zzz\"] \
                [:db/retract [:person/name \"Alice\"] :person/best [:person/name \"Alice\"]]])",
        )
        .expect("retract absent values");
    assert!(
        report.contains(":mentat.store/datoms-asserted 0"),
        "{report}"
    );
    assert!(
        report.contains(":mentat.store/datoms-retracted 0"),
        "{report}"
    );
    assert_eq!(q(it, state), before, "nothing changed");
    assert_eq!(tag_count(it), "2", "nothing changed");
    // The log has no retraction for Alice.
    let log = q(
        it,
        "[:find ?v ?added :where [?e :person/name \"Alice\"] [?e :person/tag ?v ?tx ?added]]",
    );
    assert!(!log.contains("false"), "{log}");
    let log = q(
        it,
        "[:find ?v ?added :where [?e :person/name \"Alice\"] [?e :person/age ?v ?tx ?added]]",
    );
    assert!(!log.contains("false"), "{log}");
    // The present values still retract, one datom each.
    let report = it
        .eval_to_string(
            "(mentat.store/transact c \
               [[:db/retract [:person/name \"Alice\"] :person/age 30] \
                [:db/retract [:person/name \"Alice\"] :person/tag \"x\"] \
                [:db/retract [:person/name \"Alice\"] :person/best [:person/name \"Bob\"]]])",
        )
        .expect("retract present values");
    assert!(
        report.contains(":mentat.store/datoms-retracted 3"),
        "{report}"
    );
    assert_eq!(
        q(
            it,
            "[:find [?t ...] :where [?e :person/name \"Alice\"] [?e :person/tag ?t]]"
        ),
        "[\"y\"]"
    );
    for a in [":person/age", ":person/best"] {
        assert_eq!(
            q(
                it,
                &format!("[:find ?x . :where [?e :person/name \"Alice\"] [?e {a} ?x]]")
            ),
            "nil",
            "{a}"
        );
    }
}

/// Issue #12 (Mozilla #818): renaming a unique identity value and explicitly retracting the
/// old value in the same transaction retracts the old value once. The report counts one
/// retraction and the log holds one, on every backend.
pub fn rename_and_retract_logs_one_retraction(it: &mut Interpreter) {
    it.eval("(def c (mentat.store/open))").expect("open");
    it.eval_to_string(
        "(mentat.store/transact c \
           [{:db/ident :t/id :db/valueType :db.type/string :db/cardinality :db.cardinality/one \
             :db/unique :db.unique/identity :db/index true}])",
    )
    .expect("schema");
    it.eval_to_string("(mentat.store/transact c [{:t/id \"One\"}])")
        .expect("data");
    let report = it
        .eval_to_string(
            "(mentat.store/transact c \
               [[:db/add [:t/id \"One\"] :t/id \"Two\"] \
                [:db/retract [:t/id \"One\"] :t/id \"One\"]])",
        )
        .expect("rename and retract");
    assert!(
        report.contains(":mentat.store/datoms-asserted 1"),
        "{report}"
    );
    assert!(
        report.contains(":mentat.store/datoms-retracted 1"),
        "{report}"
    );
    let q = |it: &mut Interpreter, query: &str| {
        it.eval_to_string(&format!("(mentat.store/q (mentat.store/db c) '{query})"))
            .unwrap()
    };
    // One assertion and one retraction of "One". (A Datalog result is a set, so this can't
    // see two identical log rows; the report's count, the rows written, can.)
    let log = q(
        it,
        "[:find ?added (count ?tx) :where [?e :t/id \"One\" ?tx ?added]]",
    );
    assert!(
        log.contains("[false 1]") && log.contains("[true 1]"),
        "{log}"
    );
    assert_eq!(
        q(it, "[:find ?e . :where [?e :t/id \"One\"]]"),
        "nil",
        "\"One\" is retracted"
    );
}

/// Issue #152: in list form, `[:db/add e a v]` takes one value (Datomic's grammar), so on a
/// ref attribute, cardinality-one or -many, a vector `v` is a lookup ref under any
/// `:db/unique` attribute, and one that doesn't resolve is an error. It used to make, for a
/// `:db.unique/value` attribute, a ref to the attribute plus a new empty entity "x". Map
/// form keeps DataScript's rule (only `:db.unique/identity` makes the whole value a lookup
/// ref), so there it is still two refs.
pub fn list_form_ref_vector_is_one_lookup_ref(it: &mut Interpreter) {
    it.eval("(def c (mentat.store/open))").expect("open");
    it.eval_to_string(
        "(mentat.store/transact c \
           [{:db/ident :l/uv :db/valueType :db.type/string :db/cardinality :db.cardinality/one \
             :db/unique :db.unique/value :db/index true} \
            {:db/ident :l/id :db/valueType :db.type/string :db/cardinality :db.cardinality/one \
             :db/unique :db.unique/identity :db/index true} \
            {:db/ident :l/n :db/valueType :db.type/long :db/cardinality :db.cardinality/one} \
            {:db/ident :l/many :db/valueType :db.type/ref :db/cardinality :db.cardinality/many} \
            {:db/ident :l/one :db/valueType :db.type/ref :db/cardinality :db.cardinality/one}])",
    )
    .expect("schema");
    it.eval_to_string(
        "(mentat.store/transact c [{:l/uv \"x\" :l/id \"x\"} {:l/uv \"y\" :l/id \"y\"}])",
    )
    .expect("data");
    let q = |it: &mut Interpreter, query: &str| {
        it.eval_to_string(&format!("(mentat.store/q (mentat.store/db c) '{query})"))
            .unwrap()
    };
    for attr in [":l/many", ":l/one"] {
        let report = it
            .eval_to_string(&format!(
                "(mentat.store/transact c [[:db/add \"s\" :l/id \"s{attr}\"] \
                   [:db/add \"s\" {attr} [:l/uv \"x\"]]])"
            ))
            .unwrap_or_else(|e| panic!("{attr}: {e}"));
        // Only "s" is a tempid: "x" is a lookup ref, not a new entity.
        assert!(!report.contains("\"x\""), "{attr}: {report}");
        assert!(
            report.contains(":mentat.store/datoms-asserted 2"),
            "{attr}: {report}"
        );
        assert_eq!(
            q(
                it,
                &format!(
                    "[:find [?i ...] :where [?s :l/id \"s{attr}\"] [?s {attr} ?r] [?r :l/id ?i]]"
                )
            ),
            "[\"x\"]",
            "{attr}"
        );
    }
    // Retracting it the same way finds the same entity.
    it.eval_to_string(
        "(mentat.store/transact c [[:db/retract [:l/id \"s:l/many\"] :l/many [:l/uv \"x\"]]])",
    )
    .expect("retract by lookup ref");
    assert_eq!(
        q(
            it,
            "[:find ?r . :where [?s :l/id \"s:l/many\"] [?s :l/many ?r]]"
        ),
        "nil"
    );
    // One value: an unresolved lookup ref, a non-unique attribute or a list is an error.
    for v in [
        "[:l/uv \"nope\"]",
        "[:l/n 1]",
        "[[:l/uv \"x\"] [:l/uv \"y\"]]",
    ] {
        assert!(
            it.eval(&format!(
                "(mentat.store/transact c [[:db/add [:l/id \"x\"] :l/many {v}]])"
            ))
            .is_err(),
            "{v}"
        );
    }
    // Map form: DataScript's rule, so [:l/uv :l/n] under :db.unique/value is two refs.
    let report = it
        .eval_to_string("(mentat.store/transact c [{:db/id \"m\" :l/many [:l/uv :l/n]}])")
        .expect("map form");
    assert!(
        report.contains(":mentat.store/datoms-asserted 2"),
        "{report}"
    );
}