gen-models 0.5.0

Models for the gen sequence graph and version control system.
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
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
//! Dolt-backed history access for Gen's graph database.
//!
//! Gen stores its biological graph tables in a DoltLite-backed `GraphConnection`, so commits,
//! branches, status, merges, and remotes are database operations rather than a separate metadata
//! store. This module is the central adapter between the rest of the codebase and Dolt's SQL
//! functions and system tables. It exposes the raw Dolt row shapes needed by branch and remote
//! workflows and implements the backend-neutral [`HistoryStore`] interface used by CLI commands,
//! diff construction, patch handling, imports, and updates.
//!
//! # Why operations have two call styles
//!
//! The public free functions are connection-oriented building blocks. Code that already has a
//! `GraphConnection`—especially model/database setup and remote-transfer code—can call a specific
//! Dolt operation directly, including operations that do not belong in the common [`HistoryStore`]
//! interface.
//!
//! [`DoltHistoryStore`] is the bound form. It borrows the graph connection, optionally borrows Gen's
//! config database for commit-author defaults, and implements [`HistoryStore`] so higher-level code
//! can work through one cohesive history API. Where both forms expose the same operation, the bound
//! method delegates to the free function; the two forms are entry points for different callers, not
//! separate implementations of Dolt behavior.

use std::{collections::HashMap, rc::Rc};

use gen_core::{BranchName, CommitRef, DoltHashId};
use rusqlite::{
    OptionalExtension, Result as SqlResult, params,
    types::{Type, Value},
};

use crate::{
    db::{ConfigConnection, GraphConnection},
    history::{
        HistoryConflict, HistoryEntry, HistoryError, HistoryResult, HistoryStatus, HistoryStore,
    },
    operations::{DEFAULT_COMMITTER_EMAIL, Defaults, GEN_DEFAULT_COMMITTER_NAME},
};

/// Raw commit metadata read from `dolt_log` before conversion to [`HistoryEntry`].
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DoltLogEntry {
    pub commit_hash: DoltHashId,
    pub parent_hash: Option<DoltHashId>,
    pub committer: String,
    pub email: String,
    pub date: String,
    pub message: String,
}

/// Raw table status returned to connection-oriented callers and converted to [`HistoryStatus`].
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DoltStatusRow {
    pub table_name: String,
    pub staged: bool,
    pub status: String,
}

/// Branch metadata used by branch selection, checkout, and remote-tracking workflows.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DoltBranchRow {
    pub name: String,
    pub hash: DoltHashId,
    pub latest_committer: String,
    pub latest_committer_email: String,
    pub latest_commit_date: String,
    pub latest_commit_message: String,
    pub remote: String,
    pub branch: String,
    pub dirty: bool,
}

/// Remote configuration read from `dolt_remotes` for remote-transfer workflows.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DoltRemoteRow {
    pub name: String,
    pub url: String,
    pub fetch_specs: String,
    pub params: String,
}

/// Executes a Dolt SQL function whose scalar result only signals whether the command succeeded.
fn run_history_statement(
    conn: &GraphConnection,
    query: &str,
    params: &[&dyn rusqlite::ToSql],
) -> SqlResult<()> {
    conn.query_row(query, params, |row| row.get_ref(0).map(|_| ()))?;
    Ok(())
}

/// A borrowed, backend-neutral history facade over a Dolt-backed graph connection.
///
/// The optional config connection is used only when an operation needs Gen-level defaults, such as
/// choosing the commit author. Callers that only need graph history can construct the store without
/// it.
pub struct DoltHistoryStore<'connection> {
    graph: &'connection GraphConnection,
    config: Option<&'connection ConfigConnection>,
}

impl<'connection> DoltHistoryStore<'connection> {
    /// Binds history operations to a graph connection without Gen configuration defaults.
    pub fn new(graph: &'connection GraphConnection) -> Self {
        Self {
            graph,
            config: None,
        }
    }

    /// Binds history operations to both the graph and Gen config connections.
    ///
    /// Use this form for commits that should inherit the configured default committer identity.
    pub fn new_with_config(
        graph: &'connection GraphConnection,
        config: &'connection ConfigConnection,
    ) -> Self {
        Self {
            graph,
            config: Some(config),
        }
    }
}

// These connection-oriented functions are also used by `DoltHistoryStore` below. Keeping the SQL
// operations here lets direct database callers and `HistoryStore` callers share the same behavior.
pub fn commit_author_name(conn: &GraphConnection) -> SqlResult<Option<String>> {
    conn.query_row("SELECT dolt_config('user.name')", [], |row| row.get(0))
}

pub fn commit_author_email(conn: &GraphConnection) -> SqlResult<Option<String>> {
    conn.query_row("SELECT dolt_config('user.email')", [], |row| row.get(0))
}

pub fn set_commit_author_name(conn: &GraphConnection, name: &str) -> SqlResult<()> {
    conn.query_row("SELECT dolt_config('user.name', ?1)", [name], |row| {
        row.get::<_, i64>(0)
    })?;
    Ok(())
}

pub fn set_commit_author_email(conn: &GraphConnection, email: &str) -> SqlResult<()> {
    conn.query_row("SELECT dolt_config('user.email', ?1)", [email], |row| {
        row.get::<_, i64>(0)
    })?;
    Ok(())
}

fn default_committer_name(config_conn: Option<&ConfigConnection>) -> String {
    config_conn
        .map(Defaults::get_default_committer_name)
        .unwrap_or_else(|| GEN_DEFAULT_COMMITTER_NAME.to_string())
}

fn default_committer_email(config_conn: Option<&ConfigConnection>) -> String {
    config_conn
        .map(Defaults::get_default_committer_email)
        .unwrap_or_else(|| DEFAULT_COMMITTER_EMAIL.to_string())
}

fn should_set_committer_name(name: Option<&str>, email: Option<&str>) -> bool {
    name.is_none()
        || name == Some("")
        || name == Some(GEN_DEFAULT_COMMITTER_NAME)
        || email.is_none()
        || email == Some("")
}

fn should_set_committer_email(email: Option<&str>) -> bool {
    email.is_none() || email == Some("")
}

pub fn set_default_commit_author(
    conn: &GraphConnection,
    config_conn: Option<&ConfigConnection>,
) -> SqlResult<()> {
    let committer_name = commit_author_name(conn)?;
    let committer_email = commit_author_email(conn)?;
    if should_set_committer_name(committer_name.as_deref(), committer_email.as_deref()) {
        set_commit_author_name(conn, &default_committer_name(config_conn))?;
    }
    if should_set_committer_email(committer_email.as_deref()) {
        set_commit_author_email(conn, &default_committer_email(config_conn))?;
    }
    Ok(())
}

#[cfg_attr(feature = "profiling", tracing::instrument(skip(conn, message)))]
pub fn commit_all(conn: &GraphConnection, message: &str) -> SqlResult<DoltHashId> {
    commit_all_with_config(conn, None, message)
}

#[cfg_attr(
    feature = "profiling",
    tracing::instrument(skip(conn, config_conn, message))
)]
pub fn commit_all_with_config(
    conn: &GraphConnection,
    config_conn: Option<&ConfigConnection>,
    message: &str,
) -> SqlResult<DoltHashId> {
    set_default_commit_author(conn, config_conn)?;
    commit_staged_all(conn, message)
}

#[cfg_attr(feature = "profiling", tracing::instrument(skip(conn, message)))]
pub fn commit_staged_all(conn: &GraphConnection, message: &str) -> SqlResult<DoltHashId> {
    conn.query_row("SELECT dolt_commit('-A', '-m', ?1)", [message], |row| {
        row.get(0)
    })
}

pub fn active_branch(conn: &GraphConnection) -> SqlResult<String> {
    conn.query_row("SELECT active_branch()", [], |row| row.get(0))
}

pub fn log_entries(conn: &GraphConnection) -> SqlResult<Vec<DoltLogEntry>> {
    let mut statement = conn.prepare(
        "SELECT commits.commit_hash, ancestors.parent_hash, commits.committer, \
                commits.email, commits.date, commits.message \
         FROM dolt_log AS commits \
         LEFT JOIN dolt_commit_ancestors AS ancestors \
           ON ancestors.commit_hash = commits.commit_hash AND ancestors.parent_index = 0",
    )?;
    let rows = statement.query_map([], |row| {
        Ok(DoltLogEntry {
            commit_hash: row.get(0)?,
            parent_hash: row.get(1)?,
            committer: row.get(2)?,
            email: row.get(3)?,
            date: row.get(4)?,
            message: row.get(5)?,
        })
    })?;
    rows.collect()
}

/// Loads metadata for existing commit hashes in the requested order.
///
/// Dolt omits hashes that do not identify commits. Callers can compare the returned hashes with
/// their request to report the missing commit while still allowing commits from unrelated branches.
///
/// # Arguments
///
/// * `conn` - The graph database containing the Dolt repository.
/// * `commit_hashes` - The commit hashes whose metadata should be loaded.
///
/// # Errors
///
/// Returns an error if Dolt commit metadata cannot be queried.
pub fn log_entries_for_hashes(
    conn: &GraphConnection,
    commit_hashes: &[DoltHashId],
) -> SqlResult<Vec<DoltLogEntry>> {
    if commit_hashes.is_empty() {
        return Ok(Vec::new());
    }
    let commit_hashes = Rc::new(
        commit_hashes
            .iter()
            .map(|commit_hash| Value::Text(commit_hash.to_string()))
            .collect::<Vec<_>>(),
    );
    // A plain dolt_log hash filter only sees commits reachable from the active checkout.
    // Ancestors omits missing hashes and supplies each existing commit as an explicit log
    // revision, so this batch also includes commits from other branches and root commits.
    let mut statement = conn.prepare(
        "WITH requested AS ( \
             SELECT rowid AS position, value AS commit_hash FROM rarray(?1) \
         ) \
         SELECT commits.commit_hash, ancestors.parent_hash, commits.committer, \
                commits.email, commits.date, commits.message \
         FROM requested \
         JOIN dolt_commit_ancestors AS ancestors \
           ON ancestors.commit_hash = requested.commit_hash AND ancestors.parent_index = 0 \
         JOIN dolt_log(ancestors.commit_hash) AS commits \
           ON commits.commit_hash = requested.commit_hash \
         ORDER BY requested.position",
    )?;
    let rows = statement.query_map([commit_hashes], |row| {
        Ok(DoltLogEntry {
            commit_hash: row.get(0)?,
            parent_hash: row.get(1)?,
            committer: row.get(2)?,
            email: row.get(3)?,
            date: row.get(4)?,
            message: row.get(5)?,
        })
    })?;
    rows.collect()
}

/// Loads the commit log selected by a Dolt revision or revision range.
///
/// # Arguments
///
/// * `conn` - The graph database containing the Dolt repository.
/// * `revision` - A Dolt ref or range such as `feature`, `main..feature`, or `main...feature`.
///
/// # Errors
///
/// Returns an error if Dolt cannot resolve or query the revision.
pub fn log_entries_for_revision(
    conn: &GraphConnection,
    revision: &str,
) -> SqlResult<Vec<DoltLogEntry>> {
    let mut statement = conn.prepare(
        "SELECT commits.commit_hash, first_parents.parent_hash, commits.committer, \
                commits.email, commits.date, commits.message \
         FROM dolt_log(?1) AS commits \
         LEFT JOIN dolt_commit_ancestors AS first_parents \
           ON first_parents.commit_hash = commits.commit_hash \
          AND first_parents.parent_index = 0",
    )?;
    let rows = statement.query_map([revision], |row| {
        Ok(DoltLogEntry {
            commit_hash: row.get(0)?,
            parent_hash: row.get(1)?,
            committer: row.get(2)?,
            email: row.get(3)?,
            date: row.get(4)?,
            message: row.get(5)?,
        })
    })?;
    rows.collect()
}

#[cfg_attr(feature = "profiling", tracing::instrument(skip(conn, head_hash)))]
fn head_log_entries(
    conn: &GraphConnection,
    head_hash: &DoltHashId,
    limit: Option<usize>,
) -> SqlResult<Vec<DoltLogEntry>> {
    let commit_hashes: Vec<DoltHashId> = match limit {
        Some(limit) => {
            let max_depth = i64::try_from(limit).map_err(|_| {
                rusqlite::Error::ToSqlConversionFailure(
                    format!("history limit {limit} exceeds i64").into(),
                )
            })?;
            let mut statement = conn.prepare(
                "WITH RECURSIVE ancestry(commit_hash, depth) AS ( \
                     SELECT ?1, 0 \
                     UNION ALL \
                     SELECT ancestors.parent_hash, ancestry.depth + 1 \
                     FROM ancestry \
                     JOIN dolt_commit_ancestors AS ancestors ON ancestors.commit_hash = ancestry.commit_hash \
                     WHERE ancestors.parent_hash IS NOT NULL AND ancestry.depth + 1 < ?2 \
                 ) \
                 SELECT commit_hash \
                 FROM ancestry \
                 GROUP BY commit_hash \
                 ORDER BY MIN(depth) \
                 LIMIT ?2",
            )?;
            let rows = statement.query_map(params![head_hash, max_depth], |row| row.get(0))?;
            rows.collect::<SqlResult<Vec<_>>>()
        }
        None => {
            let mut statement = conn.prepare(
                "WITH RECURSIVE ancestry(commit_hash, depth) AS ( \
                     SELECT ?1, 0 \
                     UNION ALL \
                     SELECT ancestors.parent_hash, ancestry.depth + 1 \
                     FROM ancestry \
                     JOIN dolt_commit_ancestors AS ancestors ON ancestors.commit_hash = ancestry.commit_hash \
                     WHERE ancestors.parent_hash IS NOT NULL \
                 ) \
                 SELECT commit_hash \
                 FROM ancestry \
                 GROUP BY commit_hash \
                 ORDER BY MIN(depth)",
            )?;
            let rows = statement.query_map([head_hash], |row| row.get(0))?;
            rows.collect::<SqlResult<Vec<_>>>()
        }
    }?;

    log_entries_for_hashes(conn, &commit_hashes)
}

#[cfg_attr(feature = "profiling", tracing::instrument(skip(conn, head_hash)))]
fn nth_ancestor_hash(
    conn: &GraphConnection,
    head_hash: &DoltHashId,
    offset: usize,
) -> SqlResult<Option<DoltHashId>> {
    let offset = i64::try_from(offset).map_err(|_| {
        rusqlite::Error::ToSqlConversionFailure(
            format!("ancestor offset {offset} exceeds i64").into(),
        )
    })?;
    conn.query_row(
        "WITH RECURSIVE ancestry(commit_hash, depth) AS ( \
             SELECT ?1, 0 \
             UNION ALL \
             SELECT ancestors.parent_hash, ancestry.depth + 1 \
             FROM ancestry \
             JOIN dolt_commit_ancestors AS ancestors ON ancestors.commit_hash = ancestry.commit_hash \
             WHERE ancestors.parent_hash IS NOT NULL \
               AND ancestors.parent_index = 0 \
               AND ancestry.depth < ?2 \
         ) \
         SELECT commit_hash \
         FROM ancestry \
         WHERE depth = ?2 \
         LIMIT 1",
        params![head_hash, offset],
        |row| row.get(0),
    )
    .optional()
}

#[cfg_attr(feature = "profiling", tracing::instrument(skip(conn)))]
pub fn status_rows(conn: &GraphConnection) -> SqlResult<Vec<DoltStatusRow>> {
    let mut statement = conn.prepare(
        "SELECT table_name, staged, status FROM dolt_status ORDER BY table_name, staged DESC",
    )?;
    let rows = statement.query_map([], |row| {
        Ok(DoltStatusRow {
            table_name: row.get(0)?,
            staged: row.get(1)?,
            status: row.get(2)?,
        })
    })?;
    rows.collect()
}

pub fn create_branch(conn: &GraphConnection, branch_name: &str) -> SqlResult<()> {
    run_history_statement(conn, "SELECT dolt_branch(?1)", &[&branch_name])
}

pub fn checkout(conn: &GraphConnection, target: &str) -> SqlResult<()> {
    run_history_statement(conn, "SELECT dolt_checkout(?1)", &[&target])
}

pub fn connect_branch(conn: &GraphConnection, branch_name: &str) -> SqlResult<()> {
    run_history_statement(conn, "SELECT dolt_connect_branch(?1)", &[&branch_name])
}

fn resolve_created_on_conflicts(
    conn: &GraphConnection,
    conflicts: &[HistoryConflict],
) -> SqlResult<()> {
    // This handles known conflict cases automatically. The cases are:
    // Created_on dates between otherwise identical objects can differ. Automatically use the target branch created_on date for a conflict
    for conflict in conflicts {
        if conflict.num_conflicts == 0 {
            continue;
        }

        let Some(query) = (match conflict.table_name.as_str() {
            "block_groups" => Some(
                "DELETE FROM dolt_conflicts_block_groups \
                 WHERE our_created_on IS NOT their_created_on \
                   AND our_id IS their_id \
                   AND our_collection_name IS their_collection_name \
                   AND our_sample_name IS their_sample_name \
                   AND our_name IS their_name \
                   AND our_parent_block_group_id IS their_parent_block_group_id \
                   AND our_is_default IS their_is_default",
            ),
            "paths" => Some(
                "DELETE FROM dolt_conflicts_paths \
                 WHERE our_created_on IS NOT their_created_on \
                   AND our_id IS their_id \
                   AND our_block_group_id IS their_block_group_id \
                   AND our_name IS their_name \
                   AND our_edge_ids IS their_edge_ids",
            ),
            "block_group_edges" => Some(
                "DELETE FROM dolt_conflicts_block_group_edges \
                 WHERE our_created_on IS NOT their_created_on \
                   AND our_id IS their_id \
                   AND our_block_group_id IS their_block_group_id \
                   AND our_edge_id IS their_edge_id \
                   AND our_chromosome_index IS their_chromosome_index \
                   AND our_phased IS their_phased",
            ),
            "gen_asset_refs" => Some(
                "DELETE FROM dolt_conflicts_gen_asset_refs \
                 WHERE our_created_on IS NOT their_created_on \
                   AND our_id IS their_id \
                   AND our_uri IS their_uri \
                   AND our_file_type IS their_file_type \
                   AND our_checksum IS their_checksum \
                   AND our_size IS their_size \
                   AND our_role IS their_role \
                   AND our_logical_path IS their_logical_path \
                   AND our_name IS their_name \
                   AND our_upstream_asset_ref_id IS their_upstream_asset_ref_id",
            ),
            "gen_operation_log" => Some(
                "DELETE FROM dolt_conflicts_gen_operation_log \
                 WHERE our_created_on IS NOT their_created_on \
                   AND our_id IS their_id \
                   AND our_operation_kind IS their_operation_kind \
                   AND our_command IS their_command",
            ),
            _ => None,
        }) else {
            continue;
        };
        conn.execute(query, [])?;
    }
    Ok(())
}

fn merge_commit(conn: &GraphConnection, message: &str) -> SqlResult<DoltHashId> {
    let result: Value = conn.query_row("SELECT dolt_commit('-A', '-m', ?1)", [message], |row| {
        row.get(0)
    })?;
    let Value::Text(result) = result else {
        return Err(rusqlite::Error::FromSqlConversionFailure(
            0,
            Type::Text,
            "dolt_commit returned a non-text result".into(),
        ));
    };
    DoltHashId::try_from(result.as_str())
        .map_err(|error| rusqlite::Error::FromSqlConversionFailure(0, Type::Text, Box::new(error)))
}

/// Merges a branch or commit reference into the active branch and returns the resulting hash.
///
/// The `dolt_merge('--no-commit', reference)` outcomes are:
///
/// | Result | Meaning |
/// | --- | --- |
/// | `Text("Already up to date")` | No-op; return the current HEAD. |
/// | `Text(commit hash)` | Fast-forward; return the resulting hash. |
/// | `Integer(0)` | Clean non-fast-forward working set; requires `dolt_commit`. |
/// | `SQLITE_ERROR` with data conflicts | Conflict rows materialized for selective resolution before commit. |
///
/// An active SQL transaction is required. Callers must invoke this operation inside
/// [`GraphConnection::with_transaction`] (or another explicit transaction) for the supported
/// workflow: the transaction both rolls back failed merges and keeps DoltLite conflict state
/// available while conflicts are inspected and resolved.
pub fn merge(conn: &GraphConnection, reference: &str) -> SqlResult<DoltHashId> {
    if conn.is_autocommit() {
        return Err(rusqlite::Error::SqliteFailure(
            rusqlite::ffi::Error::new(rusqlite::ffi::SQLITE_MISUSE),
            Some("merge requires an active transaction".to_string()),
        ));
    }

    let target_branch = active_branch(conn)?;
    let merge_message = format!("Merge branch '{reference}' into {target_branch}");

    let merge_result: Result<Value, rusqlite::Error> =
        conn.query_row("SELECT dolt_merge('--no-commit', ?1)", [reference], |row| {
            row.get(0)
        });

    let result = match merge_result {
        Ok(Value::Text(result)) if result == "Already up to date" => {
            return hash_of(conn, "HEAD");
        }
        Ok(Value::Text(result)) => match DoltHashId::try_from(result.as_str()) {
            Ok(commit_hash) => return Ok(commit_hash),
            Err(error) => {
                return Err(rusqlite::Error::FromSqlConversionFailure(
                    0,
                    Type::Text,
                    Box::new(error),
                ));
            }
        },
        Ok(Value::Integer(0)) => None,
        Ok(result) => {
            return Err(rusqlite::Error::FromSqlConversionFailure(
                0,
                Type::Text,
                format!("unexpected dolt_merge result: {result:?}").into(),
            ));
        }
        Err(error) => Some(error),
    };

    let conflicts = conflict_rows(conn)?;
    let had_data_conflicts = conflicts.iter().any(|conflict| conflict.num_conflicts > 0);
    resolve_created_on_conflicts(conn, &conflicts)?;

    if !had_data_conflicts && let Some(error) = result {
        return Err(error);
    }

    merge_commit(conn, &merge_message)
}

pub fn reset_hard(conn: &GraphConnection, target: &str) -> SqlResult<()> {
    run_history_statement(conn, "SELECT dolt_reset('--hard', ?1)", &[&target])
}

pub fn add_remote(conn: &GraphConnection, remote_name: &str, remote_url: &str) -> SqlResult<()> {
    run_history_statement(
        conn,
        "SELECT dolt_remote('add', ?1, ?2)",
        &[&remote_name, &remote_url],
    )
}

pub fn remove_remote(conn: &GraphConnection, remote_name: &str) -> SqlResult<()> {
    run_history_statement(conn, "SELECT dolt_remote('remove', ?1)", &[&remote_name])
}

/// This command is specific to the libdoltlite-sys library. It allows for an in-place update of remote urls
/// for baking in short lived credentials and allowing use with the standard dolt_push/pull/clone commands.
pub fn set_remote_url(
    conn: &GraphConnection,
    remote_name: &str,
    remote_url: &str,
) -> SqlResult<()> {
    run_history_statement(
        conn,
        "SELECT dolt_remote('set-url', ?1, ?2)",
        &[&remote_name, &remote_url],
    )
}

pub fn clone_remote(conn: &GraphConnection, remote_url: &str) -> SqlResult<()> {
    run_history_statement(conn, "SELECT dolt_clone(?1)", &[&remote_url])
}

pub fn branch_rows(conn: &GraphConnection) -> SqlResult<Vec<DoltBranchRow>> {
    // DoltLite exposes an all-zero hash for an uninitialized branch, but its
    // latest_commit_* columns currently try to load that hash as a commit.
    // CASE is lazy in DoltLite and keeps those placeholder rows readable.
    let mut statement = conn.prepare(
        "SELECT name, hash, \
         CASE WHEN hash = '0000000000000000000000000000000000000000' \
              THEN '' ELSE latest_committer END, \
         CASE WHEN hash = '0000000000000000000000000000000000000000' \
              THEN '' ELSE latest_committer_email END, \
         CASE WHEN hash = '0000000000000000000000000000000000000000' \
              THEN '' ELSE latest_commit_date END, \
         CASE WHEN hash = '0000000000000000000000000000000000000000' \
              THEN '' ELSE latest_commit_message END, \
         remote, branch, dirty \
         FROM dolt_branches ORDER BY name",
    )?;
    let rows = statement.query_map([], |row| {
        Ok(DoltBranchRow {
            name: row.get(0)?,
            hash: row.get(1)?,
            latest_committer: row.get(2)?,
            latest_committer_email: row.get(3)?,
            latest_commit_date: row.get(4)?,
            latest_commit_message: row.get(5)?,
            remote: row.get(6)?,
            branch: row.get(7)?,
            dirty: row.get(8)?,
        })
    })?;
    rows.collect()
}

/// Searches materialized branch names, ranking exact and prefix matches first.
pub fn search_branch_names(conn: &GraphConnection, search_term: &str) -> SqlResult<Vec<String>> {
    let zero_hash = "0000000000000000000000000000000000000000";
    let mut statement = conn.prepare(
        "SELECT name FROM dolt_branches \
         WHERE hash <> ?1 AND LOWER(name) LIKE '%' || LOWER(?2) || '%' \
         ORDER BY CASE \
           WHEN LOWER(name) = LOWER(?2) THEN 0 \
           WHEN LOWER(name) LIKE LOWER(?2) || '%' THEN 1 \
           ELSE 2 \
         END, LOWER(name), name",
    )?;
    let rows = statement.query_map([zero_hash, search_term], |row| row.get(0))?;
    rows.collect()
}

pub fn branch_exists(conn: &GraphConnection, branch_name: &str) -> SqlResult<bool> {
    conn.query_row(
        "SELECT EXISTS(SELECT 1 FROM dolt_branches WHERE name = ?1)",
        [branch_name],
        |row| row.get(0),
    )
}

/// Checks whether each distinct requested branch name exists.
///
/// The returned map has one entry per distinct input name, including missing names with a `false`
/// value. Branch names use the same exact equality semantics as [`branch_exists`].
pub fn branches_exist(
    conn: &GraphConnection,
    branch_names: &[&str],
) -> SqlResult<HashMap<String, bool>> {
    if branch_names.is_empty() {
        return Ok(HashMap::new());
    }

    let branch_names = Rc::new(
        branch_names
            .iter()
            .map(|branch_name| Value::Text((*branch_name).to_owned()))
            .collect::<Vec<_>>(),
    );
    let mut statement = conn.prepare(
        "WITH requested AS ( \
             SELECT DISTINCT value AS branch_name FROM rarray(?1) \
         ) \
         SELECT requested.branch_name, branches.name IS NOT NULL \
         FROM requested \
         LEFT JOIN dolt_branches AS branches ON branches.name = requested.branch_name",
    )?;
    let rows = statement.query_map([branch_names], |row| Ok((row.get(0)?, row.get(1)?)))?;
    rows.collect()
}

pub fn branch_hash(conn: &GraphConnection, branch_name: &str) -> SqlResult<Option<DoltHashId>> {
    conn.query_row(
        "SELECT hash FROM dolt_branches WHERE name = ?1",
        [branch_name],
        |row| row.get(0),
    )
    .optional()
}

pub fn hash_of(conn: &GraphConnection, commit_ref: &str) -> SqlResult<DoltHashId> {
    conn.query_row("SELECT dolt_hashof(?1)", [commit_ref], |row| row.get(0))
}

pub fn commit_exists(conn: &GraphConnection, commit_hash: &DoltHashId) -> SqlResult<bool> {
    // Unlike dolt_log, ancestors resolves hashes independently of the active branch.
    conn.query_row(
        "SELECT EXISTS(SELECT 1 FROM dolt_commit_ancestors WHERE commit_hash = ?1)",
        [commit_hash],
        |row| row.get(0),
    )
}

/// Returns every direct parent of a commit in Dolt's parent order.
pub fn commit_parents(
    conn: &GraphConnection,
    commit_hash: &DoltHashId,
) -> SqlResult<Vec<DoltHashId>> {
    let mut statement = conn.prepare(
        "SELECT parent_hash \
         FROM dolt_commit_ancestors \
         WHERE commit_hash = ?1 AND parent_hash IS NOT NULL \
         ORDER BY parent_index",
    )?;
    let rows = statement.query_map([commit_hash], |row| row.get(0))?;
    rows.collect()
}

/// Returns whether `ancestor_hash` is reachable from `descendant_hash`, including equality.
pub fn is_ancestor(
    conn: &GraphConnection,
    ancestor_hash: &DoltHashId,
    descendant_hash: &DoltHashId,
) -> SqlResult<bool> {
    conn.query_row(
        "WITH RECURSIVE ancestry(commit_hash) AS ( \
             SELECT ?2 \
             WHERE EXISTS( \
                 SELECT 1 FROM dolt_commit_ancestors WHERE commit_hash = ?2 \
             ) \
             UNION \
             SELECT parents.parent_hash \
             FROM ancestry \
             JOIN dolt_commit_ancestors AS parents \
               ON parents.commit_hash = ancestry.commit_hash \
             WHERE parents.parent_hash IS NOT NULL \
         ) \
         SELECT EXISTS( \
             SELECT 1 FROM ancestry WHERE commit_hash = ?1 \
         )",
        [ancestor_hash, descendant_hash],
        |row| row.get(0),
    )
}

pub fn merge_base(
    conn: &GraphConnection,
    source_ref: &str,
    target_ref: &str,
) -> SqlResult<DoltHashId> {
    conn.query_row(
        "SELECT dolt_merge_base(?1, ?2)",
        [source_ref, target_ref],
        |row| row.get(0),
    )
}

#[cfg_attr(feature = "profiling", tracing::instrument(skip(conn)))]
pub fn is_current_branch_dirty(conn: &GraphConnection) -> SqlResult<bool> {
    conn.query_row(
        "SELECT dirty FROM dolt_branches WHERE name = active_branch() LIMIT 1",
        [],
        |row| row.get::<_, bool>(0),
    )
}

pub fn delete_branch(conn: &GraphConnection, branch_name: &str) -> SqlResult<()> {
    run_history_statement(conn, "SELECT dolt_branch('-d', ?1)", &[&branch_name])
}

pub fn delete_branch_force(conn: &GraphConnection, branch_name: &str) -> SqlResult<()> {
    run_history_statement(conn, "SELECT dolt_branch('-D', ?1)", &[&branch_name])
}

pub fn cherry_pick(conn: &GraphConnection, commit_hash: &str) -> SqlResult<()> {
    run_history_statement(conn, "SELECT dolt_cherry_pick(?1)", &[&commit_hash])
}

pub fn push(conn: &GraphConnection, remote_name: &str, branch_name: &str) -> SqlResult<()> {
    run_history_statement(
        conn,
        "SELECT dolt_push(?1, ?2)",
        &[&remote_name, &branch_name],
    )
}

pub fn push_force(conn: &GraphConnection, remote_name: &str, branch_name: &str) -> SqlResult<()> {
    run_history_statement(
        conn,
        "SELECT dolt_push(?1, ?2, '--force')",
        &[&remote_name, &branch_name],
    )
}

pub fn pull(conn: &GraphConnection, remote_name: &str, branch_name: &str) -> SqlResult<()> {
    run_history_statement(
        conn,
        "SELECT dolt_pull(?1, ?2)",
        &[&remote_name, &branch_name],
    )
}

pub fn fetch(
    conn: &GraphConnection,
    remote_name: &str,
    branch_name: Option<&str>,
) -> SqlResult<()> {
    match branch_name {
        Some(branch_name) => run_history_statement(
            conn,
            "SELECT dolt_fetch(?1, ?2)",
            &[&remote_name, &branch_name],
        ),
        None => run_history_statement(conn, "SELECT dolt_fetch(?1)", &[&remote_name]),
    }
}

pub fn remote_rows(conn: &GraphConnection) -> SqlResult<Vec<DoltRemoteRow>> {
    let mut statement =
        conn.prepare("SELECT name, url, fetch_specs, params FROM dolt_remotes ORDER BY name")?;
    let rows = statement.query_map([], |row| {
        Ok(DoltRemoteRow {
            name: row.get(0)?,
            url: row.get(1)?,
            fetch_specs: row.get(2)?,
            params: row.get(3)?,
        })
    })?;
    rows.collect()
}

pub fn diff_row_count(
    conn: &GraphConnection,
    table_name: &str,
    from_ref: &str,
    to_ref: &str,
) -> SqlResult<i64> {
    if !table_name
        .chars()
        .all(|character| character.is_ascii_alphanumeric() || character == '_')
    {
        return Err(rusqlite::Error::InvalidParameterName(
            table_name.to_string(),
        ));
    }

    let query = format!("SELECT COUNT(*) FROM dolt_diff_{table_name}(?1, ?2)");
    conn.query_row(&query, params![from_ref, to_ref], |row| row.get(0))
}

pub fn conflict_rows(conn: &GraphConnection) -> SqlResult<Vec<HistoryConflict>> {
    let mut statement =
        conn.prepare("SELECT \"table\", num_conflicts FROM dolt_conflicts ORDER BY \"table\"")?;
    let rows = statement.query_map([], |row| {
        Ok(HistoryConflict {
            table_name: row.get(0)?,
            num_conflicts: row.get(1)?,
        })
    })?;
    rows.collect()
}

// This is the self-bound entry point used by code written against `HistoryStore`. Methods delegate
// to the connection-oriented functions above when an equivalent function exists.
impl HistoryStore for DoltHistoryStore<'_> {
    #[cfg_attr(feature = "profiling", tracing::instrument(skip(self)))]
    fn current_head(&self) -> SqlResult<Option<DoltHashId>> {
        self.graph
            .query_row(
                "SELECT hash FROM dolt_branches WHERE name = active_branch()",
                [],
                |row| row.get(0),
            )
            .optional()
    }

    #[cfg_attr(feature = "profiling", tracing::instrument(skip(self)))]
    fn current_branch(&self) -> SqlResult<Option<BranchName>> {
        self.graph
            .query_row("SELECT active_branch()", [], |row| row.get::<_, String>(0))
            .optional()
            .map(|branch_name| branch_name.map(BranchName))
    }

    #[cfg_attr(feature = "profiling", tracing::instrument(skip(self, reference)))]
    fn resolve_ref(&self, reference: &CommitRef) -> HistoryResult<Option<DoltHashId>> {
        if reference.0 == "HEAD" {
            return self.current_head().map_err(HistoryError::from);
        }

        if let Some((base_reference, offset)) = reference.0.rsplit_once('~') {
            let offset = match offset.parse::<usize>() {
                Ok(offset) => offset,
                Err(_) => return Ok(None),
            };
            let Some(head_hash) = self.resolve_ref(&CommitRef(base_reference.to_string()))? else {
                return Ok(None);
            };
            return nth_ancestor_hash(self.graph, &head_hash, offset).map_err(HistoryError::from);
        }

        let branch_hash = self
            .graph
            .query_row(
                "SELECT hash FROM dolt_branches WHERE name = ?1",
                [&reference.0],
                |row| row.get(0),
            )
            .optional()
            .map_err(HistoryError::from)?;
        if branch_hash.is_some() {
            return Ok(branch_hash);
        }

        let prefix_matches = log_entries(self.graph)
            .map_err(HistoryError::from)?
            .into_iter()
            .filter(|entry| entry.commit_hash.to_string().starts_with(&reference.0))
            .map(|entry| entry.commit_hash)
            .collect::<Vec<_>>();
        if prefix_matches.len() == 1 {
            return Ok(prefix_matches.into_iter().next());
        }
        if prefix_matches.len() > 1 {
            return Err(HistoryError::AmbiguousReference(reference.0.clone()));
        }

        if let Ok(commit_hash) = DoltHashId::try_from(reference.0.as_str()) {
            return Ok(Some(commit_hash));
        }

        Ok(None)
    }

    #[cfg_attr(feature = "profiling", tracing::instrument(skip(self, reference)))]
    fn resolve_operation_hash(&self, reference: &CommitRef) -> HistoryResult<DoltHashId> {
        self.resolve_ref(reference)?
            .ok_or_else(|| HistoryError::UnresolvedReference(reference.0.clone()))
    }

    #[cfg_attr(feature = "profiling", tracing::instrument(skip(self, reference)))]
    fn log_for_ref(
        &self,
        reference: &CommitRef,
        limit: Option<usize>,
    ) -> HistoryResult<Vec<HistoryEntry>> {
        let head_hash = self
            .resolve_ref(reference)?
            .ok_or_else(|| HistoryError::UnresolvedReference(reference.0.clone()))?;
        let history = head_log_entries(self.graph, &head_hash, limit)?
            .into_iter()
            .map(|entry| HistoryEntry {
                is_head: entry.commit_hash == head_hash,
                commit_hash: entry.commit_hash,
                parent_hash: entry.parent_hash,
                committer: entry.committer,
                email: entry.email,
                date: entry.date,
                message: entry.message,
            })
            .collect::<Vec<_>>();
        Ok(history)
    }

    #[cfg_attr(feature = "profiling", tracing::instrument(skip(self)))]
    fn log(&self, limit: Option<usize>) -> SqlResult<Vec<HistoryEntry>> {
        let head_hash = self.current_head()?;
        let history = match head_hash.as_ref() {
            Some(head_hash) => head_log_entries(self.graph, head_hash, limit)?,
            None => Vec::new(),
        }
        .into_iter()
        .map(|entry| HistoryEntry {
            is_head: head_hash.as_ref() == Some(&entry.commit_hash),
            commit_hash: entry.commit_hash,
            parent_hash: entry.parent_hash,
            committer: entry.committer,
            email: entry.email,
            date: entry.date,
            message: entry.message,
        })
        .collect::<Vec<_>>();
        Ok(history)
    }

    #[cfg_attr(feature = "profiling", tracing::instrument(skip(self)))]
    fn status(&self) -> SqlResult<Vec<HistoryStatus>> {
        status_rows(self.graph).map(|rows| {
            rows.into_iter()
                .map(|row| HistoryStatus {
                    table_name: row.table_name,
                    staged: row.staged,
                    status: row.status,
                })
                .collect()
        })
    }

    fn conflicts(&self) -> SqlResult<Vec<HistoryConflict>> {
        conflict_rows(self.graph)
    }

    fn commit_exists(&self, commit_hash: &DoltHashId) -> SqlResult<bool> {
        commit_exists(self.graph, commit_hash)
    }

    fn commit_parents(&self, commit_hash: &DoltHashId) -> SqlResult<Vec<DoltHashId>> {
        commit_parents(self.graph, commit_hash)
    }

    fn is_ancestor(
        &self,
        ancestor_hash: &DoltHashId,
        descendant_hash: &DoltHashId,
    ) -> SqlResult<bool> {
        is_ancestor(self.graph, ancestor_hash, descendant_hash)
    }

    #[cfg_attr(feature = "profiling", tracing::instrument(skip(self, message)))]
    fn commit_all(&self, message: &str) -> SqlResult<DoltHashId> {
        commit_all_with_config(self.graph, self.config, message)
    }

    fn checkout_branch(&self, branch_name: &BranchName) -> SqlResult<()> {
        connect_branch(self.graph, &branch_name.0)
    }

    fn checkout_commit(&self, commit_hash: &DoltHashId) -> SqlResult<()> {
        run_history_statement(self.graph, "SELECT dolt_checkout(?1)", &[commit_hash])
    }

    fn create_branch(
        &self,
        branch_name: &BranchName,
        start_ref: Option<&CommitRef>,
    ) -> SqlResult<()> {
        match start_ref {
            Some(start_ref) => run_history_statement(
                self.graph,
                "SELECT dolt_branch(?1, ?2)",
                &[&branch_name.0, &start_ref.0],
            ),
            None => create_branch(self.graph, &branch_name.0),
        }
    }

    fn delete_branch(&self, branch_name: &BranchName) -> SqlResult<()> {
        delete_branch(self.graph, &branch_name.0)
    }

    fn merge_base(&self, source: &CommitRef, target: &CommitRef) -> SqlResult<DoltHashId> {
        merge_base(self.graph, &source.0, &target.0)
    }

    fn merge(&self, reference: &CommitRef) -> SqlResult<DoltHashId> {
        merge(self.graph, &reference.0)
    }

    fn cherry_pick(&self, commit_hash: &DoltHashId) -> SqlResult<()> {
        cherry_pick(self.graph, &commit_hash.to_string())
    }

    fn reset_hard(&self, target: &CommitRef) -> SqlResult<()> {
        reset_hard(self.graph, &target.0)
    }

    fn push(&self, remote_name: &str, branch_name: &BranchName) -> SqlResult<()> {
        push(self.graph, remote_name, &branch_name.0)
    }

    fn pull(&self, remote_name: &str, branch_name: &BranchName) -> SqlResult<()> {
        pull(self.graph, remote_name, &branch_name.0)
    }

    fn fetch(&self, remote_name: &str, branch_name: Option<&BranchName>) -> SqlResult<()> {
        fetch(
            self.graph,
            remote_name,
            branch_name.map(|branch_name| branch_name.0.as_str()),
        )
    }

    fn graph(&self) -> &GraphConnection {
        self.graph
    }
}

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

    use gen_core::{
        BranchName, CommitRef, DoltHashId, HashId, PATH_END_NODE_ID, PATH_START_NODE_ID, Strand,
    };
    use tempfile::tempdir;

    use super::{
        DoltHistoryStore, active_branch, add_remote, branch_exists, branch_hash, branch_rows,
        branches_exist, checkout, commit_all, commit_exists, commit_parents, commit_staged_all,
        conflict_rows, connect_branch, create_branch, delete_branch_force, diff_row_count, hash_of,
        is_ancestor, is_current_branch_dirty, log_entries, log_entries_for_hashes,
        log_entries_for_revision, merge, merge_base, remote_rows, remove_remote, reset_hard,
        search_branch_names, set_commit_author_email, set_commit_author_name, status_rows,
    };
    use crate::{
        annotations::{AnnotationFileChecksumOverrides, add_annotation_file},
        assets::{AssetRef, AssetRole, OperationAsset, OperationKind},
        block_group_edge::{BlockGroupEdge, BlockGroupEdgeData},
        collection::Collection,
        db,
        edge::Edge,
        history::{HistoryError, HistoryStore},
        operations::Defaults,
        path::Path,
        sample::{NewSample, Sample},
        test_helpers::{create_bg, get_connection, setup_gen_on_disk},
    };

    #[test]
    fn test_diff_row_count_counts_committed_sample_change() {
        let conn = get_connection(None).expect("should create graph database");

        Collection::create(&conn, "main-collection").expect("should insert collection");
        commit_all(&conn, "initial commit").expect("should create initial commit");
        Sample::create(
            &conn,
            NewSample {
                name: "feature-sample",
                is_reference: false,
            },
        )
        .expect("should insert sample");
        commit_all(&conn, "sample commit").expect("should commit sample change");

        let sample_diff_count = diff_row_count(&conn, "samples", "HEAD~1", "HEAD")
            .expect("should diff committed samples");
        assert_eq!(
            sample_diff_count, 1,
            "sample commit should add one sample row"
        );
    }

    #[test]
    fn test_resolve_operation_hash_rejects_an_unresolved_commit_ref() {
        let conn = get_connection(None).expect("should create graph database");
        let history_store = DoltHistoryStore::new(&conn);

        let error = history_store
            .resolve_operation_hash(&CommitRef("missing-commit".to_string()))
            .expect_err("should reject an unresolved commit reference");

        assert!(
            matches!(error, HistoryError::UnresolvedReference(reference) if reference == "missing-commit"),
            "missing commit should produce an unresolved-reference error"
        );
    }

    #[test]
    fn test_branch_rows_include_created_branch() {
        let conn = get_connection(None).expect("should create graph database");

        create_branch(&conn, "feature").expect("should create a feature branch");

        let branches = branch_rows(&conn).expect("should query branches");
        assert!(
            branches.iter().any(|branch| branch.name == "feature"),
            "branch list should include the created feature branch"
        );
        assert!(branch_exists(&conn, "feature").expect("should find feature branch"));
        assert!(!branch_exists(&conn, "missing").expect("should not find missing branch"));
        assert_eq!(
            branch_hash(&conn, "feature").expect("should read feature hash"),
            branches
                .iter()
                .find(|branch| branch.name == "feature")
                .map(|branch| branch.hash)
        );
        assert_eq!(
            Some(hash_of(&conn, "feature").expect("should resolve feature hash")),
            branch_hash(&conn, "feature").expect("should read feature hash")
        );
        assert_eq!(
            branch_hash(&conn, "missing").expect("missing branch should be optional"),
            None
        );
    }

    #[test]
    fn test_branches_exist_returns_distinct_exact_name_results() {
        let conn = get_connection(None).expect("should create graph database");
        let special_branch = "release%_branch'quote";

        create_branch(&conn, "feature").expect("should create feature branch");
        create_branch(&conn, special_branch).expect("should create special-character branch");

        let requested = [
            "missing",
            "feature",
            "feature",
            special_branch,
            "missing%_branch'quote",
            "Feature",
            "feat%",
        ];
        let found = branches_exist(&conn, &requested).expect("should query branch existence");

        assert_eq!(
            found,
            HashMap::from([
                ("missing".to_string(), false),
                ("feature".to_string(), true),
                (special_branch.to_string(), true),
                ("missing%_branch'quote".to_string(), false),
                ("Feature".to_string(), false),
                ("feat%".to_string(), false),
            ])
        );
        assert_eq!(found.len(), 6, "duplicate input names should collapse");
        for branch_name in requested {
            let single_result =
                branch_exists(&conn, branch_name).expect("should query single branch existence");
            assert_eq!(
                found.get(branch_name).copied(),
                Some(single_result),
                "bulk and single branch existence should agree for {branch_name:?}"
            );
        }
    }

    #[test]
    fn test_branches_exist_returns_empty_for_empty_input() {
        let conn = get_connection(None).expect("should create graph database");

        assert_eq!(
            branches_exist(&conn, &[]).expect("should return an empty result"),
            HashMap::<String, bool>::new()
        );
    }

    #[test]
    fn search_branch_names_ranks_exact_then_prefix_matches() {
        let conn = get_connection(None).expect("should create graph database");
        for name in ["feature", "feature-next", "my-feature"] {
            create_branch(&conn, name).expect("should create branch");
        }

        let branches = search_branch_names(&conn, "feature").expect("should search branches");

        assert_eq!(branches, vec!["feature", "feature-next", "my-feature"]);
    }

    #[test]
    fn test_merge_then_reset_hard_restores_pre_merge_state() {
        let conn = get_connection(None).expect("should create graph database");

        Collection::create(&conn, "main-collection").expect("should insert graph row");
        commit_all(&conn, "initial commit").expect("should create initial commit");
        let main_branch = active_branch(&conn).expect("should resolve the active branch");
        create_branch(&conn, "feature").expect("should create a feature branch");
        checkout(&conn, "feature").expect("should checkout feature branch");
        Sample::create(
            &conn,
            NewSample {
                name: "feature-sample",
                is_reference: false,
            },
        )
        .expect("should insert feature branch graph row");
        commit_all(&conn, "feature commit").expect("should commit feature branch changes");
        checkout(&conn, &main_branch).expect("should checkout the original branch");
        Collection::create(&conn, "main-second-collection")
            .expect("should insert a main branch graph row");
        commit_all(&conn, "main branch commit").expect("should commit main branch change");
        conn.with_transaction(|| merge(&conn, "feature"))
            .expect("should merge feature branch");

        let feature_sample_exists_after_merge = conn
            .query_row(
                "SELECT EXISTS(SELECT 1 FROM samples WHERE name = ?1)",
                ["feature-sample"],
                |row| row.get::<_, bool>(0),
            )
            .expect("should query merged sample state");
        assert!(
            feature_sample_exists_after_merge,
            "merge should add rows from the feature branch"
        );

        reset_hard(&conn, "HEAD~1").expect("should hard reset to the pre-merge commit");
        let feature_sample_exists = conn
            .query_row(
                "SELECT EXISTS(SELECT 1 FROM samples WHERE name = ?1)",
                ["feature-sample"],
                |row| row.get::<_, bool>(0),
            )
            .expect("should query reset sample state");
        assert!(
            !feature_sample_exists,
            "hard reset should remove rows introduced by the merge"
        );
    }

    #[test]
    fn test_merge_base_returns_common_ancestor_of_divergent_branches() {
        let conn = get_connection(None).expect("should create graph database");

        Collection::create(&conn, "base-collection").expect("should insert base graph row");
        let base = commit_all(&conn, "base commit").expect("should create base commit");
        let main_branch = active_branch(&conn).expect("should resolve the active branch");
        create_branch(&conn, "feature").expect("should create feature branch");

        Collection::create(&conn, "main-collection").expect("should insert main graph row");
        commit_all(&conn, "main commit").expect("should create main commit");

        checkout(&conn, "feature").expect("should checkout feature branch");
        Collection::create(&conn, "feature-collection").expect("should insert feature graph row");
        commit_all(&conn, "feature commit").expect("should create feature commit");

        let common_ancestor =
            merge_base(&conn, &main_branch, "feature").expect("should resolve merge base");
        assert_eq!(
            common_ancestor, base,
            "merge base should be common ancestor"
        );
    }

    // History order is for presentation, while `parent_hash` and tilde refs
    // represent directed first-parent edges. A merge must preserve both
    // contracts so callers never infer ancestry from adjacent history rows.
    #[test]
    fn test_merge_history_records_first_parents_and_resolves_tilde_refs() {
        let conn = get_connection(None).expect("should create graph database");
        let history_store = DoltHistoryStore::new(&conn);

        Collection::create(&conn, "base-collection").expect("should insert base graph row");
        let base_commit = history_store
            .commit_all("base")
            .expect("should commit base state");
        history_store
            .create_branch(&BranchName("feature".to_string()), None)
            .expect("should create feature branch");
        history_store
            .checkout_branch(&BranchName("feature".to_string()))
            .expect("should checkout feature branch");
        Collection::create(&conn, "feature-collection").expect("should insert feature graph row");
        let feature_commit = history_store
            .commit_all("feature")
            .expect("should commit feature state");

        history_store
            .checkout_branch(&BranchName("main".to_string()))
            .expect("should checkout main branch");
        Collection::create(&conn, "main-collection").expect("should insert main graph row");
        let main_commit = history_store
            .commit_all("main")
            .expect("should commit main state");
        conn.with_transaction(|| history_store.merge(&CommitRef("feature".to_string())))
            .expect("should merge feature branch");
        let merge_commit = history_store
            .current_head()
            .expect("should query merged head")
            .expect("should create a merge commit");
        let entries = history_store.log(None).expect("should load merged history");
        let parent_for = |commit_hash| {
            entries
                .iter()
                .find(|entry| entry.commit_hash == commit_hash)
                .expect("should include commit in merged history")
                .parent_hash
        };

        assert_eq!(
            parent_for(merge_commit),
            Some(main_commit),
            "merge entry should record the main-side first parent"
        );
        assert_eq!(
            parent_for(main_commit),
            Some(base_commit),
            "main commit should retain its direct parent"
        );
        assert_eq!(
            parent_for(feature_commit),
            Some(base_commit),
            "feature commit should retain its direct parent"
        );
        assert!(
            entries.iter().any(|entry| entry.parent_hash.is_none()),
            "merged history should retain its root entry without a parent"
        );
        assert_eq!(
            history_store
                .resolve_ref(&CommitRef("HEAD~1".to_string()))
                .expect("should resolve first parent"),
            Some(main_commit),
            "HEAD~1 should follow the merge's first-parent edge"
        );
        assert_eq!(
            history_store
                .resolve_ref(&CommitRef("HEAD~2".to_string()))
                .expect("should resolve first-parent grandparent"),
            Some(base_commit),
            "HEAD~2 should remain on the main-side first-parent chain"
        );
    }

    #[test]
    fn test_merge_by_commit_returns_all_parents_after_source_branch_deleted() {
        let conn = get_connection(None).expect("should create graph database");

        Collection::create(&conn, "base").expect("should create base collection");
        commit_all(&conn, "base").expect("should commit base state");
        create_branch(&conn, "feature").expect("should create feature branch");

        checkout(&conn, "feature").expect("should checkout feature branch");
        Collection::create(&conn, "feature").expect("should create feature collection");
        let source_hash = commit_all(&conn, "feature").expect("should commit feature state");

        checkout(&conn, "main").expect("should checkout main branch");
        Collection::create(&conn, "target").expect("should create target collection");
        let target_hash = commit_all(&conn, "target").expect("should commit target state");

        delete_branch_force(&conn, "feature").expect("should delete the source branch");
        let merge_hash = conn
            .with_transaction(|| merge(&conn, &source_hash.to_string()))
            .expect("should merge the immutable source commit");
        assert_eq!(
            commit_parents(&conn, &merge_hash).expect("should query all merge parents"),
            vec![target_hash, source_hash],
            "merge parents should preserve target then source order"
        );
    }

    #[test]
    fn test_is_ancestor_includes_commit_equality() {
        let conn = get_connection(None).expect("should create graph database");

        Collection::create(&conn, "base").expect("should create base collection");
        let base_hash = commit_all(&conn, "base").expect("should commit base state");
        Collection::create(&conn, "descendant").expect("should create descendant collection");
        let descendant_hash =
            commit_all(&conn, "descendant").expect("should commit descendant state");

        assert!(
            is_ancestor(&conn, &base_hash, &descendant_hash)
                .expect("should query descendant ancestry"),
            "a parent commit should be an ancestor of its descendant"
        );
        assert!(
            is_ancestor(&conn, &descendant_hash, &descendant_hash)
                .expect("should query equal ancestry"),
            "a commit should be an ancestor of itself"
        );
        assert!(
            !is_ancestor(&conn, &descendant_hash, &base_hash)
                .expect("should query reverse ancestry"),
            "a descendant should not be an ancestor of its parent"
        );
        let missing_hash = DoltHashId::try_from("0000000000000000000000000000000000000000")
            .expect("should parse a zero hash");
        assert!(
            !is_ancestor(&conn, &missing_hash, &missing_hash)
                .expect("should query missing ancestry"),
            "an unknown hash should not be considered its own ancestor"
        );
    }

    #[test]
    fn test_merge_returns_source_hash_for_fast_forward_and_noop() {
        let conn = get_connection(None).expect("should create graph database");

        Collection::create(&conn, "base").expect("should create base collection");
        commit_all(&conn, "base").expect("should commit base state");
        create_branch(&conn, "feature").expect("should create feature branch");
        checkout(&conn, "feature").expect("should checkout feature branch");
        Collection::create(&conn, "feature").expect("should create feature collection");
        let source_hash = commit_all(&conn, "feature").expect("should commit feature state");
        checkout(&conn, "main").expect("should checkout main branch");

        assert_eq!(
            conn.with_transaction(|| merge(&conn, &source_hash.to_string()))
                .expect("should fast-forward to source"),
            source_hash,
            "a fast-forward merge should return the resulting source tip"
        );
        assert_eq!(
            conn.with_transaction(|| merge(&conn, &source_hash.to_string()))
                .expect("should merge an already included source"),
            source_hash,
            "an already included source should be a successful no-op returning the current target"
        );
    }

    #[test]
    fn test_merge_requires_active_transaction_for_clean_non_fast_forward() {
        let conn = get_connection(None).expect("should create graph database");

        Collection::create(&conn, "base-collection").expect("should create base collection");
        commit_all(&conn, "base").expect("should commit base state");
        create_branch(&conn, "feature").expect("should create feature branch");

        checkout(&conn, "feature").expect("should checkout feature branch");
        Collection::create(&conn, "feature-only-collection")
            .expect("should create feature collection");
        let source_hash = commit_all(&conn, "feature").expect("should commit feature state");

        checkout(&conn, "main").expect("should checkout main branch");
        Collection::create(&conn, "target-only-collection")
            .expect("should create target collection");
        let target_hash = commit_all(&conn, "target").expect("should commit target state");
        assert_ne!(
            source_hash, target_hash,
            "feature and target must be distinct tips for a non-fast-forward merge"
        );

        let status_before = status_rows(&conn).expect("should read target status before merge");
        assert!(
            status_before.is_empty(),
            "target history should be clean before rejected merge"
        );
        let conflicts_before = conflict_rows(&conn).expect("should read conflicts before merge");
        assert!(
            conflicts_before.is_empty(),
            "target history should have no conflicts before rejected merge"
        );
        let merge_status_before: i64 = conn
            .query_row("SELECT is_merging FROM dolt_merge_status", [], |row| {
                row.get(0)
            })
            .expect("should read merge status before merge");
        assert_eq!(
            merge_status_before, 0,
            "target history should not be merging before rejected merge"
        );
        let target_hash_before = hash_of(&conn, "main").expect("should read target hash");
        assert!(
            Collection::exists(&conn, "target-only-collection"),
            "target data should exist before rejected merge"
        );
        assert!(
            !Collection::exists(&conn, "feature-only-collection"),
            "feature-only data should be absent from target before rejected merge"
        );

        let merge_error =
            merge(&conn, "feature").expect_err("merge should require an active transaction");
        assert!(
            matches!(
                merge_error,
                rusqlite::Error::SqliteFailure(error, Some(message))
                    if error.extended_code == rusqlite::ffi::SQLITE_MISUSE
                        && message == "merge requires an active transaction"
            ),
            "merge should report its active-transaction precondition"
        );
        assert_eq!(
            hash_of(&conn, "main").expect("should read target hash after rejected merge"),
            target_hash_before,
            "rejected merge must not advance the target branch"
        );
        assert!(
            Collection::exists(&conn, "target-only-collection"),
            "rejected merge must preserve target data"
        );
        assert!(
            !Collection::exists(&conn, "feature-only-collection"),
            "rejected merge must not add feature-only data"
        );
        assert_eq!(
            status_rows(&conn).expect("should read target status after rejected merge"),
            status_before,
            "rejected merge must preserve clean working-set status"
        );
        assert_eq!(
            conflict_rows(&conn).expect("should read conflicts after rejected merge"),
            conflicts_before,
            "rejected merge must not leave conflict rows behind"
        );
        assert_eq!(
            conn.query_row("SELECT is_merging FROM dolt_merge_status", [], |row| row
                .get::<_, i64>(0))
                .expect("should read merge status after rejected merge"),
            0,
            "rejected merge must not leave merge state behind"
        );
        assert!(
            conn.is_autocommit(),
            "a rejected merge must not open a transaction"
        );
    }

    #[test]
    fn test_merge_resolves_created_on_conflict_and_merges_independent_row() {
        let conn = get_connection(None).expect("should create graph database");

        Collection::create(&conn, "merge-collection").expect("should create merge collection");
        let block_group = create_bg(&conn, "merge-collection", "merge-sample", "chr1");
        let edge = Edge::create(
            &conn,
            PATH_START_NODE_ID,
            0,
            Strand::Forward,
            PATH_END_NODE_ID,
            0,
            Strand::Forward,
        )
        .expect("should create merge edge");
        let base_block_group_edge = BlockGroupEdgeData {
            block_group_id: block_group.id,
            edge_id: edge.id,
            chromosome_index: 0,
            phased: 0,
        };
        let base_block_group_edge_id = base_block_group_edge.id_hash();
        BlockGroupEdge::bulk_create(&conn, std::slice::from_ref(&base_block_group_edge));
        conn.execute(
            "UPDATE block_group_edges SET created_on = ?1 WHERE id = ?2",
            rusqlite::params![1_i64, base_block_group_edge_id],
        )
        .expect("should set deterministic base timestamp");
        commit_all(&conn, "base").expect("should commit base state");
        create_branch(&conn, "feature").expect("should create feature branch");

        checkout(&conn, "feature").expect("should checkout feature branch");
        conn.execute(
            "UPDATE block_group_edges SET created_on = ?1 WHERE id = ?2",
            rusqlite::params![2_i64, base_block_group_edge_id],
        )
        .expect("should update feature timestamp");
        let independent_block_group_edge = BlockGroupEdgeData {
            chromosome_index: 1,
            ..base_block_group_edge
        };
        let independent_block_group_edge_id = independent_block_group_edge.id_hash();
        BlockGroupEdge::bulk_create(&conn, std::slice::from_ref(&independent_block_group_edge));
        conn.execute(
            "UPDATE block_group_edges SET created_on = ?1 WHERE id = ?2",
            rusqlite::params![20_i64, independent_block_group_edge_id],
        )
        .expect("should set independent feature timestamp");
        let source_hash = commit_all(&conn, "feature").expect("should commit feature state");

        checkout(&conn, "main").expect("should checkout main branch");
        conn.execute(
            "UPDATE block_group_edges SET created_on = ?1 WHERE id = ?2",
            rusqlite::params![3_i64, base_block_group_edge_id],
        )
        .expect("should update target timestamp");
        let target_hash = commit_all(&conn, "target").expect("should commit target state");

        let merge_hash = conn
            .with_transaction(|| merge(&conn, "feature"))
            .expect("should resolve created_on-only conflict");
        assert_eq!(
            conn.query_row(
                "SELECT created_on FROM block_group_edges WHERE id = ?1",
                [&base_block_group_edge_id],
                |row| row.get::<_, i64>(0),
            )
            .expect("should read the resolved row"),
            3,
            "the target created_on value should win the conflict"
        );
        assert_eq!(
            conn.query_row(
                "SELECT created_on FROM block_group_edges WHERE id = ?1",
                [&independent_block_group_edge_id],
                |row| row.get::<_, i64>(0),
            )
            .expect("should read the independent source row"),
            20,
            "an independent source row should be merged"
        );
        assert_eq!(
            commit_parents(&conn, &merge_hash).expect("should query merge parents"),
            vec![target_hash, source_hash],
            "the resolved merge should retain target then source parents"
        );
        assert!(
            status_rows(&conn)
                .expect("should read merged working-set status")
                .is_empty(),
            "the resolved merge should leave a clean working set"
        );
    }

    #[test]
    fn test_merge_rejects_unhandled_conflicts_atomically() {
        // Currently we do not handle a case where a path between 2 branches has a differing edge_id paths. This shows that
        // conflict emerges and prevents the merge
        let conn = get_connection(None).expect("should create graph database");

        Collection::create(&conn, "merge-collection").expect("should create merge collection");
        let block_group = create_bg(&conn, "merge-collection", "merge-sample", "chr1");
        let base_edge = Edge::create(
            &conn,
            PATH_START_NODE_ID,
            0,
            Strand::Forward,
            PATH_END_NODE_ID,
            0,
            Strand::Forward,
        )
        .expect("should create base edge");
        let feature_edge = Edge::create(
            &conn,
            PATH_START_NODE_ID,
            1,
            Strand::Forward,
            PATH_END_NODE_ID,
            1,
            Strand::Forward,
        )
        .expect("should create feature edge");
        let target_edge = Edge::create(
            &conn,
            PATH_START_NODE_ID,
            2,
            Strand::Forward,
            PATH_END_NODE_ID,
            2,
            Strand::Forward,
        )
        .expect("should create target edge");
        let base_block_group_edge = BlockGroupEdgeData {
            block_group_id: block_group.id,
            edge_id: base_edge.id,
            chromosome_index: 0,
            phased: 0,
        };
        let feature_block_group_edge = BlockGroupEdgeData {
            edge_id: feature_edge.id,
            ..base_block_group_edge
        };
        let target_block_group_edge = BlockGroupEdgeData {
            edge_id: target_edge.id,
            ..base_block_group_edge
        };
        let base_block_group_edge_id = base_block_group_edge.id_hash();
        BlockGroupEdge::bulk_create(
            &conn,
            &[
                base_block_group_edge,
                feature_block_group_edge,
                target_block_group_edge,
            ],
        );
        let path = Path::create(&conn, "chr1", &block_group.id, &[base_edge.id])
            .expect("should create base path");
        conn.execute(
            "UPDATE block_group_edges SET created_on = ?1 WHERE id = ?2",
            rusqlite::params![1_i64, base_block_group_edge_id],
        )
        .expect("should set deterministic base timestamp");
        commit_all(&conn, "base").expect("should commit base state");
        create_branch(&conn, "feature").expect("should create feature branch");

        checkout(&conn, "feature").expect("should checkout feature branch");
        conn.execute(
            "UPDATE block_group_edges SET created_on = ?1 WHERE id = ?2",
            rusqlite::params![2_i64, base_block_group_edge_id],
        )
        .expect("should update feature timestamp");
        conn.execute(
            "UPDATE paths SET edge_ids = ?1 WHERE id = ?2",
            rusqlite::params![feature_edge.id.0.to_vec(), path.id],
        )
        .expect("should update feature path edges");
        let source_hash = commit_all(&conn, "feature").expect("should commit feature conflict");

        checkout(&conn, "main").expect("should checkout main branch");
        conn.execute(
            "UPDATE block_group_edges SET created_on = ?1 WHERE id = ?2",
            rusqlite::params![3_i64, base_block_group_edge_id],
        )
        .expect("should update target timestamp");
        conn.execute(
            "UPDATE paths SET edge_ids = ?1 WHERE id = ?2",
            rusqlite::params![target_edge.id.0.to_vec(), path.id],
        )
        .expect("should update target path edges");
        let target_hash = commit_all(&conn, "target").expect("should commit target conflict");

        let merge_error = conn
            .with_transaction(|| merge(&conn, "feature"))
            .expect_err("should reject created_on plus value conflicts");
        assert!(
            merge_error.to_string().contains("conflict")
                || merge_error.to_string().contains("CONSTRAINT"),
            "merge failure should identify the unresolved conflict: {merge_error}"
        );
        assert_eq!(
            hash_of(&conn, "main").expect("should read target hash after failed merge"),
            target_hash,
            "an aborted merge must not advance the target branch"
        );
        assert_eq!(
            conn.query_row(
                "SELECT created_on FROM block_group_edges WHERE id = ?1",
                [&base_block_group_edge_id],
                |row| row.get::<_, i64>(0),
            )
            .expect("should read target block group edge after failed merge"),
            3,
            "an aborted merge must restore the target block group edge"
        );
        assert_eq!(
            Path::edge_ids_for_path(&conn, &path.id, None),
            vec![target_edge.id],
            "an aborted merge must restore the target path edges"
        );
        assert!(
            status_rows(&conn)
                .expect("should read working-set status after failed merge")
                .is_empty(),
            "an aborted merge must leave the working set clean"
        );

        assert_eq!(
            commit_parents(&conn, &source_hash)
                .expect("should query source parents")
                .len(),
            1,
            "the source commit should remain unchanged after the failed merge"
        );
    }

    #[test]
    fn test_merge_does_not_resolve_conflict_in_custom_table() {
        // Shows we only resolve conflicts in our explicit tables
        let conn = get_connection(None).expect("should create graph database");

        conn.execute(
            "CREATE TABLE custom_created_on_conflict (\
                id INTEGER PRIMARY KEY,\
                value TEXT NOT NULL,\
                created_on INTEGER NOT NULL\
            )",
            [],
        )
        .expect("should create custom conflict fixture table");
        conn.execute(
            "INSERT INTO custom_created_on_conflict (id, value, created_on) \
             VALUES (1, 'same', 1)",
            [],
        )
        .expect("should create base custom row");
        commit_all(&conn, "base").expect("should commit base state");
        create_branch(&conn, "feature").expect("should create feature branch");

        checkout(&conn, "feature").expect("should checkout feature branch");
        conn.execute(
            "UPDATE custom_created_on_conflict SET created_on = 2 WHERE id = 1",
            [],
        )
        .expect("should update feature timestamp");
        let source_hash = commit_all(&conn, "feature").expect("should commit feature state");

        checkout(&conn, "main").expect("should checkout main branch");
        conn.execute(
            "UPDATE custom_created_on_conflict SET created_on = 3 WHERE id = 1",
            [],
        )
        .expect("should update target timestamp");
        let target_hash = commit_all(&conn, "target").expect("should commit target state");

        let merge_error = conn
            .with_transaction(|| merge(&conn, &source_hash.to_string()))
            .expect_err("should reject custom created_on-only conflicts");
        assert!(
            merge_error.to_string().contains("conflict")
                || merge_error.to_string().contains("CONSTRAINT"),
            "merge failure should identify the unresolved conflict: {merge_error}"
        );
        assert_eq!(
            hash_of(&conn, "main").expect("should read target hash after failed merge"),
            target_hash,
            "an aborted merge must not advance the target branch"
        );
        assert_eq!(
            conn.query_row(
                "SELECT value, created_on FROM custom_created_on_conflict WHERE id = 1",
                [],
                |row| Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)?)),
            )
            .expect("should read target data after failed merge"),
            ("same".to_string(), 3),
            "an aborted merge must restore the target row"
        );
        assert!(
            status_rows(&conn)
                .expect("should read working-set status after failed merge")
                .is_empty(),
            "an aborted merge must leave the working set clean"
        );
    }

    #[test]
    fn test_merge_conflict_is_atomic_and_preserves_target_hash() {
        let conn = get_connection(None).expect("should create graph database");

        conn.execute(
            "CREATE TABLE merge_conflicts (id INTEGER PRIMARY KEY, value TEXT NOT NULL)",
            [],
        )
        .expect("should create conflict fixture table");
        conn.execute(
            "INSERT INTO merge_conflicts (id, value) VALUES (1, 'base')",
            [],
        )
        .expect("should create base conflict row");
        commit_all(&conn, "base").expect("should commit base state");
        create_branch(&conn, "feature").expect("should create feature branch");

        checkout(&conn, "feature").expect("should checkout feature branch");
        conn.execute(
            "UPDATE merge_conflicts SET value = 'feature' WHERE id = 1",
            [],
        )
        .expect("should update feature conflict row");
        let source_hash =
            commit_all(&conn, "feature conflict").expect("should commit feature conflict");

        checkout(&conn, "main").expect("should checkout main branch");
        conn.execute(
            "UPDATE merge_conflicts SET value = 'target' WHERE id = 1",
            [],
        )
        .expect("should update target conflict row");
        let target_hash =
            commit_all(&conn, "target conflict").expect("should commit target conflict");

        let merge_error = conn
            .with_transaction(|| merge(&conn, &source_hash.to_string()))
            .expect_err("should reject conflicting collection rows");
        assert!(
            merge_error.to_string().contains("conflict")
                || merge_error.to_string().contains("CONSTRAINT"),
            "merge failure should identify the conflicting operation: {merge_error}"
        );
        assert_eq!(
            hash_of(&conn, "main").expect("should read target hash after failed merge"),
            target_hash,
            "an aborted DoltLite merge must not advance the target branch"
        );
        assert_eq!(
            conn.query_row(
                "SELECT value FROM merge_conflicts WHERE id = 1",
                [],
                |row| row.get::<_, String>(0),
            )
            .expect("should read target data after failed merge"),
            "target",
            "an aborted DoltLite merge must restore the target data"
        );
        assert!(
            status_rows(&conn)
                .expect("should read working-set status after failed merge")
                .is_empty(),
            "an aborted DoltLite merge must leave the working set clean"
        );
    }

    #[test]
    fn test_remote_rows_include_added_remote() {
        let conn = get_connection(None).expect("should create graph database");

        let remote_dir = tempdir().expect("should create temporary remote directory");
        let remote_url = remote_dir.path().display().to_string();
        add_remote(&conn, "origin", &remote_url).expect("should add a file remote");
        let remotes = remote_rows(&conn).expect("should query remotes");
        assert!(
            remotes
                .iter()
                .any(|remote| remote.name == "origin" && remote.url == remote_url),
            "dolt_remotes should include the configured file remote"
        );

        remove_remote(&conn, "origin").expect("should remove the file remote");
        assert!(
            remote_rows(&conn).expect("should query remotes").is_empty(),
            "dolt_remotes should not include the removed remote"
        );
    }

    #[test]
    fn test_commit_staged_all_clears_status() {
        let conn = get_connection(None).expect("should create graph database");

        Collection::create(&conn, "main-collection").expect("should insert graph row");
        let status_before_commit = status_rows(&conn).expect("should query dolt status");
        assert!(
            !status_before_commit.is_empty(),
            "status should report modified tables before commit"
        );

        let commit_hash =
            commit_staged_all(&conn, "initial commit").expect("should commit staged changes");
        assert!(
            commit_hash != DoltHashId::default(),
            "commit hash should be returned for explicit staged-all commit"
        );

        let clean_status = status_rows(&conn).expect("should query clean dolt status");
        assert!(
            clean_status.is_empty(),
            "explicit staged-all commit should clear dolt status"
        );
    }

    #[test]
    fn test_commit_all_uses_configured_commit_author() {
        let conn = get_connection(None).expect("should create graph database");
        set_commit_author_name(&conn, "Test User").expect("should configure commit author name");
        set_commit_author_email(&conn, "test@example.com")
            .expect("should configure commit author email");

        Collection::create(&conn, "main-collection").expect("should insert graph row");
        commit_all(&conn, "initial commit").expect("should commit staged changes");

        let history = log_entries(&conn).expect("should query Dolt log");
        let head = history.first().expect("should contain committed entry");
        assert_eq!(head.committer, "Test User");
        assert_eq!(head.email, "test@example.com");
    }

    #[test]
    fn test_commit_all_uses_config_default_commit_author() {
        let context = setup_gen_on_disk();
        let graph_conn = context.graph().conn();
        let config_conn = context.config().conn();
        Defaults::set_default_committer_name(config_conn, "Config User")
            .expect("should configure default committer name");
        Defaults::set_default_committer_email(config_conn, "config@example.com")
            .expect("should configure default committer email");

        Collection::create(graph_conn, "main-collection").expect("should insert graph row");
        DoltHistoryStore::new_with_config(graph_conn, config_conn)
            .commit_all("initial commit")
            .expect("should commit staged changes");

        let log = log_entries(graph_conn).expect("should load commit log");
        let head = log.first().expect("should include committed head");
        assert_eq!(head.committer, "Config User");
        assert_eq!(head.email, "config@example.com");
    }

    #[test]
    fn test_commit_all_preserves_configured_commit_author() {
        let context = setup_gen_on_disk();
        let graph_conn = context.graph().conn();
        let config_conn = context.config().conn();
        Defaults::set_default_committer_name(config_conn, "Config User")
            .expect("should configure default committer name");
        Defaults::set_default_committer_email(config_conn, "config@example.com")
            .expect("should configure default committer email");
        set_commit_author_name(graph_conn, "Manual User")
            .expect("should configure graph committer name");
        set_commit_author_email(graph_conn, "manual@example.com")
            .expect("should configure graph committer email");

        Collection::create(graph_conn, "main-collection").expect("should insert graph row");
        DoltHistoryStore::new_with_config(graph_conn, config_conn)
            .commit_all("initial commit")
            .expect("should commit staged changes");

        let log = log_entries(graph_conn).expect("should load commit log");
        let head = log.first().expect("should include committed head");
        assert_eq!(head.committer, "Manual User");
        assert_eq!(head.email, "manual@example.com");
    }

    #[test]
    fn test_commit_staged_all_reports_nothing_to_commit_on_clean_repo() {
        let conn = get_connection(None).expect("should create graph database");

        Collection::create(&conn, "main-collection").expect("should insert graph row");
        commit_all(&conn, "initial commit").expect("should commit initial state");

        let err = commit_staged_all(&conn, "second commit")
            .expect_err("clean repo should not produce a second commit");
        let err_text = err.to_string();
        assert!(
            err_text.contains("nothing to commit"),
            "clean repo error should explain no-op commit: {err_text}"
        );
    }

    #[test]
    fn test_is_current_branch_dirty_matches_status_rows() {
        let conn = get_connection(None).expect("should create graph database");

        assert_eq!(
            is_current_branch_dirty(&conn).expect("should query fresh branch dirty flag"),
            !status_rows(&conn)
                .expect("should query fresh dolt status rows")
                .is_empty(),
            "fresh repo dirty flag should match dolt_status emptiness"
        );

        Collection::create(&conn, "main-collection").expect("should insert graph row");
        assert_eq!(
            is_current_branch_dirty(&conn).expect("should query dirty branch flag"),
            !status_rows(&conn)
                .expect("should query dirty dolt status rows")
                .is_empty(),
            "dirty repo dirty flag should match dolt_status emptiness"
        );

        commit_all(&conn, "initial commit").expect("should commit initial state");
        assert_eq!(
            is_current_branch_dirty(&conn).expect("should query clean branch flag"),
            !status_rows(&conn)
                .expect("should query clean dolt status rows")
                .is_empty(),
            "clean repo dirty flag should match dolt_status emptiness"
        );
    }

    #[test]
    fn test_history_store_resolves_refs_and_logs_commits() {
        let conn = get_connection(None).expect("should create graph database");
        let history_store = DoltHistoryStore::new(&conn);

        Collection::create(&conn, "main-collection").expect("should insert graph row");
        let first_commit = history_store
            .commit_all("initial commit")
            .expect("should commit initial graph change");
        history_store
            .create_branch(&BranchName("feature".to_string()), None)
            .expect("should create branch through the history facade");
        history_store
            .checkout_branch(&BranchName("feature".to_string()))
            .expect("should checkout branch through the history facade");
        Sample::create(
            &conn,
            NewSample {
                name: "feature-sample",
                is_reference: false,
            },
        )
        .expect("should insert feature graph row");
        let second_commit = history_store
            .commit_all("feature commit")
            .expect("should commit feature graph change");
        Sample::create(
            &conn,
            NewSample {
                name: "second-feature-sample",
                is_reference: false,
            },
        )
        .expect("should insert second feature graph row");
        let third_commit = history_store
            .commit_all("second feature commit")
            .expect("should commit second feature graph change");

        let current_head = history_store
            .current_head()
            .expect("should resolve current head")
            .expect("should return a head commit");
        assert_eq!(current_head, third_commit);

        let branch_name = history_store
            .current_branch()
            .expect("should resolve current branch")
            .expect("should return a branch name");
        assert_eq!(branch_name, BranchName("feature".to_string()));

        let head_ref = history_store
            .resolve_ref(&CommitRef("HEAD".to_string()))
            .expect("should resolve HEAD")
            .expect("should match current head");
        assert_eq!(head_ref, third_commit);

        let previous_ref = history_store
            .resolve_ref(&CommitRef("HEAD~1".to_string()))
            .expect("should resolve HEAD~1")
            .expect("should match parent commit");
        assert_eq!(previous_ref, second_commit);

        let grandparent_ref = history_store
            .resolve_ref(&CommitRef("HEAD~2".to_string()))
            .expect("should resolve HEAD~2")
            .expect("should match grandparent commit");
        assert_eq!(grandparent_ref, first_commit);

        let branch_ref = history_store
            .resolve_ref(&CommitRef("feature".to_string()))
            .expect("should resolve branch name")
            .expect("should match branch head");
        assert_eq!(branch_ref, third_commit);

        let third_commit_hex = third_commit.to_string();
        let short_hash = &third_commit_hex[..12];
        let prefix_ref = history_store
            .resolve_ref(&CommitRef(short_hash.to_string()))
            .expect("should resolve unique hash prefix")
            .expect("should match the prefixed commit");
        assert_eq!(prefix_ref, third_commit);

        let head_operation_hash = history_store
            .resolve_operation_hash(&CommitRef("HEAD".to_string()))
            .expect("should resolve HEAD as an operation hash");
        assert_eq!(head_operation_hash, third_commit);

        let history = history_store
            .log(Some(2))
            .expect("should query history through the facade");
        assert_eq!(history.len(), 2, "history log should honor the limit");
        assert!(
            history[0].is_head,
            "the newest history entry should be flagged as HEAD"
        );
        assert_eq!(history[0].message, "second feature commit");
        assert_eq!(history[1].message, "feature commit");
    }

    #[test]
    fn test_log_for_ref_reads_non_current_branch_without_changing_checkout() {
        let conn = get_connection(None).expect("should create graph database");
        let history_store = DoltHistoryStore::new(&conn);

        Collection::create(&conn, "main-collection").expect("should insert main graph row");
        history_store
            .commit_all("main commit")
            .expect("should commit main graph change");
        history_store
            .create_branch(&BranchName("feature".to_string()), None)
            .expect("should create feature branch");
        history_store
            .checkout_branch(&BranchName("feature".to_string()))
            .expect("should checkout feature branch");
        Sample::create(
            &conn,
            NewSample {
                name: "feature-sample",
                is_reference: false,
            },
        )
        .expect("should insert feature graph row");
        history_store
            .commit_all("feature commit")
            .expect("should commit feature graph change");
        history_store
            .checkout_branch(&BranchName("main".to_string()))
            .expect("should restore main before the history lookup");

        let feature_history = history_store
            .log_for_ref(&CommitRef("feature".to_string()), None)
            .expect("should load history from a non-current branch");

        assert_eq!(feature_history[0].message, "feature commit");
        assert_eq!(
            history_store
                .current_branch()
                .expect("should read current branch"),
            Some(BranchName("main".to_string())),
            "history lookup should not change the checkout"
        );
    }

    #[test]
    fn test_log_entries_for_hashes_loads_commits_across_branches_and_omits_missing_hashes() {
        let conn = get_connection(None).expect("should create graph database");

        Collection::create(&conn, "base-collection").expect("should insert base graph row");
        let base_commit = commit_all(&conn, "base commit").expect("should commit base change");
        create_branch(&conn, "feature").expect("should create feature branch");

        Collection::create(&conn, "main-collection").expect("should insert main graph row");
        let main_commit = commit_all(&conn, "main commit").expect("should commit main change");

        checkout(&conn, "feature").expect("should checkout feature branch");
        Collection::create(&conn, "feature-collection").expect("should insert feature graph row");
        let feature_commit =
            commit_all(&conn, "feature commit").expect("should commit feature change");
        checkout(&conn, "main").expect("should restore main branch");

        Collection::create(&conn, "uncommitted-collection")
            .expect("should insert an uncommitted graph row");
        let dirty_status = status_rows(&conn)
            .expect("should read dirty status")
            .into_iter()
            .map(|row| (row.table_name, row.staged, row.status))
            .collect::<Vec<_>>();
        assert!(!dirty_status.is_empty(), "checkout should be dirty");
        let missing_commit = DoltHashId::try_from("1111111111111111111111111111111111111111")
            .expect("should parse a missing nonzero hash");
        assert!(commit_exists(&conn, &feature_commit).expect("should find the feature commit"));
        assert!(!commit_exists(&conn, &missing_commit).expect("should query missing commit"));
        assert!(!commit_exists(&conn, &DoltHashId::default()).expect("should query zero hash"));

        let entries = log_entries_for_hashes(
            &conn,
            &[
                feature_commit,
                main_commit,
                base_commit,
                DoltHashId::default(),
                missing_commit,
                feature_commit,
            ],
        )
        .expect("should load requested commits from all repository branches");

        assert_eq!(
            entries
                .iter()
                .map(|entry| entry.commit_hash)
                .collect::<Vec<_>>(),
            vec![feature_commit, main_commit, base_commit, feature_commit],
            "all existing commits should be returned in request order while missing hashes are omitted"
        );
        assert_eq!(
            entries[0].parent_hash,
            Some(base_commit),
            "the feature commit should retain its first parent"
        );
        assert_eq!(
            entries[0].message, "feature commit",
            "the requested commit metadata should include its message"
        );
        assert_eq!(
            status_rows(&conn)
                .expect("should read status after lookup")
                .into_iter()
                .map(|row| (row.table_name, row.staged, row.status))
                .collect::<Vec<_>>(),
            dirty_status,
            "commit metadata lookup should preserve uncommitted changes"
        );
        assert!(
            Collection::exists(&conn, "uncommitted-collection"),
            "commit metadata lookup should preserve the uncommitted graph row"
        );
        assert_eq!(
            active_branch(&conn).expect("should read active branch"),
            "main",
            "commit metadata lookup should not change the active checkout"
        );
    }

    #[test]
    fn test_commit_metadata_lookup_includes_root_commit() {
        let conn = get_connection(None).expect("should create graph database");
        let root_commit = log_entries(&conn)
            .expect("should load initialized history")
            .into_iter()
            .find(|entry| entry.parent_hash.is_none())
            .expect("should contain a root commit");

        assert!(commit_exists(&conn, &root_commit.commit_hash).expect("should find root commit"));
        assert_eq!(
            log_entries_for_hashes(&conn, &[root_commit.commit_hash])
                .expect("should load root metadata"),
            vec![root_commit],
            "a commit without parents should retain its metadata"
        );
    }

    #[test]
    fn test_log_entries_for_revision_uses_dolt_commit_ranges() {
        let conn = get_connection(None).expect("should create graph database");

        Collection::create(&conn, "base-collection").expect("should insert base graph row");
        let base_commit = commit_all(&conn, "base commit").expect("should commit base change");
        create_branch(&conn, "feature").expect("should create feature branch");

        Collection::create(&conn, "main-collection").expect("should insert main graph row");
        let main_commit = commit_all(&conn, "main commit").expect("should commit main change");

        checkout(&conn, "feature").expect("should checkout feature branch");
        Collection::create(&conn, "feature-collection").expect("should insert feature graph row");
        let feature_commit =
            commit_all(&conn, "feature commit").expect("should commit feature change");
        checkout(&conn, "main").expect("should restore main branch");

        let feature_entries = log_entries_for_revision(&conn, "main..feature")
            .expect("should query the feature-only Dolt log range");
        assert_eq!(
            feature_entries
                .iter()
                .map(|entry| entry.commit_hash)
                .collect::<Vec<_>>(),
            vec![feature_commit],
            "Dolt range should return only commits unique to feature"
        );

        let main_entries = log_entries_for_revision(&conn, "feature..main")
            .expect("should query the main-only Dolt log range");
        assert_eq!(
            main_entries
                .iter()
                .map(|entry| entry.commit_hash)
                .collect::<Vec<_>>(),
            vec![main_commit],
            "reversing the Dolt range should return only commits unique to main"
        );

        let feature_from_base = log_entries_for_revision(&conn, &format!("{base_commit}..feature"))
            .expect("should query a hash-to-branch Dolt log range");
        assert_eq!(
            feature_from_base
                .iter()
                .map(|entry| entry.commit_hash)
                .collect::<Vec<_>>(),
            vec![feature_commit],
            "two-dot Dolt ranges should exclude the left revision"
        );
    }

    #[test]
    fn test_resolve_ref_errors_for_ambiguous_hash_prefix() {
        let conn = get_connection(None).expect("should create graph database");
        let history_store = DoltHistoryStore::new(&conn);
        Collection::create(&conn, "main-collection").expect("should insert initial graph row");
        let first_commit = history_store
            .commit_all("initial commit")
            .expect("should commit initial graph change");

        let mut commits = vec![first_commit];
        for index in 1..=16 {
            let sample_name = format!("sample-{index}");
            Sample::create(
                &conn,
                NewSample {
                    name: &sample_name,
                    is_reference: false,
                },
            )
            .expect("should insert graph row");
            let commit = history_store
                .commit_all(&format!("commit {index}"))
                .expect("should commit graph change");
            commits.push(commit);
        }

        let ambiguous_prefix = commits
            .iter()
            .fold(
                std::collections::HashMap::<char, usize>::new(),
                |mut counts, commit| {
                    let first_char = commit
                        .to_string()
                        .chars()
                        .next()
                        .expect("should contain at least one hex digit");
                    *counts.entry(first_char).or_default() += 1;
                    counts
                },
            )
            .into_iter()
            .find_map(|(character, count)| (count >= 2).then(|| character.to_string()))
            .expect("should find an ambiguous one-digit prefix after 17 commits");

        let err = history_store
            .resolve_ref(&CommitRef(ambiguous_prefix.clone()))
            .expect_err("ambiguous prefix should be reported as an error");
        let err_text = err.to_string();
        assert!(
            err_text.contains("ambiguous"),
            "ambiguous prefix should mention ambiguity: {err_text}"
        );
    }

    #[test]
    fn test_doltlite_sample_diff_contract() {
        let conn = get_connection(None).expect("should create graph database");

        Collection::create(&conn, "main-collection").expect("should insert collection");
        commit_all(&conn, "initial commit").expect("should commit initial graph change");
        Sample::create(
            &conn,
            NewSample {
                name: "feature-sample",
                is_reference: false,
            },
        )
        .expect("should insert sample");
        commit_all(&conn, "sample commit").expect("should commit sample change");

        let mut statement = conn
            .prepare("SELECT to_name, from_name, diff_type FROM dolt_diff_samples(?1, ?2)")
            .expect("should prepare dolt diff query");
        let mut rows = statement
            .query(["HEAD~1", "HEAD"])
            .expect("should query dolt diff rows");
        let row = rows
            .next()
            .expect("should yield a result row")
            .expect("should decode dolt diff row");
        let to_name: String = row.get(0).expect("should include the added sample name");
        let from_name: Option<String> = row.get(1).expect("should decode nullable from_name");
        let diff_type: String = row.get(2).expect("should decode diff_type");
        assert_eq!(to_name, "feature-sample");
        assert_eq!(from_name, None);
        assert_eq!(
            diff_type, "added",
            "dolt_diff_samples should label the inserted row as added"
        );
    }

    #[test]
    fn test_doltlite_annotation_asset_diff_contract() {
        let context = setup_gen_on_disk();
        let conn = context.graph().conn();
        let fixture_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../fixtures/simple.gff");

        add_annotation_file(
            &context,
            fixture_path.to_str().expect("should encode fixture path"),
            None,
            None,
            Some("fixture-track"),
            Some("annotation diff contract"),
            AnnotationFileChecksumOverrides::default(),
        )
        .expect("should commit annotation-file asset refs");

        let mut log_statement = conn
            .prepare(
                "SELECT to_id, to_operation_kind, diff_type \
                 FROM dolt_diff_gen_operation_log(?1, ?2)",
            )
            .expect("should prepare operation log diff query");
        let log_rows = log_statement
            .query_map(["HEAD~1", "HEAD"], |row| {
                Ok((
                    row.get::<_, Option<Vec<u8>>>(0)?,
                    row.get::<_, Option<OperationKind>>(1)?,
                    row.get::<_, String>(2)?,
                ))
            })
            .expect("should query operation log diffs")
            .collect::<Result<Vec<_>, _>>()
            .expect("should decode operation log diff rows");
        let log_id = log_rows
            .iter()
            .find_map(|(log_id, operation_kind, diff_type)| {
                (operation_kind.as_ref() == Some(&OperationKind::AnnotationFile)
                    && diff_type == "added")
                    .then(|| log_id.clone())
                    .flatten()
            });
        assert!(
            log_id.is_some(),
            "annotation-file commit should add a graph operation log row: {log_rows:?}"
        );
        let log_id = log_id.expect("should locate the committed log id");
        let log_id = HashId::try_from(log_id.as_slice()).expect("should decode log id");

        let mut asset_ref_statement = conn
            .prepare("SELECT diff_type FROM dolt_diff_gen_asset_refs(?1, ?2)")
            .expect("should prepare asset ref diff query");
        let asset_ref_rows = asset_ref_statement
            .query_map(["HEAD~1", "HEAD"], |row| row.get::<_, String>(0))
            .expect("should query asset ref diffs")
            .collect::<Result<Vec<_>, _>>()
            .expect("should decode asset ref diff rows");
        assert!(
            asset_ref_rows.iter().any(|diff_type| diff_type == "added"),
            "annotation-file commit should add an asset ref row: {asset_ref_rows:?}"
        );

        let committed_assets = OperationAsset::by_log_id(conn, &log_id)
            .into_iter()
            .filter_map(|asset| {
                AssetRef::select(conn)
                    .get_by_id(asset.asset_ref_id)
                    .expect("should query asset reference")
            })
            .map(|asset_ref| (asset_ref.file_type, asset_ref.role, asset_ref.name))
            .collect::<Vec<_>>();
        assert!(
            committed_assets.iter().any(|(file_type, role, name)| {
                file_type == "gff3"
                    && *role == AssetRole::Annotation
                    && name.as_deref() == Some("fixture-track")
            }),
            "committed log should resolve to the annotation asset metadata: {committed_assets:?}"
        );
    }

    #[test]
    fn test_connect_branch_restores_clean_status_after_reopen() {
        let temp_dir = tempdir().expect("should create temporary repo directory");
        let db_path = temp_dir.path().join("default.db");
        let conn = db::get_connection(&db_path).expect("should open graph database");

        Collection::create(&conn, "main-collection").expect("should insert graph row");
        commit_all(&conn, "initial commit").expect("should create initial commit");
        create_branch(&conn, "feature").expect("should create a feature branch");
        checkout(&conn, "feature").expect("should checkout feature branch");
        Sample::create(
            &conn,
            NewSample {
                name: "feature-sample",
                is_reference: false,
            },
        )
        .expect("should insert feature sample");
        commit_all(&conn, "feature commit").expect("should commit feature branch graph change");
        checkout(&conn, "main").expect("should switch back to main");
        let clean_status = status_rows(&conn).expect("should query clean status");
        assert!(
            clean_status.is_empty(),
            "checkout back to main should leave a clean working tree before reopen: {clean_status:?}"
        );
        drop(conn);

        let reopened = db::get_connection(&db_path).expect("should reopen graph database");
        connect_branch(&reopened, "main").expect("should reconnect main branch state");
        let reopened_status = status_rows(&reopened).expect("should query reopened status");
        assert!(
            reopened_status.is_empty(),
            "reopening main should keep a clean working tree: {reopened_status:?}"
        );
    }

    #[test]
    fn test_checkout_branch_created_from_relative_ref_after_copy() {
        let temp_dir = tempdir().expect("should create temporary repo directory");
        let db_path = temp_dir.path().join("default.db");
        let conn = db::get_connection(&db_path).expect("should open graph database");

        Collection::create(&conn, "main-collection").expect("should insert initial collection");
        commit_all(&conn, "initial commit").expect("should create initial commit");
        Sample::create(
            &conn,
            NewSample {
                name: "feature-sample",
                is_reference: false,
            },
        )
        .expect("should insert sample on main");
        commit_all(&conn, "sample commit").expect("should create second commit");

        let copied_dir = tempdir().expect("should create copied repo directory");
        let copied_path = copied_dir.path().join("default.db");
        std::fs::copy(&db_path, &copied_path).expect("should copy graph database");

        let copied = db::get_connection(&copied_path).expect("should open copied graph database");
        connect_branch(&copied, "main").expect("should reconnect copied main branch");
        let copied_history = DoltHistoryStore::new(&copied);
        copied_history
            .create_branch(
                &BranchName("snapshot".to_string()),
                Some(&CommitRef("main~1".to_string())),
            )
            .expect("should create a snapshot branch at the prior main commit");
        copied_history
            .checkout_branch(&BranchName("snapshot".to_string()))
            .expect("should checkout the copied snapshot branch");

        let feature_sample_exists = copied
            .query_row(
                "SELECT EXISTS(SELECT 1 FROM samples WHERE name = ?1)",
                ["feature-sample"],
                |row| row.get::<_, bool>(0),
            )
            .expect("should query copied reset sample state");
        assert!(
            !feature_sample_exists,
            "snapshot branch checkout should expose the prior commit state"
        );
    }
}